diff options
223 files changed, 0 insertions, 29073 deletions
diff --git a/TEST_MAPPING b/TEST_MAPPING index 317967bf94..0df52f054d 100644 --- a/TEST_MAPPING +++ b/TEST_MAPPING @@ -113,9 +113,6 @@ "name": "bluetooth_vc_test" }, { - "name": "bluetoothtbd_test" - }, - { "name": "bt_host_test_bta" }, { diff --git a/system/main/BUILD.gn b/system/main/BUILD.gn index a699b2fe23..c9b92158f9 100644 --- a/system/main/BUILD.gn +++ b/system/main/BUILD.gn @@ -23,8 +23,6 @@ static_library("bluetooth-static") { complete_static_lib = true sources = [ - "//bt/system/service/hal/bluetooth_interface.cc", - "//bt/system/service/logging_helpers.cc", ] configs += [ diff --git a/system/service/Android.bp b/system/service/Android.bp deleted file mode 100644 index ef579ad871..0000000000 --- a/system/service/Android.bp +++ /dev/null @@ -1,313 +0,0 @@ -package { - // See: http://go/android-license-faq - // A large-scale-change added 'default_applicable_licenses' to import - // all of the 'license_kinds' from "system_bt_license" - // to get the below license kinds: - // SPDX-license-identifier-Apache-2.0 - default_applicable_licenses: ["system_bt_license"], -} - -subdirs = [ - "common", -] - -cc_defaults { - name: "fluoride_service_defaults", - defaults: ["fluoride_defaults"], - include_dirs: [ - "packages/modules/Bluetooth/system", - "packages/modules/Bluetooth/system/gd", - ], - header_libs: ["libbluetooth_headers"], -} - -// Source variables -btserviceDaemonSrc = [ - "a2dp_sink.cc", - "a2dp_source.cc", - "adapter.cc", - "avrcp_control.cc", - "avrcp_target.cc", - "daemon.cc", - "gatt_client.cc", - "gatt_server.cc", - "gatt_server_old.cc", - "hal/bluetooth_av_interface.cc", - "hal/bluetooth_avrcp_interface.cc", - "hal/bluetooth_gatt_interface.cc", - "hal/bluetooth_interface.cc", - "ipc/ipc_handler.cc", - "ipc/ipc_manager.cc", - "logging_helpers.cc", - "low_energy_advertiser.cc", - "low_energy_scanner.cc", - "low_energy_client.cc", - "settings.cc", -] - -btserviceLinuxSrc = [ - "ipc/ipc_handler_linux.cc", - "ipc/linux_ipc_host.cc", -] - -btserviceBinderDaemonSrc = [ - "ipc/binder/bluetooth_a2dp_sink_binder_server.cc", - "ipc/binder/bluetooth_a2dp_source_binder_server.cc", - "ipc/binder/bluetooth_avrcp_control_binder_server.cc", - "ipc/binder/bluetooth_avrcp_target_binder_server.cc", - "ipc/binder/bluetooth_binder_server.cc", - "ipc/binder/bluetooth_gatt_client_binder_server.cc", - "ipc/binder/bluetooth_gatt_server_binder_server.cc", - "ipc/binder/bluetooth_le_advertiser_binder_server.cc", - "ipc/binder/bluetooth_le_scanner_binder_server.cc", - "ipc/binder/bluetooth_low_energy_binder_server.cc", - "ipc/binder/interface_with_instances_base.cc", - "ipc/binder/ipc_handler_binder.cc", -] - -// Main unit test sources. These get built for host and target. -btserviceBaseTestSrc = [ - "hal/fake_bluetooth_av_interface.cc", - "hal/fake_bluetooth_gatt_interface.cc", - "hal/fake_bluetooth_interface.cc", - "test/a2dp_sink_unittest.cc", - "test/a2dp_source_unittest.cc", - "test/adapter_unittest.cc", - "test/advertise_data_unittest.cc", - "test/fake_hal_util.cc", - "test/gatt_client_unittest.cc", - "test/gatt_server_unittest.cc", - "test/low_energy_advertiser_unittest.cc", - "test/low_energy_client_unittest.cc", - "test/low_energy_scanner_unittest.cc", - "test/settings_unittest.cc", -] - -// Native system service for target -cc_binary { - name: "bluetoothtbd", - defaults: ["fluoride_service_defaults"], - srcs: btserviceBinderDaemonSrc + - btserviceLinuxSrc + - btserviceDaemonSrc + - ["main.cc"], - static_libs: [ - "avrcp-target-service", - "libaudio-a2dp-hw-utils", - "libbluetooth-binder-common", - "libbluetooth-dumpsys", - "libbluetooth-types", - "libbt-audio-hal-interface", - "libbt-bta", - "libbt-bta-core", - "libbt-common", - "libbtcore", - "libbtdevice", - "libbte", - "libbt-hci", - "libbthalutils", - "libbtif", - "libbtif-core", - "lib-bt-packets", - "lib-bt-packets-avrcp", - "lib-bt-packets-base", - "libbt-protos-lite", - "libbt-sbc-decoder", - "libbt-sbc-encoder", - "libbt-stack", - "libbt-stack-core", - "libbt-utils", - "libc++fs", - "libchrome", - "libflatbuffers-cpp", - "libFraunhoferAAC", - "libg722codec", - "liblc3", - "libopus", - "libosi", - "libudrv-uipc", - ], - - shared_libs: [ - "android.hardware.bluetooth@1.0", - "android.hardware.bluetooth@1.1", - "android.hardware.bluetooth.a2dp@1.0", - "android.hardware.bluetooth.audio@2.0", - "android.hardware.bluetooth.audio@2.1", - "android.system.suspend.control-V1-ndk", - "android.system.suspend-V1-ndk", - "libaaudio", - "libbinder", - "libbinder_ndk", - "libcrypto", - "libcutils", - "libfmq", - "liblog", - "libprocessgroup", - "libprotobuf-cpp-lite", - "libutils", - ], - init_rc: ["bluetoothtbd.rc"], - target: { - android: { - shared_libs: [ - "android.hardware.bluetooth.audio-V3-ndk", - "libPlatformProperties", - ], - }, - }, -} - -// Native system service unit tests for target and host - -cc_test { - name: "bluetoothtbd_test", - test_suites: ["device-tests"], - defaults: [ - "fluoride_service_defaults", - "mts_defaults", - ], - srcs: btserviceBaseTestSrc + - btserviceDaemonSrc + [ - "test/main.cc", - ], - aidl: { - include_dirs: [ - "packages/modules/Bluetooth/system/service/common", - "frameworks/native/aidl/binder", - ], - }, - static_libs: [ - "android.hardware.bluetooth.a2dp@1.0", - "avrcp-target-service", - "libaudio-a2dp-hw-utils", - "libbluetooth-common", - "libbluetooth-dumpsys", - "libbluetooth-types", - "libbt-audio-hal-interface", - "libbt-bta", - "libbt-bta-core", - "libbt-common", - "libbtcore", - "libbtdevice", - "libbte", - "libbt-hci", - "libbtif", - "libbtif-core", - "lib-bt-packets", - "lib-bt-packets-avrcp", - "lib-bt-packets-base", - "libbt-protos-lite", - "libbt-sbc-decoder", - "libbt-sbc-encoder", - "libbt-stack", - "libbt-stack-core", - "libbt-utils", - "libc++fs", - "libchrome", - "libgmock", - "liblog", - "libflatbuffers-cpp", - "libFraunhoferAAC", - "libg722codec", - "liblc3", - "libopus", - "libosi", - "libudrv-uipc", - ], - shared_libs: [ - "android.hardware.bluetooth@1.0", - "android.hardware.bluetooth@1.1", - "android.hardware.bluetooth.audio@2.0", - "android.hardware.bluetooth.audio@2.1", - "libbinder_ndk", - "libcrypto", - "libfmq", - "libprocessgroup", - "libprotobuf-cpp-lite", - ], - - // host_supported: true, // TODO (b/263324289) - test_options: { - unit_test: true, - }, - target: { - // This includes Binder related tests that can only be run - // on target. - android: { - srcs: btserviceBinderDaemonSrc + [ - "test/parcelable_unittest.cc", - "test/ParcelableTest.aidl", - ], - static_libs: [ - "android.system.suspend.control-V1-ndk", - "libbluetooth-binder-common", - ], - shared_libs: [ - "android.hardware.bluetooth.audio-V3-ndk", - "android.system.suspend-V1-ndk", - "libbinder", - "libvndksupport", - "libPlatformProperties", - ], - }, - host: { - srcs: [ - "test/stub_ipc_handler_binder.cc", - ], - }, - host_linux: { - srcs: btserviceLinuxSrc + [ - // TODO(bcf): Fix this test. - //"test/ipc_linux_unittest.cc", - ], - }, - }, - sanitize: { - cfi: false, - }, -} - -// Native system service CLI for target -cc_binary { - name: "bluetooth-cli", - defaults: ["fluoride_defaults"], - srcs: ["client/main.cc"], - static_libs: [ - "libbluetooth-binder-common", - ], - shared_libs: [ - "libbinder", - "libutils", - ], -} - -// Heart Rate GATT service example for target -cc_binary { - name: "bt-example-hr-server", - defaults: ["fluoride_defaults"], - local_include_dirs: ["example/heart_rate"], - srcs: [ - "example/heart_rate/heart_rate_server.cc", - "example/heart_rate/server_main.cc", - ], - static_libs: [ - "libbluetooth-binder-common", - ], - shared_libs: [ - "libbinder", - "libutils", - ], -} - -cc_library_static { - name: "libbluetoothtbd_hal", - defaults: ["fluoride_defaults"], - include_dirs: ["packages/modules/Bluetooth/system"], - header_libs: ["libbluetooth_headers"], - srcs: [ - "hal/bluetooth_gatt_interface.cc", - "hal/bluetooth_interface.cc", - "logging_helpers.cc", - ], -} diff --git a/system/service/BUILD.gn b/system/service/BUILD.gn deleted file mode 100644 index 71ecdff87b..0000000000 --- a/system/service/BUILD.gn +++ /dev/null @@ -1,171 +0,0 @@ -# -# Copyright 2015 Google -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at: -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -config("service_config") { - include_dirs = [ - "//bt/system/", - "//bt/system/linux_include", - "//bt/system/include", - "//bt/system/service", - "//bt/system/service/common", - ] - - configs = [ "//bt/system:target_defaults" ] -} - -source_set("service_daemon_src") { - sources = [ - "a2dp_sink.cc", - "a2dp_source.cc", - "adapter.cc", - "avrcp_control.cc", - "avrcp_target.cc", - "daemon.cc", - "gatt_client.cc", - "gatt_server.cc", - "gatt_server_old.cc", - "hal/bluetooth_av_interface.cc", - "hal/bluetooth_avrcp_interface.cc", - "hal/bluetooth_gatt_interface.cc", - "hal/bluetooth_interface.cc", - "ipc/ipc_handler.cc", - "ipc/ipc_manager.cc", - "logging_helpers.cc", - "low_energy_advertiser.cc", - "low_energy_client.cc", - "low_energy_scanner.cc", - "settings.cc", - ] - - deps = [ - "//bt/system/gd/rust/shim:init_flags_bridge_header", - "//bt/system/osi", - "//bt/system/types", - ] - - configs += [ ":service_config" ] -} - -source_set("service_linux_src") { - sources = [ - "ipc/ipc_handler_linux.cc", - "ipc/linux_ipc_host.cc", - "ipc/dbus/ipc_handler_dbus.cc", - "ipc/dbus/bluetooth_adapter.cc", - ] - - deps = [ - "//bt/system/gd/rust/shim:init_flags_bridge_header", - "//bt/system/osi", - "//bt/system/types", - ] - - configs += [ ":service_config" ] -} - -static_library("service") { - sources = [ - "common/bluetooth/a2dp_codec_config.cc", - "common/bluetooth/adapter_state.cc", - "common/bluetooth/advertise_data.cc", - "common/bluetooth/advertise_settings.cc", - "common/bluetooth/avrcp_int_value.cc", - "common/bluetooth/avrcp_media_attr.cc", - "common/bluetooth/avrcp_register_notification_response.cc", - "common/bluetooth/characteristic.cc", - "common/bluetooth/descriptor.cc", - "common/bluetooth/remote_device_props.cc", - "common/bluetooth/scan_filter.cc", - "common/bluetooth/scan_result.cc", - "common/bluetooth/scan_settings.cc", - "common/bluetooth/service.cc", - "common/bluetooth/util/atomic_string.cc", - ] - - deps = [ - ":service_daemon_src", - ":service_linux_src", - "//bt/system/gd/rust/shim:init_flags_bridge_header", - "//bt/system/osi", - "//bt/system/types", - ] - - configs += [ ":service_config" ] -} - -executable("bluetoothtbd") { - sources = [ "main.cc" ] - - deps = [ - ":service", - "//bt/system/btcore", - "//bt/system/main:bluetooth", - ] - - configs += [ ":service_config" ] - - libs = [ - "dl", - "pthread", - "rt", - "bt_shim_ffi", - "ssl", - "crypto", - ] - - lib_dirs = [ - "${root_out_dir}/rust" - ] -} - -if (use.test) { - source_set("service_base_test_src") { - sources = [ - "hal/fake_bluetooth_av_interface.cc", - "hal/fake_bluetooth_gatt_interface.cc", - "hal/fake_bluetooth_interface.cc", - "test/a2dp_sink_unittest.cc", - "test/a2dp_source_unittest.cc", - "test/adapter_unittest.cc", - "test/advertise_data_unittest.cc", - "test/fake_hal_util.cc", - "test/gatt_client_unittest.cc", - "test/gatt_server_unittest.cc", - "test/low_energy_advertiser_unittest.cc", - "test/low_energy_client_unittest.cc", - "test/low_energy_scanner_unittest.cc", - "test/settings_unittest.cc", - ] - - configs += [ ":service_config" ] - } - - executable("bluetoothtbd_test") { - sources = [ "test/main.cc" ] - - deps = [ - ":service_base_test_src", - ":service_daemon_src", - ":service_linux_src", - "//bt/system/service/common:libbluetooth_common", - ] - - configs += [ - "//bt/system:external_gmock_main", - ":service_config", - ] - } -} diff --git a/system/service/a2dp_sink.cc b/system/service/a2dp_sink.cc deleted file mode 100644 index d7b3ec6585..0000000000 --- a/system/service/a2dp_sink.cc +++ /dev/null @@ -1,154 +0,0 @@ -// -// Copyright 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/a2dp_sink.h" - -#include <base/logging.h> -#include <base/memory/ptr_util.h> - -#include "service/logging_helpers.h" -#include "types/raw_address.h" - -using bluetooth::hal::BluetoothAvInterface; - -namespace bluetooth { - -// static -const int A2dpSink::kSingletonInstanceId = 0; - -A2dpSink::A2dpSink(const Uuid& uuid) : app_identifier_(uuid) { - hal::BluetoothAvInterface::Get()->AddA2dpSinkObserver(this); -} - -A2dpSink::~A2dpSink() { - hal::BluetoothAvInterface::Get()->RemoveA2dpSinkObserver(this); -} - -const Uuid& A2dpSink::GetAppIdentifier() const { return app_identifier_; } - -int A2dpSink::GetInstanceId() const { return kSingletonInstanceId; } - -void A2dpSink::SetDelegate(Delegate* delegate) { - std::lock_guard<std::mutex> lock(delegate_mutex_); - delegate_ = delegate; -} - -bool A2dpSink::Enable() { - std::lock_guard<std::mutex> lock(mutex_); - return hal::BluetoothAvInterface::Get()->A2dpSinkEnable(); -} - -void A2dpSink::Disable() { - std::lock_guard<std::mutex> lock(mutex_); - hal::BluetoothAvInterface::Get()->A2dpSinkDisable(); -} - -bool A2dpSink::Connect(const std::string& device_address) { - std::lock_guard<std::mutex> lock(mutex_); - RawAddress addr; - if (!RawAddress::FromString(device_address, addr)) { - LOG(ERROR) << "Invalid device address given: " << device_address; - return false; - } - - bt_status_t status = - hal::BluetoothAvInterface::Get()->GetA2dpSinkHALInterface()->connect( - addr); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to connect"; - return false; - } - - return true; -} - -bool A2dpSink::Disconnect(const std::string& device_address) { - std::lock_guard<std::mutex> lock(mutex_); - RawAddress addr; - if (!RawAddress::FromString(device_address, addr)) { - LOG(ERROR) << "Invalid device address given: " << device_address; - return false; - } - - bt_status_t status = - hal::BluetoothAvInterface::Get()->GetA2dpSinkHALInterface()->disconnect( - addr); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to disconnect"; - return false; - } - - return true; -} - -void A2dpSink::SetAudioFocusState(int focus_state) { - std::lock_guard<std::mutex> lock(mutex_); - hal::BluetoothAvInterface::Get() - ->GetA2dpSinkHALInterface() - ->set_audio_focus_state(focus_state); -} - -void A2dpSink::SetAudioTrackGain(float gain) { - std::lock_guard<std::mutex> lock(mutex_); - hal::BluetoothAvInterface::Get() - ->GetA2dpSinkHALInterface() - ->set_audio_track_gain(gain); -} - -void A2dpSink::ConnectionStateCallback(BluetoothAvInterface* iface, - const RawAddress& bd_addr, - btav_connection_state_t state) { - std::string device_address = BtAddrString(&bd_addr); - std::lock_guard<std::mutex> lock(delegate_mutex_); - - if (delegate_) - delegate_->OnConnectionState(device_address, static_cast<int>(state)); -} - -void A2dpSink::AudioStateCallback(BluetoothAvInterface* iface, - const RawAddress& bd_addr, - btav_audio_state_t state) { - std::string device_address = BtAddrString(&bd_addr); - std::lock_guard<std::mutex> lock(delegate_mutex_); - - if (delegate_) - delegate_->OnAudioState(device_address, static_cast<int>(state)); -} - -void A2dpSink::AudioConfigCallback(BluetoothAvInterface* iface, - const RawAddress& bd_addr, - uint32_t sample_rate, - uint8_t channel_count) { - std::string device_address = BtAddrString(&bd_addr); - std::lock_guard<std::mutex> lock(delegate_mutex_); - if (delegate_) - delegate_->OnAudioConfig(device_address, sample_rate, channel_count); -} - -// A2dpSinkFactory implementation -A2dpSinkFactory::A2dpSinkFactory() = default; -A2dpSinkFactory::~A2dpSinkFactory() = default; - -bool A2dpSinkFactory::RegisterInstance(const Uuid& uuid, - const RegisterCallback& callback) { - VLOG(1) << __func__ << " - Uuid: " << uuid.ToString(); - - auto a2dp_sink = base::WrapUnique(new A2dpSink(uuid)); - callback(BLE_STATUS_SUCCESS, uuid, std::move(a2dp_sink)); - return true; -} - -} // namespace bluetooth diff --git a/system/service/a2dp_sink.h b/system/service/a2dp_sink.h deleted file mode 100644 index 7b6f3ce7e0..0000000000 --- a/system/service/a2dp_sink.h +++ /dev/null @@ -1,103 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <atomic> -#include <mutex> -#include <string> -#include <vector> - -#include "service/bluetooth_instance.h" -#include "service/hal/bluetooth_av_interface.h" -#include "types/raw_address.h" - -namespace bluetooth { - -class A2dpSink : public BluetoothInstance, - private hal::BluetoothAvInterface::A2dpSinkObserver { - public: - // We only allow one instance of this object at a time. - static const int kSingletonInstanceId; - - class Delegate { - public: - virtual void OnConnectionState(const std::string& device_address, - int state) = 0; - virtual void OnAudioState(const std::string& device_address, int state) = 0; - virtual void OnAudioConfig(const std::string& device_address, - uint32_t sample_rate, uint8_t channel_count) = 0; - - protected: - virtual ~Delegate() = default; - }; - - A2dpSink(const A2dpSink&) = delete; - A2dpSink& operator=(const A2dpSink&) = delete; - - ~A2dpSink() override; - - void SetDelegate(Delegate* delegate); - - // BluetoothInstance implementation: - const Uuid& GetAppIdentifier() const override; - int GetInstanceId() const override; - - bool Enable(); - void Disable(); - bool Connect(const std::string& device_address); - bool Disconnect(const std::string& device_address); - void SetAudioFocusState(int focus_state); - void SetAudioTrackGain(float gain); - - private: - friend class A2dpSinkFactory; - - explicit A2dpSink(const Uuid& uuid); - - // hal::bluetooth::hal::BluetoothAvInterface::Observer implementation: - void ConnectionStateCallback(bluetooth::hal::BluetoothAvInterface* iface, - const RawAddress& bd_addr, - btav_connection_state_t state) override; - void AudioStateCallback(bluetooth::hal::BluetoothAvInterface* iface, - const RawAddress& bd_addr, - btav_audio_state_t state) override; - void AudioConfigCallback(bluetooth::hal::BluetoothAvInterface* iface, - const RawAddress& bd_addr, uint32_t sample_rate, - uint8_t channel_count) override; - - // See getters above for documentation. - const Uuid app_identifier_; - - std::mutex mutex_; - std::mutex delegate_mutex_; - Delegate* delegate_ = nullptr; -}; - -class A2dpSinkFactory : public BluetoothInstanceFactory { - public: - A2dpSinkFactory(); - A2dpSinkFactory(const A2dpSinkFactory&) = delete; - A2dpSinkFactory& operator=(const A2dpSinkFactory&) = delete; - - ~A2dpSinkFactory() override; - - // BluetoothInstanceFactory override: - bool RegisterInstance(const Uuid& uuid, - const RegisterCallback& callback) override; -}; - -} // namespace bluetooth diff --git a/system/service/a2dp_source.cc b/system/service/a2dp_source.cc deleted file mode 100644 index c77466badb..0000000000 --- a/system/service/a2dp_source.cc +++ /dev/null @@ -1,223 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/a2dp_source.h" - -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "service/logging_helpers.h" -#include "types/raw_address.h" - -#define PARSE_ADDR(str) \ - ({ \ - RawAddress tmp; \ - if (!RawAddress::FromString((str), tmp)) { \ - LOG(ERROR) << "Invalid device address given: " << (str); \ - return false; \ - } \ - tmp; \ - }) - -#define TRY_RET(expr, err_msg) \ - do { \ - if (!(expr)) { \ - LOG(ERROR) << err_msg; \ - return false; \ - } \ - return true; \ - } while (0) - -#define TRY_RET_FUNC(expr) TRY_RET(expr, __func__ << " failed") - -using bluetooth::hal::BluetoothAvInterface; -using LockGuard = std::lock_guard<std::mutex>; - -namespace bluetooth { - -namespace { - -btav_a2dp_codec_config_t CodecConfigToFluoride(const A2dpCodecConfig& config) { - btav_a2dp_codec_config_t ret = { - .codec_type = static_cast<btav_a2dp_codec_index_t>(config.codec_type()), - .codec_priority = - static_cast<btav_a2dp_codec_priority_t>(config.codec_priority()), - .sample_rate = - static_cast<btav_a2dp_codec_sample_rate_t>(config.sample_rate()), - .bits_per_sample = static_cast<btav_a2dp_codec_bits_per_sample_t>( - config.bits_per_sample()), - .channel_mode = - static_cast<btav_a2dp_codec_channel_mode_t>(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 ret; -} - -std::vector<btav_a2dp_codec_config_t> CodecConfigsToFluoride( - const std::vector<A2dpCodecConfig>& configs) { - std::vector<btav_a2dp_codec_config_t> ret; - ret.reserve(configs.size()); - for (const auto& config : configs) { - ret.push_back(CodecConfigToFluoride(config)); - } - - return ret; -} -A2dpCodecConfig FluorideCodecToCodec(const btav_a2dp_codec_config_t& config) { - A2dpCodecConfig ret(config.codec_type, config.codec_priority, - config.sample_rate, config.bits_per_sample, - config.channel_mode, config.codec_specific_1, - config.codec_specific_2, config.codec_specific_3, - config.codec_specific_4); - - return ret; -} - -std::vector<A2dpCodecConfig> FluorideCodecsToCodec( - const std::vector<btav_a2dp_codec_config_t>& configs) { - std::vector<A2dpCodecConfig> ret; - ret.reserve(configs.size()); - for (const auto& config : configs) { - ret.push_back(FluorideCodecToCodec(config)); - } - - return ret; -} - -} // namespace - -// static -const int A2dpSource::kSingletonInstanceId = 0; - -A2dpSource::A2dpSource(const Uuid& uuid) : app_identifier_(uuid) { - hal::BluetoothAvInterface::Get()->AddA2dpSourceObserver(this); -} - -A2dpSource::~A2dpSource() { - hal::BluetoothAvInterface::Get()->RemoveA2dpSourceObserver(this); -} - -const Uuid& A2dpSource::GetAppIdentifier() const { return app_identifier_; } - -int A2dpSource::GetInstanceId() const { return kSingletonInstanceId; } - -void A2dpSource::SetDelegate(Delegate* delegate) { - LockGuard lock(delegate_mutex_); - delegate_ = delegate; -} - -bool A2dpSource::Enable(const std::vector<A2dpCodecConfig>& codec_priorities) { - auto fluoride_priorities = CodecConfigsToFluoride(codec_priorities); - LockGuard lock(mutex_); - return hal::BluetoothAvInterface::Get()->A2dpSourceEnable( - fluoride_priorities); -} - -void A2dpSource::Disable() { - LockGuard lock(mutex_); - hal::BluetoothAvInterface::Get()->A2dpSourceDisable(); -} - -bool A2dpSource::Connect(const std::string& device_address) { - RawAddress addr = PARSE_ADDR(device_address); - LockGuard lock(mutex_); - TRY_RET_FUNC( - hal::BluetoothAvInterface::Get()->GetA2dpSourceHALInterface()->connect( - addr) == BT_STATUS_SUCCESS); -} - -bool A2dpSource::Disconnect(const std::string& device_address) { - RawAddress addr = PARSE_ADDR(device_address); - LockGuard lock(mutex_); - TRY_RET_FUNC( - hal::BluetoothAvInterface::Get()->GetA2dpSourceHALInterface()->disconnect( - addr) == BT_STATUS_SUCCESS); -} - -bool A2dpSource::ConfigCodec( - const std::string& device_address, - const std::vector<A2dpCodecConfig>& codec_preferences) { - RawAddress addr = PARSE_ADDR(device_address); - auto fluoride_preferences = CodecConfigsToFluoride(codec_preferences); - LockGuard lock(mutex_); - TRY_RET_FUNC(hal::BluetoothAvInterface::Get() - ->GetA2dpSourceHALInterface() - ->config_codec(addr, fluoride_preferences) == - BT_STATUS_SUCCESS); -} - -void A2dpSource::ConnectionStateCallback(BluetoothAvInterface* iface, - const RawAddress& bd_addr, - btav_connection_state_t state) { - auto device_address = BtAddrString(&bd_addr); - LockGuard lock(delegate_mutex_); - if (delegate_) - delegate_->OnConnectionState(device_address, static_cast<int>(state)); -} - -void A2dpSource::AudioStateCallback(BluetoothAvInterface* iface, - const RawAddress& bd_addr, - btav_audio_state_t state) { - auto device_address = BtAddrString(&bd_addr); - LockGuard lock(delegate_mutex_); - if (delegate_) - delegate_->OnAudioState(device_address, static_cast<int>(state)); -} - -void A2dpSource::AudioConfigCallback( - BluetoothAvInterface* iface, const RawAddress& bd_addr, - const btav_a2dp_codec_config_t& codec_config_fluoride, - const std::vector<btav_a2dp_codec_config_t> - codecs_local_capabilities_fluoride, - const std::vector<btav_a2dp_codec_config_t> - codecs_selectable_capabilities_fluoride) { - auto device_address = BtAddrString(&bd_addr); - auto codec_config = FluorideCodecToCodec(codec_config_fluoride); - auto codecs_local_capabilities = - FluorideCodecsToCodec(codecs_local_capabilities_fluoride); - auto codecs_selectable_capabilities = - FluorideCodecsToCodec(codecs_selectable_capabilities_fluoride); - LockGuard lock(delegate_mutex_); - if (delegate_) - delegate_->OnAudioConfig(device_address, codec_config, - codecs_local_capabilities, - codecs_selectable_capabilities); -} - -bool A2dpSource::MandatoryCodecPreferredCallback(BluetoothAvInterface* iface, - const RawAddress& bd_addr) { - LockGuard lock(delegate_mutex_); - // Do nothing. Optional codecs are preferred by default. - return false; -} - -// A2dpSourceFactory implementation -A2dpSourceFactory::A2dpSourceFactory() = default; -A2dpSourceFactory::~A2dpSourceFactory() = default; - -bool A2dpSourceFactory::RegisterInstance(const Uuid& uuid, - const RegisterCallback& callback) { - VLOG(1) << __func__ << " - UUID: " << uuid.ToString(); - - auto a2dp_source = base::WrapUnique(new A2dpSource(uuid)); - callback(BLE_STATUS_SUCCESS, uuid, std::move(a2dp_source)); - return true; -} - -} // namespace bluetooth diff --git a/system/service/a2dp_source.h b/system/service/a2dp_source.h deleted file mode 100644 index 5b1b554606..0000000000 --- a/system/service/a2dp_source.h +++ /dev/null @@ -1,118 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <atomic> -#include <mutex> -#include <string> -#include <vector> - -#include "service/bluetooth_instance.h" -#include "service/common/bluetooth/a2dp_codec_config.h" -#include "service/hal/bluetooth_av_interface.h" -#include "types/raw_address.h" - -namespace bluetooth { - -class A2dpSource : public BluetoothInstance, - private hal::BluetoothAvInterface::A2dpSourceObserver { - public: - // We only allow one instance of this object at a time. - static const int kSingletonInstanceId; - - class Delegate { - public: - virtual void OnConnectionState(const std::string& device_address, - int state) = 0; - virtual void OnAudioState(const std::string& device_address, int state) = 0; - virtual void OnAudioConfig( - const std::string& device_address, A2dpCodecConfig codec_config, - const std::vector<A2dpCodecConfig>& codecs_local_capabilities, - const std::vector<A2dpCodecConfig>& codecs_selectable_capabilities) = 0; - - protected: - virtual ~Delegate() = default; - }; - - A2dpSource(const A2dpSource&) = delete; - A2dpSource& operator=(const A2dpSource&) = delete; - - ~A2dpSource() override; - - void SetDelegate(Delegate* delegate); - - // BluetoothInstance implementation: - const Uuid& GetAppIdentifier() const override; - int GetInstanceId() const override; - - bool Enable(const std::vector<A2dpCodecConfig>& codec_priorities); - void Disable(); - bool Connect(const std::string& device_address); - bool Disconnect(const std::string& device_address); - bool ConfigCodec(const std::string& device_address, - const std::vector<A2dpCodecConfig>& codec_preferences); - - private: - friend class A2dpSourceFactory; - - explicit A2dpSource(const Uuid& uuid); - - // hal::bluetooth::hal::BluetoothAvInterface::Observer implementation: - void ConnectionStateCallback(hal::BluetoothAvInterface* iface, - const RawAddress& bd_addr, - btav_connection_state_t state) override; - void AudioStateCallback(hal::BluetoothAvInterface* iface, - const RawAddress& bd_addr, - btav_audio_state_t state) override; - void AudioConfigCallback( - hal::BluetoothAvInterface* iface, const RawAddress& bd_addr, - const btav_a2dp_codec_config_t& codec_config, - const std::vector<btav_a2dp_codec_config_t> codecs_local_capabilities, - const std::vector<btav_a2dp_codec_config_t> - codecs_selectable_capabilities) override; - bool MandatoryCodecPreferredCallback(hal::BluetoothAvInterface* iface, - const RawAddress& bd_addr) override; - - // For |GetAppIdentifier|. - const Uuid app_identifier_; - - std::mutex mutex_; - - // A second mutex is used only for |delegate_|. We cannot use |mutex_| because - // it may cause a deadlock if the caller and Delegate both take the same lock - // 'clock'. - // In that scenario, the caller may take 'clock' first and will try to take - // |mutex_| second. The callback will take |mutex_| first and invoke a - // delegate function which attempts to take 'clock'. - std::mutex delegate_mutex_; - Delegate* delegate_ = nullptr; -}; - -class A2dpSourceFactory : public BluetoothInstanceFactory { - public: - A2dpSourceFactory(); - A2dpSourceFactory(const A2dpSourceFactory&) = delete; - A2dpSourceFactory& operator=(const A2dpSourceFactory&) = delete; - - ~A2dpSourceFactory() override; - - // BluetoothInstanceFactory override: - bool RegisterInstance(const Uuid& uuid, - const RegisterCallback& callback) override; -}; - -} // namespace bluetooth diff --git a/system/service/adapter.cc b/system/service/adapter.cc deleted file mode 100644 index 73cf836025..0000000000 --- a/system/service/adapter.cc +++ /dev/null @@ -1,815 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/adapter.h" - -#include <base/logging.h> -#include <base/observer_list.h> - -#include <atomic> -#include <mutex> -#include <string> -#include <unordered_set> - -#include "abstract_observer_list.h" -#include "notreached.h" -#include "service/a2dp_sink.h" -#include "service/a2dp_source.h" -#include "service/avrcp_control.h" -#include "service/avrcp_target.h" -#include "service/common/bluetooth/util/atomic_string.h" -#include "service/gatt_client.h" -#include "service/gatt_server.h" -#include "service/hal/bluetooth_interface.h" -#include "service/logging_helpers.h" -#include "service/low_energy_advertiser.h" -#include "service/low_energy_client.h" -#include "service/low_energy_scanner.h" -#include "types/raw_address.h" - -using std::lock_guard; -using std::mutex; - -namespace bluetooth { - -namespace { - -RemoteDeviceProps ParseRemoteDeviceProps(int num_properties, - bt_property_t* properties) { - std::string name; - std::string address; - std::vector<Uuid> service_uuids; - int32_t device_class = 0; - int32_t device_type = 0; - int32_t rssi = 0; - - for (int i = 0; i < num_properties; ++i) { - bt_property_t* property = properties + i; - switch (property->type) { - case BT_PROPERTY_BDNAME: { - if (property->len < 0) { - NOTREACHED() << "Invalid length for BT_PROPERTY_BDNAME"; - break; - } - bt_bdname_t* hal_name = reinterpret_cast<bt_bdname_t*>(property->val); - name = reinterpret_cast<char*>(hal_name->name); - break; - } - case BT_PROPERTY_BDADDR: { - if (property->len != sizeof(RawAddress)) { - NOTREACHED() << "Invalid length for BT_PROPERTY_BDADDR"; - break; - } - address = BtAddrString(reinterpret_cast<RawAddress*>(property->val)); - break; - } - case BT_PROPERTY_UUIDS: { - if (property->len < 0) { - NOTREACHED() << "Negative length on BT_PROPERTY_UUIDS:"; - break; - } - if (property->len % sizeof(Uuid) != 0) { - NOTREACHED() << "Trailing bytes on BT_PROPERTY_UUIDS:"; - } - auto uuids = static_cast<const Uuid*>(property->val); - - for (size_t i = 0; i < property->len / sizeof(Uuid); ++i) { - service_uuids.push_back(uuids[i]); - } - break; - } - case BT_PROPERTY_CLASS_OF_DEVICE: { - if (property->len != sizeof(int32_t)) { - NOTREACHED() << "Invalid length for BT_PROPERTY_CLASS_OF_DEVICE"; - break; - } - device_class = *reinterpret_cast<const int32_t*>(property->val); - break; - } - case BT_PROPERTY_TYPE_OF_DEVICE: { - if (property->len != sizeof(int32_t)) { - NOTREACHED() << "Invalid length for BT_PROPERTY_TYPE_OF_DEVICE"; - break; - } - device_type = *reinterpret_cast<const int32_t*>(property->val); - break; - } - case BT_PROPERTY_REMOTE_RSSI: { - if (property->len != sizeof(int8_t)) { - NOTREACHED() << "Invalid length for BT_PROPERTY_REMOTE_RSSI"; - break; - } - rssi = *reinterpret_cast<const int8_t*>(property->val); - break; - } - default: - VLOG(1) << "Unhandled adapter property: " - << BtPropertyText(property->type); - break; - } - } - - return RemoteDeviceProps(name, address, service_uuids, device_class, - device_type, rssi); -} - -} // namespace - -// static -const char Adapter::kDefaultAddress[] = "00:00:00:00:00:00"; -// static -const char Adapter::kDefaultName[] = "not-initialized"; - -// TODO(armansito): The following constants come straight from -// packages/apps/Bluetooth/src/c/a/b/btservice/AdapterService.java. It would be -// nice to know if there were a way to obtain these values from the stack -// instead of hardcoding them here. - -// The minimum number of advertising instances required for multi-advertisement -// support. -const int kMinAdvInstancesForMultiAdv = 5; - -// Used when determining if offloaded scan filtering is supported. -const int kMinOffloadedFilters = 10; - -// Used when determining if offloaded scan batching is supported. -const int kMinOffloadedScanStorageBytes = 1024; - -void Adapter::Observer::OnAdapterStateChanged(Adapter* adapter, - AdapterState prev_state, - AdapterState new_state) { - // Default implementation does nothing -} - -void Adapter::Observer::OnDeviceConnectionStateChanged( - Adapter* adapter, const std::string& device_address, bool connected) { - // Default implementation does nothing -} - -void Adapter::Observer::OnScanEnableChanged(Adapter* adapter, - bool scan_enabled) { - // Default implementation does nothing -} - -void Adapter::Observer::OnSspRequest(Adapter* adapter, - const std::string& device_address, - const std::string& device_name, int cod, - int pairing_variant, int pass_key) { - // Default implementation does nothing -} - -void Adapter::Observer::OnBondStateChanged(Adapter* adapter, int status, - const std::string& device_address, - int state) { - // Default implementation does nothing -} - -void Adapter::Observer::OnGetBondedDevices( - Adapter* adapter, int status, - const std::vector<std::string>& bonded_devices) { - // Default implementation does nothing -} - -void Adapter::Observer::OnGetRemoteDeviceProperties( - Adapter* adapter, int status, const std::string& device_address, - const RemoteDeviceProps& properties) { - // Default implementation does nothing -} - -void Adapter::Observer::OnDeviceFound(Adapter* adapter, - const RemoteDeviceProps& properties) { - // Default implementation does nothing -} - -// The real Adapter implementation used in production. -class AdapterImpl : public Adapter, public hal::BluetoothInterface::Observer { - public: - AdapterImpl() - : state_(ADAPTER_STATE_OFF), - address_(kDefaultAddress), - name_(kDefaultName) { - memset(&local_le_features_, 0, sizeof(local_le_features_)); - hal::BluetoothInterface::Get()->AddObserver(this); - a2dp_sink_factory_.reset(new A2dpSinkFactory); - a2dp_source_factory_.reset(new A2dpSourceFactory); - avrcp_control_factory_.reset(new AvrcpControlFactory); - avrcp_target_factory_.reset(new AvrcpTargetFactory); - ble_client_factory_.reset(new LowEnergyClientFactory(*this)); - ble_advertiser_factory_.reset(new LowEnergyAdvertiserFactory()); - ble_scanner_factory_.reset(new LowEnergyScannerFactory(*this)); - gatt_client_factory_.reset(new GattClientFactory()); - gatt_server_factory_.reset(new GattServerFactory()); - hal::BluetoothInterface::Get()->GetHALInterface()->get_adapter_properties(); - } - - AdapterImpl(const AdapterImpl&) = delete; - AdapterImpl& operator=(const AdapterImpl&) = delete; - - ~AdapterImpl() override { - hal::BluetoothInterface::Get()->RemoveObserver(this); - } - - void AddObserver(Adapter::Observer* observer) override { - lock_guard<mutex> lock(observers_lock_); - observers_.AddObserver(observer); - } - - void RemoveObserver(Adapter::Observer* observer) override { - lock_guard<mutex> lock(observers_lock_); - observers_.RemoveObserver(observer); - } - - AdapterState GetState() const override { return state_.load(); } - - bool IsEnabled() const override { return state_.load() == ADAPTER_STATE_ON; } - - bool Enable() override { - AdapterState current_state = GetState(); - if (current_state != ADAPTER_STATE_OFF) { - LOG(INFO) << "Adapter not disabled - state: " - << AdapterStateToString(current_state); - return false; - } - - // Set the state before calling enable() as there might be a race between - // here and the AdapterStateChangedCallback. - state_ = ADAPTER_STATE_TURNING_ON; - NotifyAdapterStateChanged(current_state, state_); - - int status = hal::BluetoothInterface::Get()->GetHALInterface()->enable(); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to enable Bluetooth - status: " - << BtStatusText((const bt_status_t)status); - state_ = ADAPTER_STATE_OFF; - NotifyAdapterStateChanged(ADAPTER_STATE_TURNING_ON, state_); - return false; - } - - return true; - } - - bool Disable() override { - if (!IsEnabled()) { - LOG(INFO) << "Adapter is not enabled"; - return false; - } - - AdapterState current_state = GetState(); - - // Set the state before calling enable() as there might be a race between - // here and the AdapterStateChangedCallback. - state_ = ADAPTER_STATE_TURNING_OFF; - NotifyAdapterStateChanged(current_state, state_); - - int status = hal::BluetoothInterface::Get()->GetHALInterface()->disable(); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to disable Bluetooth - status: " - << BtStatusText((const bt_status_t)status); - state_ = current_state; - NotifyAdapterStateChanged(ADAPTER_STATE_TURNING_OFF, state_); - return false; - } - - return true; - } - - std::string GetName() const override { return name_.Get(); } - - bool SetName(const std::string& name) override { - bt_bdname_t hal_name; - size_t max_name_len = sizeof(hal_name.name); - - // Include the \0 byte in size measurement. - if (name.length() >= max_name_len) { - LOG(ERROR) << "Given name \"" << name << "\" is larger than maximum" - << " allowed size: " << max_name_len; - return false; - } - - strncpy(reinterpret_cast<char*>(hal_name.name), name.c_str(), - name.length() + 1); - - VLOG(1) << "Setting adapter name: " << name; - - if (!SetAdapterProperty(BT_PROPERTY_BDNAME, &hal_name, sizeof(hal_name))) { - LOG(ERROR) << "Failed to set adapter name: " << name; - return false; - } - - return true; - } - - std::string GetAddress() const override { return address_.Get(); } - - bool SetScanMode(int scan_mode) override { - switch (scan_mode) { - case BT_SCAN_MODE_NONE: - case BT_SCAN_MODE_CONNECTABLE: - case BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE: - break; - default: - LOG(ERROR) << "Unknown scan mode: " << scan_mode; - return false; - } - - auto bd_scanmode = static_cast<bt_scan_mode_t>(scan_mode); - - if (!SetAdapterProperty(BT_PROPERTY_ADAPTER_SCAN_MODE, &bd_scanmode, - sizeof(bd_scanmode))) { - LOG(ERROR) << "Failed to set scan mode to : " << scan_mode; - return false; - } - - return true; - } - - bool SetScanEnable(bool scan_enable) override { - if (scan_enable) { - int status = - hal::BluetoothInterface::Get()->GetHALInterface()->start_discovery(); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to enable scanning"; - return false; - } - } else { - int status = - hal::BluetoothInterface::Get()->GetHALInterface()->cancel_discovery(); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to disable scanning"; - return false; - } - } - return true; - } - - bool SspReply(const std::string& device_address, int variant, bool accept, - int32_t pass_key) override { - RawAddress addr; - if (!RawAddress::FromString(device_address, addr)) { - LOG(ERROR) << "Invalid device address given: " << device_address; - return false; - } - - int status = hal::BluetoothInterface::Get()->GetHALInterface()->ssp_reply( - &addr, static_cast<bt_ssp_variant_t>(variant), accept, pass_key); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to send SSP response - status: " - << BtStatusText((const bt_status_t)status); - return false; - } - - return true; - } - - bool CreateBond(const std::string& device_address, int transport) override { - RawAddress addr; - if (!RawAddress::FromString(device_address, addr)) { - LOG(ERROR) << "Invalid device address given: " << device_address; - return false; - } - - int status = hal::BluetoothInterface::Get()->GetHALInterface()->create_bond( - &addr, transport); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to create bond - status: " - << BtStatusText((const bt_status_t)status); - return false; - } - - return true; - } - - bool IsMultiAdvertisementSupported() override { - lock_guard<mutex> lock(local_le_features_lock_); - return local_le_features_.max_adv_instance >= kMinAdvInstancesForMultiAdv; - } - - bool IsDeviceConnected(const std::string& device_address) override { - lock_guard<mutex> lock(connected_devices_lock_); - return connected_devices_.find(device_address) != connected_devices_.end(); - } - - int GetTotalNumberOfTrackableAdvertisements() override { - lock_guard<mutex> lock(local_le_features_lock_); - return local_le_features_.total_trackable_advertisers; - } - - bool IsOffloadedFilteringSupported() override { - lock_guard<mutex> lock(local_le_features_lock_); - return local_le_features_.max_adv_filter_supported >= kMinOffloadedFilters; - } - - bool IsOffloadedScanBatchingSupported() override { - lock_guard<mutex> lock(local_le_features_lock_); - return local_le_features_.scan_result_storage_size >= - kMinOffloadedScanStorageBytes; - } - - bool GetBondedDevices() override { - int status = - hal::BluetoothInterface::Get()->GetHALInterface()->get_adapter_property( - BT_PROPERTY_ADAPTER_BONDED_DEVICES); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to get bonded devices. Status: " - << BtStatusText(static_cast<bt_status_t>(status)); - return false; - } - - return true; - } - - bool RemoveBond(const std::string& device_address) override { - RawAddress addr; - if (!RawAddress::FromString(device_address, addr)) { - LOG(ERROR) << "Invalid device address given: " << device_address; - return false; - } - - int status = - hal::BluetoothInterface::Get()->GetHALInterface()->remove_bond(&addr); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to send remove bond - status: " - << BtStatusText(static_cast<bt_status_t>(status)); - return false; - } - - return true; - } - - bool GetRemoteDeviceProperties(const std::string& device_address) override { - RawAddress addr; - if (!RawAddress::FromString(device_address, addr)) { - LOG(ERROR) << "Invalid device address given: " << device_address; - return false; - } - - int status = hal::BluetoothInterface::Get() - ->GetHALInterface() - ->get_remote_device_properties(&addr); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to send GetRemoteDeviceProperties - status: " - << BtStatusText((const bt_status_t)status); - return false; - } - - return true; - } - - A2dpSinkFactory* GetA2dpSinkFactory() const override { - return a2dp_sink_factory_.get(); - } - - A2dpSourceFactory* GetA2dpSourceFactory() const override { - return a2dp_source_factory_.get(); - } - - AvrcpControlFactory* GetAvrcpControlFactory() const override { - return avrcp_control_factory_.get(); - } - - AvrcpTargetFactory* GetAvrcpTargetFactory() const override { - return avrcp_target_factory_.get(); - } - - LowEnergyClientFactory* GetLowEnergyClientFactory() const override { - return ble_client_factory_.get(); - } - - LowEnergyAdvertiserFactory* GetLeAdvertiserFactory() const override { - return ble_advertiser_factory_.get(); - } - - LowEnergyScannerFactory* GetLeScannerFactory() const override { - return ble_scanner_factory_.get(); - } - - GattClientFactory* GetGattClientFactory() const override { - return gatt_client_factory_.get(); - } - - GattServerFactory* GetGattServerFactory() const override { - return gatt_server_factory_.get(); - } - - // hal::BluetoothInterface::Observer overrides. - void AdapterStateChangedCallback(bt_state_t state) override { - LOG(INFO) << "Adapter state changed: " << BtStateText(state); - - AdapterState prev_state = GetState(); - - switch (state) { - case BT_STATE_OFF: - state_ = ADAPTER_STATE_OFF; - break; - - case BT_STATE_ON: - state_ = ADAPTER_STATE_ON; - break; - - default: - NOTREACHED(); - } - - NotifyAdapterStateChanged(prev_state, GetState()); - } - - void AdapterPropertiesCallback(bt_status_t status, int num_properties, - bt_property_t* properties) override { - LOG(INFO) << "Adapter properties changed"; - - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "status: " << BtStatusText(status); - - for (int i = 0; i < num_properties; ++i) { - bt_property_t* property = properties + i; - if (property->type == BT_PROPERTY_ADAPTER_BONDED_DEVICES) { - lock_guard<mutex> lock(observers_lock_); - for (auto& observer : observers_) { - observer.OnGetBondedDevices(this, status, {}); - } - } - } - return; - } - - for (int i = 0; i < num_properties; i++) { - bt_property_t* property = properties + i; - switch (property->type) { - case BT_PROPERTY_BDADDR: { - std::string address = - BtAddrString(reinterpret_cast<RawAddress*>(property->val)); - LOG(INFO) << "Adapter address changed: " << address; - address_.Set(address); - break; - } - case BT_PROPERTY_BDNAME: { - bt_bdname_t* hal_name = reinterpret_cast<bt_bdname_t*>(property->val); - if (hal_name) { - std::string name = reinterpret_cast<char*>(hal_name->name); - LOG(INFO) << "Adapter name changed: " << name; - name_.Set(name); - } - break; - } - case BT_PROPERTY_LOCAL_LE_FEATURES: { - lock_guard<mutex> lock(local_le_features_lock_); - if (property->len != sizeof(bt_local_le_features_t)) { - LOG(WARNING) << "Malformed value received for property: " - << "BT_PROPERTY_LOCAL_LE_FEATURES"; - break; - } - bt_local_le_features_t* features = - reinterpret_cast<bt_local_le_features_t*>(property->val); - memcpy(&local_le_features_, features, sizeof(*features)); - LOG(INFO) << "Supported LE features updated"; - break; - } - case BT_PROPERTY_ADAPTER_BONDED_DEVICES: { - if (property->len < 0) { - NOTREACHED() << "Negative property length"; - break; - } - auto addrs = reinterpret_cast<const RawAddress*>(property->val); - if (property->len % sizeof(addrs[0]) != 0) { - LOG(ERROR) << "Invalid property length: " << property->len; - // TODO(bcf): Seems to be a bug where we hit this somewhat - // frequently. - break; - } - std::vector<std::string> str_addrs; - - for (size_t i = 0; i < property->len / sizeof(addrs[0]); ++i) - str_addrs.push_back(BtAddrString(addrs + i)); - - lock_guard<mutex> lock(observers_lock_); - for (auto& observer : observers_) { - observer.OnGetBondedDevices(this, status, str_addrs); - } - break; - } - default: - VLOG(1) << "Unhandled adapter property: " - << BtPropertyText(property->type); - break; - } - - // TODO(armansito): notify others of the updated properties - } - } - - void RemoteDevicePropertiesCallback(bt_status_t status, - RawAddress* remote_bdaddr, - int num_properties, - bt_property_t* properties) override { - std::string device_address = BtAddrString(remote_bdaddr); - if (status != BT_STATUS_SUCCESS) { - lock_guard<mutex> lock(observers_lock_); - for (auto& observer : observers_) { - observer.OnGetRemoteDeviceProperties(this, status, device_address, - RemoteDeviceProps()); - } - return; - } - - RemoteDeviceProps props = - ParseRemoteDeviceProps(num_properties, properties); - - std::string address = BtAddrString(remote_bdaddr); - props.set_address(address); - - lock_guard<mutex> lock(observers_lock_); - for (auto& observer : observers_) { - observer.OnGetRemoteDeviceProperties(this, status, device_address, props); - } - } - - void DeviceFoundCallback(int num_properties, - bt_property_t* properties) override { - RemoteDeviceProps props = - ParseRemoteDeviceProps(num_properties, properties); - - lock_guard<mutex> lock(observers_lock_); - for (auto& observer : observers_) { - observer.OnDeviceFound(this, props); - } - } - - void DiscoveryStateChangedCallback(bt_discovery_state_t state) override { - bool enabled = false; - switch (state) { - case BT_DISCOVERY_STOPPED: - enabled = false; - break; - case BT_DISCOVERY_STARTED: - enabled = true; - break; - default: - NOTREACHED(); - } - - for (auto& observer : observers_) { - observer.OnScanEnableChanged(this, enabled); - } - } - - void SSPRequestCallback(RawAddress* remote_bdaddr, bt_bdname_t* bd_name, - uint32_t cod, bt_ssp_variant_t pairing_variant, - uint32_t pass_key) override { - std::string device_address = BtAddrString(remote_bdaddr); - std::string name = reinterpret_cast<char*>(bd_name->name); - - lock_guard<mutex> lock(observers_lock_); - for (auto& observer : observers_) { - observer.OnSspRequest(this, device_address, name, cod, pairing_variant, - pass_key); - } - } - - void BondStateChangedCallback(bt_status_t status, RawAddress* remote_bdaddr, - bt_bond_state_t state, - int fail_reason) override { - std::string device_address = BtAddrString(remote_bdaddr); - - lock_guard<mutex> lock(observers_lock_); - for (auto& observer : observers_) { - observer.OnBondStateChanged(this, status, device_address, state); - } - } - - void AclStateChangedCallback(bt_status_t status, - const RawAddress& remote_bdaddr, - 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) override { - std::string device_address = BtAddrString(&remote_bdaddr); - bool connected = (state == BT_ACL_STATE_CONNECTED); - LOG(INFO) << "ACL state changed: " << device_address - << " - connected: " << (connected ? "true" : "false"); - - // If this is reported with an error status, I suppose the best thing we can - // do is to log it and ignore the event. - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "status: " << BtStatusText(status); - return; - } - - // Introduce a scope to manage |connected_devices_lock_| with RAII. - { - lock_guard<mutex> lock(connected_devices_lock_); - if (connected) - connected_devices_.insert(device_address); - else - connected_devices_.erase(device_address); - } - - lock_guard<mutex> lock(observers_lock_); - for (auto& observer : observers_) { - observer.OnDeviceConnectionStateChanged(this, device_address, connected); - } - } - - // Sends a request to set the given HAL adapter property type and value. - bool SetAdapterProperty(bt_property_type_t type, void* value, int length) { - CHECK(length > 0); - CHECK(value); - - bt_property_t property; - property.len = length; - property.val = value; - property.type = type; - - int status = - hal::BluetoothInterface::Get()->GetHALInterface()->set_adapter_property( - &property); - if (status != BT_STATUS_SUCCESS) { - VLOG(1) << "Failed to set property"; - return false; - } - - return true; - } - - // Helper for invoking the AdapterStateChanged observer method. - void NotifyAdapterStateChanged(AdapterState prev_state, - AdapterState new_state) { - if (prev_state == new_state) return; - - lock_guard<mutex> lock(observers_lock_); - for (auto& observer : observers_) { - observer.OnAdapterStateChanged(this, prev_state, new_state); - } - } - - private: - // The current adapter state. - std::atomic<AdapterState> state_; - - // The Bluetooth device address of the local adapter in string from - // (i.e.. XX:XX:XX:XX:XX:XX) - util::AtomicString address_; - - // The current local adapter name. - util::AtomicString name_; - - // The current set of supported LE features as obtained from the stack. The - // values here are all initially set to 0 and updated when the corresponding - // adapter property has been received from the stack. - std::mutex local_le_features_lock_; - bt_local_le_features_t local_le_features_; - - // List of observers that are interested in notifications from us. - std::mutex observers_lock_; - btbase::AbstractObserverList<Adapter::Observer> observers_; - - // List of devices addresses that are currently connected. - std::mutex connected_devices_lock_; - std::unordered_set<std::string> connected_devices_; - - // Factory used to create per-app A2dpSink instances. - std::unique_ptr<A2dpSinkFactory> a2dp_sink_factory_; - - // Factory used to create per-app A2dpSource instances. - std::unique_ptr<A2dpSourceFactory> a2dp_source_factory_; - - // Factory used to create per-app AvrcpControl instances. - std::unique_ptr<AvrcpControlFactory> avrcp_control_factory_; - - // Factory used to create per-app AvrcpTarget instances. - std::unique_ptr<AvrcpTargetFactory> avrcp_target_factory_; - - // Factory used to create per-app LowEnergyClient instances. - std::unique_ptr<LowEnergyClientFactory> ble_client_factory_; - - // Factory used to create per-app LeAdvertiser instances. - std::unique_ptr<LowEnergyAdvertiserFactory> ble_advertiser_factory_; - - // Factory used to create per-app LeScanner instances. - std::unique_ptr<LowEnergyScannerFactory> ble_scanner_factory_; - - // Factory used to create per-app GattClient instances. - std::unique_ptr<GattClientFactory> gatt_client_factory_; - - // Factory used to create per-app GattServer instances. - std::unique_ptr<GattServerFactory> gatt_server_factory_; -}; - -// static -std::unique_ptr<Adapter> Adapter::Create() { - return std::unique_ptr<Adapter>(new AdapterImpl()); -} - -} // namespace bluetooth diff --git a/system/service/adapter.h b/system/service/adapter.h deleted file mode 100644 index e3fa306cf1..0000000000 --- a/system/service/adapter.h +++ /dev/null @@ -1,227 +0,0 @@ -// -// Copyright (C) 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <memory> -#include <string> -#include <vector> - -#include "service/common/bluetooth/adapter_state.h" -#include "service/common/bluetooth/remote_device_props.h" - -namespace bluetooth { - -class A2dpSinkFactory; -class A2dpSourceFactory; -class AvrcpControlFactory; -class AvrcpTargetFactory; -class GattClientFactory; -class GattServerFactory; -class LowEnergyAdvertiserFactory; -class LowEnergyScannerFactory; -class LowEnergyClientFactory; - -// Represents the local Bluetooth adapter. -class Adapter { - public: - // The default values returned before the Adapter is fully initialized and - // powered. The complete values for these fields are obtained following a - // successful call to "Enable". - static const char kDefaultAddress[]; - static const char kDefaultName[]; - - // Observer interface allows other classes to receive notifications from us. - // All of the methods in this interface are declared as optional to allow - // different layers to process only those events that they are interested in. - // - // All methods take in an |adapter| argument which points to the Adapter - // object that the Observer instance was added to. - class Observer { - public: - virtual ~Observer() = default; - - // Called when there is a change in the state of the local Bluetooth - // |adapter| from |prev_state| to |new_state|. - virtual void OnAdapterStateChanged(Adapter* adapter, - AdapterState prev_state, - AdapterState new_state); - - // Called when there is a change in the connection state between the local - // |adapter| and a remote device with address |device_address|. If the ACL - // state changes from disconnected to connected, then |connected| will be - // true and vice versa. - virtual void OnDeviceConnectionStateChanged( - Adapter* adapter, const std::string& device_address, bool connected); - - // Called when scanning is enabled or disabled. - virtual void OnScanEnableChanged(Adapter* adapter, bool scan_enabled); - - // Called when a SSP pairing request comes from a remote device. - virtual void OnSspRequest(Adapter* adapter, - const std::string& device_address, - const std::string& device_name, int cod, - int pairing_variant, int pass_key); - - // Called when a remote device bond state changes. - virtual void OnBondStateChanged(Adapter* adapter, int status, - const std::string& device_address, - int state); - - // Called in response to |GetBondedDevices|. - virtual void OnGetBondedDevices( - Adapter* adapter, int status, - const std::vector<std::string>& bonded_devices); - - // Called in response to |GetRemoteDeviceProperties|. - virtual void OnGetRemoteDeviceProperties(Adapter* adapter, int status, - const std::string& device_address, - const RemoteDeviceProps& props); - - // Called when a device is found through scanning. - virtual void OnDeviceFound(Adapter* adapter, - const RemoteDeviceProps& props); - }; - - // Returns an Adapter implementation to be used in production. Don't use these - // in tests; use MockAdapter instead. - static std::unique_ptr<Adapter> Create(); - - Adapter(const Adapter&) = delete; - Adapter& operator=(const Adapter&) = delete; - - virtual ~Adapter() = default; - - // Add or remove an observer. - virtual void AddObserver(Observer* observer) = 0; - virtual void RemoveObserver(Observer* observer) = 0; - - // Returns the current Adapter state. - virtual AdapterState GetState() const = 0; - - // Returns true, if the adapter radio is current powered. - virtual bool IsEnabled() const = 0; - - // Enables Bluetooth. This method will send a request to the Bluetooth adapter - // to power up its radio. Returns true, if the request was successfully sent - // to the controller, otherwise returns false. A successful call to this - // method only means that the enable request has been sent to the Bluetooth - // controller and does not imply that the operation itself succeeded. - virtual bool Enable() = 0; - - // Powers off the Bluetooth radio. Returns true, if the disable request was - // successfully sent to the Bluetooth controller. - virtual bool Disable() = 0; - - // Returns the name currently assigned to the local adapter. - virtual std::string GetName() const = 0; - - // Sets the name assigned to the local Bluetooth adapter. This is the name - // that the local controller will present to remote devices. - virtual bool SetName(const std::string& name) = 0; - - // Returns the local adapter addess in string form (XX:XX:XX:XX:XX:XX). - virtual std::string GetAddress() const = 0; - - // Set discoverability mode. - virtual bool SetScanMode(int scan_mode) = 0; - - // Enable or disable discoverability. - virtual bool SetScanEnable(bool scan_enable) = 0; - - // Reply to an SSP request received in |OnSspRequest|. - virtual bool SspReply(const std::string& device_address, int variant, - bool accept, int32_t pass_key) = 0; - - // Create a bond with device specified by |device_address|. - virtual bool CreateBond(const std::string& device_address, int transport) = 0; - - // Returns true if the local adapter supports the Low-Energy - // multi-advertisement feature. - virtual bool IsMultiAdvertisementSupported() = 0; - - // Returns true if the remote device with address |device_address| is - // currently connected. This is not a const method as it modifies the state of - // the associated internal mutex. - virtual bool IsDeviceConnected(const std::string& device_address) = 0; - - // Returns the total number of trackable advertisements as supported by the - // underlying hardware. - virtual int GetTotalNumberOfTrackableAdvertisements() = 0; - - // Returns true if hardware-backed scan filtering is supported. - virtual bool IsOffloadedFilteringSupported() = 0; - - // Returns true if hardware-backed batch scanning is supported. - virtual bool IsOffloadedScanBatchingSupported() = 0; - - // When the stack call completes, |OnGetBondedDevices| will be called. - virtual bool GetBondedDevices() = 0; - - // When the stack call completets, |OnBondStateChanged| will be called. - virtual bool RemoveBond(const std::string& device_address) = 0; - - // When the stack call completets, |OnGetRemoteDeviceProperties| will be - // called. - virtual bool GetRemoteDeviceProperties(const std::string& device_address) = 0; - - // Returns a pointer to the A2dpSinkFactory. This can be used to - // register per-application A2dpSinkClient instances to perform A2DP sink - // operations. - virtual A2dpSinkFactory* GetA2dpSinkFactory() const = 0; - - // Returns a pointer to the A2dpSourceFactory. This can be used to - // register per-application A2dpSourceClient instances to perform A2DP source - // operations. - virtual A2dpSourceFactory* GetA2dpSourceFactory() const = 0; - - // Returns a pointer to the AvrcpControlFactory. This can be used to register - // per-application AvrcpControlClient instances to perform AVRCP control - // operations. - virtual AvrcpControlFactory* GetAvrcpControlFactory() const = 0; - - // Returns a pointer to the AvrcpTargetFactory. This can be used to register - // per-application AvrcpTargetClient instances to perform AVRCP target - // operations. - virtual AvrcpTargetFactory* GetAvrcpTargetFactory() const = 0; - - // Returns a pointer to the LowEnergyClientFactory. This can be used to - // register per-application LowEnergyClient instances to perform BLE GAP - // operations. - virtual LowEnergyClientFactory* GetLowEnergyClientFactory() const = 0; - - // Returns a pointer to the LowEnergyScannerFactory. This can be used to - // register per-application LowEnergyScanner instances to perform scanning. - virtual LowEnergyScannerFactory* GetLeScannerFactory() const = 0; - - // Returns a pointer to the LowEnergyAdvertiserFactory. This can be used to - // register per-application LowEnergyAdvertiser instances to perform - // advertising. - virtual LowEnergyAdvertiserFactory* GetLeAdvertiserFactory() const = 0; - - // Returns a pointer to the GattClientFactory. This can be used to register - // per-application GATT server instances. - virtual GattClientFactory* GetGattClientFactory() const = 0; - - // Returns a pointer to the GattServerFactory. This can be used to register - // per-application GATT server instances. - virtual GattServerFactory* GetGattServerFactory() const = 0; - - protected: - Adapter() = default; -}; - -} // namespace bluetooth diff --git a/system/service/avrcp_control.cc b/system/service/avrcp_control.cc deleted file mode 100644 index 1e4c24ae4a..0000000000 --- a/system/service/avrcp_control.cc +++ /dev/null @@ -1,230 +0,0 @@ -// -// Copyright 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/avrcp_control.h" - -#include <base/logging.h> -#include <base/memory/ptr_util.h> -#include <base/strings/string_number_conversions.h> - -#include <cerrno> -#include <climits> -#include <string> - -#include "notreached.h" -#include "service/logging_helpers.h" -#include "stack/include/avrc_defs.h" -#include "types/raw_address.h" - -namespace bluetooth { - -AvrcpControl::AvrcpControl(const Uuid& uuid, int control_id) - : app_identifier_(uuid), control_id_(control_id) { - hal::BluetoothAvrcpInterface::Get()->AddControlObserver(this); -} - -AvrcpControl::~AvrcpControl() { - hal::BluetoothAvrcpInterface::Get()->RemoveControlObserver(this); -} - -const Uuid& AvrcpControl::GetAppIdentifier() const { return app_identifier_; } - -int AvrcpControl::GetInstanceId() const { return control_id_; } - -void AvrcpControl::SetDelegate(Delegate* delegate) { - std::lock_guard<std::mutex> lock(delegate_mutex_); - delegate_ = delegate; -} - -bool AvrcpControl::Enable() { - std::lock_guard<std::mutex> lock(mutex_); - return hal::BluetoothAvrcpInterface::Get()->AvrcpControlEnable(); -} - -void AvrcpControl::Disable() { - std::lock_guard<std::mutex> lock(mutex_); - hal::BluetoothAvrcpInterface::Get()->AvrcpControlDisable(); -} - -bool AvrcpControl::SendPassThroughCommand(const std::string& device_address, - uint8_t key_code, bool key_pressed) { - RawAddress addr; - if (!RawAddress::FromString(device_address, addr)) { - LOG(ERROR) << "Invalid device address given: " << device_address; - return false; - } - - uint8_t key_state = key_pressed ? AVRC_STATE_PRESS : AVRC_STATE_RELEASE; - bt_status_t status; - { - std::lock_guard<std::mutex> lock(mutex_); - status = hal::BluetoothAvrcpInterface::Get() - ->GetControlHALInterface() - ->send_pass_through_cmd(addr, key_code, key_state); - } - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to send passthrough command"; - return false; - } - - return true; -} - -bool AvrcpControl::SetAbsVolumeResponse(const std::string& device_address, - int32_t abs_vol, int32_t label) { - RawAddress addr; - if (!RawAddress::FromString(device_address, addr)) { - LOG(ERROR) << "Invalid device address given: " << device_address; - return false; - } - - bt_status_t status; - { - std::lock_guard<std::mutex> lock(mutex_); - status = hal::BluetoothAvrcpInterface::Get() - ->GetControlHALInterface() - ->set_volume_rsp(addr, abs_vol, label); - } - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to send set absolute volume response"; - return false; - } - - return true; -} - -bool AvrcpControl::RegisterForAbsVolumeCallbackResponse( - const std::string& device_address, int32_t response_type, int32_t abs_vol, - int32_t label) { - RawAddress addr; - if (!RawAddress::FromString(device_address, addr)) { - LOG(ERROR) << "Invalid device address given: " << device_address; - return false; - } - - bt_status_t status; - { - std::lock_guard<std::mutex> lock(mutex_); - status = hal::BluetoothAvrcpInterface::Get() - ->GetControlHALInterface() - ->register_abs_vol_rsp( - addr, static_cast<btrc_notification_type_t>(response_type), - abs_vol, label); - } - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) - << "Failed to send send register for absolute volume change callback"; - return false; - } - - return true; -} - -void AvrcpControl::ConnectionStateCallback(bool rc_connect, bool bt_connect, - const RawAddress& bd_addr) { - std::string device_address = BtAddrString(&bd_addr); - std::lock_guard<std::mutex> lock(delegate_mutex_); - if (delegate_) - delegate_->OnConnectionState(rc_connect, bt_connect, device_address); -} - -void AvrcpControl::CtrlSetabsvolCmdCallback(const RawAddress& bd_addr, - uint8_t abs_vol, uint8_t label) { - std::string device_address = BtAddrString(&bd_addr); - std::lock_guard<std::mutex> lock(delegate_mutex_); - if (delegate_) - delegate_->OnSetAbsVolumeRequest(device_address, abs_vol, label); -} - -void AvrcpControl::CtrlRegisternotificationAbsVolCallback( - const RawAddress& bd_addr, uint8_t label) { - std::string device_address = BtAddrString(&bd_addr); - std::lock_guard<std::mutex> lock(delegate_mutex_); - if (delegate_) - delegate_->OnRegisterForAbsVolumeCallbackRequest(device_address, label); -} - -void AvrcpControl::CtrlTrackChangedCallback(const RawAddress& bd_addr, - uint8_t num_attr, - btrc_element_attr_val_t* p_attrs) { - std::string device_address = BtAddrString(&bd_addr); - - std::string title; - std::string artist; - std::string album; - std::string genre; - int track_num = -1; - int num_tracks = -1; - int play_time = -1; - - for (size_t i = 0; i < num_attr; ++i) { - auto attr_text = reinterpret_cast<char*>(p_attrs[i].text); - switch (p_attrs[i].attr_id) { - case BTRC_MEDIA_ATTR_ID_TITLE: - title = attr_text; - break; - case BTRC_MEDIA_ATTR_ID_ARTIST: - artist = attr_text; - break; - case BTRC_MEDIA_ATTR_ID_ALBUM: - album = attr_text; - break; - case BTRC_MEDIA_ATTR_ID_TRACK_NUM: - if (!base::StringToInt(attr_text, &track_num)) { - LOG(ERROR) << "Failed to parse track number"; - } - break; - case BTRC_MEDIA_ATTR_ID_NUM_TRACKS: - if (!base::StringToInt(attr_text, &num_tracks)) { - LOG(ERROR) << "Failed to parse number of tracks"; - } - break; - case BTRC_MEDIA_ATTR_ID_GENRE: - genre = attr_text; - break; - case BTRC_MEDIA_ATTR_ID_PLAYING_TIME: - if (!base::StringToInt(attr_text, &play_time)) { - LOG(ERROR) << "Failed to parse playing time"; - } - break; - default: - NOTREACHED(); - } - } - - const AvrcpMediaAttr attr(title, artist, album, genre, track_num, num_tracks, - play_time); - - std::lock_guard<std::mutex> lock(delegate_mutex_); - if (delegate_) delegate_->OnTrackChanged(device_address, attr); -} - -// AvrcpControlFactory implementation - -AvrcpControlFactory::AvrcpControlFactory() = default; -AvrcpControlFactory::~AvrcpControlFactory() = default; - -bool AvrcpControlFactory::RegisterInstance(const Uuid& uuid, - const RegisterCallback& callback) { - VLOG(1) << __func__ << " - Uuid: " << uuid.ToString(); - - int control_id = next_control_id_++; - std::unique_ptr<AvrcpControl> hf_client(new AvrcpControl(uuid, control_id)); - callback(BLE_STATUS_SUCCESS, uuid, std::move(hf_client)); - return true; -} - -} // namespace bluetooth diff --git a/system/service/avrcp_control.h b/system/service/avrcp_control.h deleted file mode 100644 index 47950e335d..0000000000 --- a/system/service/avrcp_control.h +++ /dev/null @@ -1,137 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <atomic> -#include <mutex> - -#include "bluetooth/uuid.h" -#include "service/bluetooth_instance.h" -#include "service/common/bluetooth/avrcp_media_attr.h" -#include "service/common/bluetooth/service.h" -#include "service/hal/bluetooth_avrcp_interface.h" -#include "types/raw_address.h" - -namespace bluetooth { - -class AvrcpControl : public BluetoothInstance, - private hal::BluetoothAvrcpInterface::ControlObserver { - public: - class Delegate { - public: - virtual void OnConnectionState(bool rc_connect, bool bt_connect, - const std::string& device_address) = 0; - - virtual void OnTrackChanged(const std::string& device_address, - const AvrcpMediaAttr& attr) = 0; - - virtual void OnSetAbsVolumeRequest(const std::string& device_address, - int32_t abs_vol, int32_t label) = 0; - - virtual void OnRegisterForAbsVolumeCallbackRequest( - const std::string& device_address, int32_t label) = 0; - - protected: - virtual ~Delegate() = default; - }; - - AvrcpControl(const AvrcpControl&) = delete; - AvrcpControl& operator=(const AvrcpControl&) = delete; - - // The destructor automatically unregisters this instance from the stack. - ~AvrcpControl() override; - - // Assigns a delegate to this instance. |delegate| must out-live this - // AvrcpControl instance. - void SetDelegate(Delegate* delegate); - - // BluetoothClientInstace overrides: - const Uuid& GetAppIdentifier() const override; - int GetInstanceId() const override; - - bool Enable(); - void Disable(); - - // Send a remote control button command. Commands which can be sent - // are defined here: - // http://1394ta.org/wp-content/uploads/2015/07/2007001.pdf - bool SendPassThroughCommand(const std::string& device_address, - uint8_t key_code, bool key_pressed); - - // Send a response to a request to change absolute volume. - bool SetAbsVolumeResponse(const std::string& device_address, int32_t abs_vol, - int32_t label); - - // Send a response to a register for absolute volume change callback. - bool RegisterForAbsVolumeCallbackResponse(const std::string& device_address, - int32_t response_type, - int32_t abs_vol, int32_t label); - - private: - friend class AvrcpControlFactory; - - // Constructor shouldn't be called directly as instances are meant to be - // obtained from the factory. - AvrcpControl(const Uuid& uuid, int control_id); - - // hal::BluetoothAvrcpInterface::ControlObserver implementation: - void ConnectionStateCallback(bool rc_connect, bool bt_connect, - const RawAddress& bd_addr) override; - void CtrlSetabsvolCmdCallback(const RawAddress& bd_addr, uint8_t abs_vol, - uint8_t label) override; - void CtrlRegisternotificationAbsVolCallback(const RawAddress& bd_addr, - uint8_t label) override; - void CtrlTrackChangedCallback(const RawAddress& bd_addr, uint8_t num_attr, - btrc_element_attr_val_t* p_attrs) override; - - // See getters for documentation. - const Uuid app_identifier_; - const int control_id_; - - // Mutex that synchronizes access to the entries below. - std::mutex mutex_; - - // Raw handle to the Delegate, which must outlive this AvrcpControl instance. - std::mutex delegate_mutex_; - Delegate* delegate_ = nullptr; -}; - -// AvrcpControlFactory is used to register and obtain a per-application -// AvrcpControl -// instance. Users should call RegisterClient to obtain their own unique -// AvrcpControl instance that has been registered with the Bluetooth stack. -class AvrcpControlFactory - : public BluetoothInstanceFactory, - private hal::BluetoothAvrcpInterface::ControlObserver { - public: - // Don't construct/destruct directly except in tests. Instead, obtain a handle - // from an Adapter instance. - AvrcpControlFactory(); - AvrcpControlFactory(const AvrcpControlFactory&) = delete; - AvrcpControlFactory& operator=(const AvrcpControlFactory&) = delete; - - ~AvrcpControlFactory() override; - - // BluetoothInstanceFactory override: - bool RegisterInstance(const Uuid& uuid, - const RegisterCallback& callback) override; - - private: - std::atomic<int> next_control_id_{0}; -}; - -} // namespace bluetooth diff --git a/system/service/avrcp_target.cc b/system/service/avrcp_target.cc deleted file mode 100644 index 9a39b412f4..0000000000 --- a/system/service/avrcp_target.cc +++ /dev/null @@ -1,380 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/avrcp_target.h" - -#include <algorithm> -#include <cerrno> -#include <climits> -#include <string> - -#include "array_utils.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "service/logging_helpers.h" -#include "stack/include/avrc_defs.h" -#include "types/raw_address.h" - -#define PARSE_ADDR(str) \ - ({ \ - RawAddress tmp; \ - if (!RawAddress::FromString((str), tmp)) { \ - LOG(ERROR) << "Invalid device address given: " << (str); \ - return false; \ - } \ - tmp; \ - }) - -#define TRY_RET(expr, err_msg) \ - do { \ - if (!(expr)) { \ - LOG(ERROR) << err_msg; \ - return false; \ - } \ - return true; \ - } while (0) - -#define TRY_RET_FUNC(expr) TRY_RET(expr, __func__ << " failed") - -using LockGuard = std::lock_guard<std::mutex>; - -namespace bluetooth { - -namespace { - -std::vector<btrc_player_setting_text_t> StringValueToPlayerSettingsText( - const std::vector<AvrcpStringValue>& attrs) { - std::vector<btrc_player_setting_text_t> btrc_attrs(attrs.size()); - for (size_t i = 0; i < attrs.size(); ++i) { - btrc_attrs[i].id = attrs[i].id(); - std::string str(attrs[i].value()); - size_t to_copy = std::min(sizeof(btrc_attrs[i].text) - 1, str.size()); - if (to_copy < str.size()) { - LOG(WARNING) << "Value truncated"; - } - - memcpy(btrc_attrs[i].text, str.data(), to_copy); - btrc_attrs[i].text[to_copy] = '\0'; - } - - return btrc_attrs; -} - -std::vector<btrc_element_attr_val_t> StringValueToElementAttrVal( - const std::vector<AvrcpStringValue>& attrs) { - std::vector<btrc_element_attr_val_t> btrc_attrs(attrs.size()); - for (size_t i = 0; i < attrs.size(); ++i) { - btrc_attrs[i].attr_id = attrs[i].id(); - std::string str(attrs[i].value()); - size_t to_copy = std::min(sizeof(btrc_attrs[i].text) - 1, str.size()); - if (to_copy < str.size()) { - LOG(WARNING) << "Value truncated"; - } - - memcpy(btrc_attrs[i].text, str.data(), to_copy); - btrc_attrs[i].text[to_copy] = '\0'; - } - - return btrc_attrs; -} - -} // namespace - -// static -const int AvrcpTarget::kSingletonInstanceId = 0; - -AvrcpTarget::AvrcpTarget(const Uuid& uuid) : app_identifier_(uuid) { - hal::BluetoothAvrcpInterface::Get()->AddTargetObserver(this); -} - -AvrcpTarget::~AvrcpTarget() { - hal::BluetoothAvrcpInterface::Get()->RemoveTargetObserver(this); -} - -const Uuid& AvrcpTarget::GetAppIdentifier() const { return app_identifier_; } - -int AvrcpTarget::GetInstanceId() const { return kSingletonInstanceId; } - -void AvrcpTarget::SetDelegate(Delegate* delegate) { - LockGuard lock(delegate_mutex_); - delegate_ = delegate; -} - -bool AvrcpTarget::Enable() { - LockGuard lock(mutex_); - return hal::BluetoothAvrcpInterface::Get()->AvrcpTargetEnable(); -} - -void AvrcpTarget::Disable() { - LockGuard lock(mutex_); - hal::BluetoothAvrcpInterface::Get()->AvrcpTargetDisable(); -} - -bool AvrcpTarget::GetPlayStatusResponse(const std::string& str_addr, - int32_t play_status, uint32_t song_len, - uint32_t song_pos) { - RawAddress addr = PARSE_ADDR(str_addr); - LockGuard lock(mutex_); - TRY_RET_FUNC(hal::BluetoothAvrcpInterface::Get() - ->GetTargetHALInterface() - ->get_play_status_rsp( - addr, static_cast<btrc_play_status_t>(play_status), - song_len, song_pos) == BT_STATUS_SUCCESS); -} - -bool AvrcpTarget::ListPlayerAppAttrResponse(const std::string& str_addr, - const std::vector<int32_t>& attrs) { - RawAddress addr = PARSE_ADDR(str_addr); - - std::vector<btrc_player_attr_t> btrc_attrs; - btrc_attrs.reserve(attrs.size()); - for (auto attr : attrs) { - btrc_attrs.push_back(static_cast<btrc_player_attr_t>(attr)); - } - - LockGuard lock(mutex_); - TRY_RET_FUNC(hal::BluetoothAvrcpInterface::Get() - ->GetTargetHALInterface() - ->list_player_app_attr_rsp(addr, btrc_attrs.size(), - btrc_attrs.data()) == - BT_STATUS_SUCCESS); -} - -bool AvrcpTarget::GetPlayerAppValueResponse( - const std::string& str_addr, const std::vector<AvrcpIntValue>& values) { - RawAddress addr = PARSE_ADDR(str_addr); - btrc_player_settings_t btrc_values; - if (values.size() >= ARRAY_SIZE(btrc_values.attr_ids)) { - LOG(ERROR) << "Too many attribute values"; - return false; - } - - btrc_values.num_attr = values.size(); - for (size_t i = 0; i < values.size(); ++i) { - btrc_values.attr_ids[i] = values[i].id(); - btrc_values.attr_values[i] = values[i].value(); - } - - LockGuard lock(mutex_); - TRY_RET_FUNC(hal::BluetoothAvrcpInterface::Get() - ->GetTargetHALInterface() - ->get_player_app_value_rsp(addr, &btrc_values) == - BT_STATUS_SUCCESS); -} - -bool AvrcpTarget::GetPlayerAppAttrTextResponse( - const std::string& str_addr, const std::vector<AvrcpStringValue>& attrs) { - RawAddress addr = PARSE_ADDR(str_addr); - auto btrc_attrs = StringValueToPlayerSettingsText(attrs); - LockGuard lock(mutex_); - TRY_RET_FUNC(hal::BluetoothAvrcpInterface::Get() - ->GetTargetHALInterface() - ->get_player_app_attr_text_rsp(addr, btrc_attrs.size(), - btrc_attrs.data()) == - BT_STATUS_SUCCESS); -} - -bool AvrcpTarget::GetPlayerAppValueTextResponse( - const std::string& str_addr, const std::vector<AvrcpStringValue>& values) { - RawAddress addr = PARSE_ADDR(str_addr); - auto btrc_values = StringValueToPlayerSettingsText(values); - LockGuard lock(mutex_); - TRY_RET_FUNC(hal::BluetoothAvrcpInterface::Get() - ->GetTargetHALInterface() - ->get_player_app_value_text_rsp(addr, btrc_values.size(), - btrc_values.data()) == - BT_STATUS_SUCCESS); -} - -bool AvrcpTarget::GetElementAttrResponse( - const std::string& str_addr, const std::vector<AvrcpStringValue>& attrs) { - RawAddress addr = PARSE_ADDR(str_addr); - auto btrc_attrs = StringValueToElementAttrVal(attrs); - LockGuard lock(mutex_); - TRY_RET_FUNC( - hal::BluetoothAvrcpInterface::Get() - ->GetTargetHALInterface() - ->get_element_attr_rsp(addr, btrc_attrs.size(), btrc_attrs.data()) == - BT_STATUS_SUCCESS); -} - -bool AvrcpTarget::SetPlayerAppValueResponse(const std::string& str_addr, - int32_t rsp_status) { - RawAddress addr = PARSE_ADDR(str_addr); - LockGuard lock(mutex_); - TRY_RET_FUNC(hal::BluetoothAvrcpInterface::Get() - ->GetTargetHALInterface() - ->set_player_app_value_rsp( - addr, static_cast<btrc_status_t>(rsp_status)) == - BT_STATUS_SUCCESS); -} - -bool AvrcpTarget::RegisterNotificationResponse( - int32_t event_id, int32_t type, - const AvrcpRegisterNotificationResponse& param) { - auto param_copy = param.data(); - LockGuard lock(mutex_); - TRY_RET_FUNC(hal::BluetoothAvrcpInterface::Get() - ->GetTargetHALInterface() - ->register_notification_rsp( - static_cast<btrc_event_id_t>(event_id), - static_cast<btrc_notification_type_t>(type), - ¶m_copy) == BT_STATUS_SUCCESS); -} - -bool AvrcpTarget::SetVolume(int volume) { - LockGuard lock(mutex_); - TRY_RET_FUNC( - hal::BluetoothAvrcpInterface::Get()->GetTargetHALInterface()->set_volume( - volume) == BT_STATUS_SUCCESS); -} - -void AvrcpTarget::RemoteFeaturesCallback(const RawAddress& bd_addr, - btrc_remote_features_t features) { - auto str_addr = BtAddrString(&bd_addr); - LockGuard lock(delegate_mutex_); - if (delegate_) - delegate_->OnGetRemoteFeatures(str_addr, static_cast<int32_t>(features)); -} - -void AvrcpTarget::GetPlayStatusCallback(const RawAddress& bd_addr) { - auto str_addr = BtAddrString(&bd_addr); - LockGuard lock(delegate_mutex_); - if (delegate_) delegate_->OnGetPlayStatus(str_addr); -} - -void AvrcpTarget::ListPlayerAppAttrCallback(const RawAddress& bd_addr) { - auto str_addr = BtAddrString(&bd_addr); - LockGuard lock(delegate_mutex_); - if (delegate_) delegate_->OnListPlayerAppAttr(str_addr); -} - -void AvrcpTarget::ListPlayerAppValuesCallback(btrc_player_attr_t attr_id, - const RawAddress& bd_addr) { - auto str_addr = BtAddrString(&bd_addr); - LockGuard lock(delegate_mutex_); - if (delegate_) - delegate_->OnListPlayerAppValues(str_addr, static_cast<int32_t>(attr_id)); -} - -void AvrcpTarget::GetPlayerAppValueCallback(uint8_t num_attr, - btrc_player_attr_t* p_attrs, - const RawAddress& bd_addr) { - auto str_addr = BtAddrString(&bd_addr); - std::vector<int32_t> attr_vec; - attr_vec.reserve(num_attr); - for (auto* it = p_attrs; it != p_attrs + num_attr; ++it) { - attr_vec.push_back(*it); - } - - LockGuard lock(delegate_mutex_); - if (delegate_) delegate_->OnGetPlayerAppValue(str_addr, attr_vec); -} - -void AvrcpTarget::GetPlayerAppAttrsTextCallback(uint8_t num_attr, - btrc_player_attr_t* p_attrs, - const RawAddress& bd_addr) { - auto str_addr = BtAddrString(&bd_addr); - std::vector<int32_t> attr_vec; - attr_vec.reserve(num_attr); - for (auto* it = p_attrs; it != p_attrs + num_attr; ++it) { - attr_vec.push_back(*it); - } - - LockGuard lock(delegate_mutex_); - if (delegate_) delegate_->OnGetPlayerAppAttrsText(str_addr, attr_vec); -} - -void AvrcpTarget::GetPlayerAppValuesTextCallback(uint8_t attr_id, - uint8_t num_val, - uint8_t* p_vals, - const RawAddress& bd_addr) { - auto str_addr = BtAddrString(&bd_addr); - std::vector<int32_t> val_vec; - val_vec.reserve(num_val); - for (auto* it = p_vals; it != p_vals + num_val; ++it) { - val_vec.push_back(*it); - } - LockGuard lock(delegate_mutex_); - if (delegate_) - delegate_->OnGetPlayerAppValuesText(str_addr, attr_id, val_vec); -} - -void AvrcpTarget::SetPlayerAppValueCallback(btrc_player_settings_t* p_vals, - const RawAddress& bd_addr) { - auto str_addr = BtAddrString(&bd_addr); - std::vector<AvrcpIntValue> values; - values.reserve(p_vals->num_attr); - for (size_t i = 0; i < p_vals->num_attr; ++i) { - values.emplace_back(p_vals->attr_ids[i], p_vals->attr_values[i]); - } - - LockGuard lock(delegate_mutex_); - if (delegate_) delegate_->OnSetPlayerAppValue(str_addr, values); -} - -void AvrcpTarget::GetElementAttrCallback(uint8_t num_attr, - btrc_media_attr_t* p_attrs, - const RawAddress& bd_addr) { - auto str_addr = BtAddrString(&bd_addr); - std::vector<int32_t> attr_vec; - attr_vec.reserve(num_attr); - for (auto* it = p_attrs; it != p_attrs + num_attr; ++it) { - attr_vec.push_back(*it); - } - LockGuard lock(delegate_mutex_); - if (delegate_) delegate_->OnGetElementAttrs(str_addr, attr_vec); -} - -void AvrcpTarget::RegisterNotificationCallback(btrc_event_id_t event_id, - uint32_t param, - const RawAddress& bd_addr) { - auto str_addr = BtAddrString(&bd_addr); - LockGuard lock(delegate_mutex_); - if (delegate_) - delegate_->OnRegisterNotification(str_addr, static_cast<int32_t>(event_id), - param); -} - -void AvrcpTarget::VolumeChangeCallback(uint8_t volume, uint8_t ctype, - const RawAddress& bd_addr) { - auto str_addr = BtAddrString(&bd_addr); - LockGuard lock(delegate_mutex_); - if (delegate_) delegate_->OnVolumeChange(str_addr, volume, ctype); -} - -void AvrcpTarget::PassthroughCmdCallback(int id, int key_state, - const RawAddress& bd_addr) { - auto str_addr = BtAddrString(&bd_addr); - LockGuard lock(delegate_mutex_); - if (delegate_) delegate_->OnPassThroughCommand(str_addr, id, key_state); -} - -// AvrcpTargetFactory implementation - -AvrcpTargetFactory::AvrcpTargetFactory() = default; -AvrcpTargetFactory::~AvrcpTargetFactory() = default; - -bool AvrcpTargetFactory::RegisterInstance(const Uuid& uuid, - const RegisterCallback& callback) { - VLOG(1) << __func__ << " - UUID: " << uuid.ToString(); - - auto avrcp_target = base::WrapUnique(new AvrcpTarget(uuid)); - callback(BLE_STATUS_SUCCESS, uuid, std::move(avrcp_target)); - return true; -} - -} // namespace bluetooth diff --git a/system/service/avrcp_target.h b/system/service/avrcp_target.h deleted file mode 100644 index 76c5be0db8..0000000000 --- a/system/service/avrcp_target.h +++ /dev/null @@ -1,178 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <mutex> -#include <string> -#include <vector> - -#include "service/bluetooth_instance.h" -#include "service/common/bluetooth/avrcp_int_value.h" -#include "service/common/bluetooth/avrcp_register_notification_response.h" -#include "service/common/bluetooth/avrcp_string_value.h" -#include "service/hal/bluetooth_avrcp_interface.h" -#include "types/raw_address.h" - -namespace bluetooth { - -// Note: presently this only supports -// (BTRC_FEAT_METADATA | BTRC_FEAT_ABSOLUTE_VOLUME) -class AvrcpTarget : public BluetoothInstance, - private hal::BluetoothAvrcpInterface::TargetObserver { - public: - // We only allow one instance of this object at a time. - static const int kSingletonInstanceId; - - class Delegate { - public: - virtual void OnGetRemoteFeatures(const std::string& addr, - int32_t features) = 0; - virtual void OnGetPlayStatus(const std::string& addr) = 0; - virtual void OnListPlayerAppAttr(const std::string& addr) = 0; - virtual void OnListPlayerAppValues(const std::string& addr, - int32_t attr_id) = 0; - virtual void OnGetPlayerAppValue(const std::string& addr, - const std::vector<int32_t>& attrs) = 0; - virtual void OnGetPlayerAppAttrsText(const std::string& addr, - const std::vector<int32_t>& attrs) = 0; - virtual void OnGetPlayerAppValuesText( - const std::string& addr, int32_t attr_id, - const std::vector<int32_t>& values) = 0; - virtual void OnSetPlayerAppValue( - const std::string& addr, const std::vector<AvrcpIntValue>& values) = 0; - virtual void OnGetElementAttrs(const std::string& addr, - const std::vector<int32_t>& attrs) = 0; - virtual void OnRegisterNotification(const std::string& addr, - int32_t event_id, uint32_t param) = 0; - virtual void OnVolumeChange(const std::string& addr, int32_t volume, - int32_t ctype) = 0; - virtual void OnPassThroughCommand(const std::string& addr, int32_t id, - int32_t key_state) = 0; - - protected: - virtual ~Delegate() = default; - }; - - AvrcpTarget(const AvrcpTarget&) = delete; - AvrcpTarget& operator=(const AvrcpTarget&) = delete; - - // The destructor automatically unregisters this instance from the stack. - ~AvrcpTarget() override; - - // Assigns a delegate to this instance. |delegate| must out-live this - // AvrcpTarget instance. - void SetDelegate(Delegate* delegate); - - // BluetoothClientInstace overrides: - const Uuid& GetAppIdentifier() const override; - int GetInstanceId() const override; - - bool Enable(); - void Disable(); - - bool GetPlayStatusResponse(const std::string& addr, int32_t play_status, - uint32_t song_len, uint32_t song_pos); - - bool ListPlayerAppAttrResponse(const std::string& addr, - const std::vector<int32_t>& attrs); - - bool GetPlayerAppValueResponse(const std::string& addr, - const std::vector<AvrcpIntValue>& values); - - bool GetPlayerAppAttrTextResponse(const std::string& addr, - const std::vector<AvrcpStringValue>& attrs); - - bool GetPlayerAppValueTextResponse( - const std::string& addr, const std::vector<AvrcpStringValue>& attrs); - - bool GetElementAttrResponse(const std::string& addr, - const std::vector<AvrcpStringValue>& attrs); - - bool SetPlayerAppValueResponse(const std::string& addr, int32_t rsp_status); - - bool RegisterNotificationResponse( - int32_t event_id, int32_t type, - const AvrcpRegisterNotificationResponse& param); - - bool SetVolume(int volume); - - private: - friend class AvrcpTargetFactory; - - // Constructor shouldn't be called directly as instances are meant to be - // obtained from the factory. - AvrcpTarget(const Uuid& uuid); - - // hal::BluetoothAvrcpInterface::TargetObserver implementation: - void RemoteFeaturesCallback(const RawAddress& bd_addr, - btrc_remote_features_t features) override; - void GetPlayStatusCallback(const RawAddress& bd_addr) override; - void ListPlayerAppAttrCallback(const RawAddress& bd_addr) override; - void ListPlayerAppValuesCallback(btrc_player_attr_t attr_id, - const RawAddress& bd_addr) override; - void GetPlayerAppValueCallback(uint8_t num_attr, btrc_player_attr_t* p_attrs, - const RawAddress& bd_addr) override; - void GetPlayerAppAttrsTextCallback(uint8_t num_attr, - btrc_player_attr_t* p_attrs, - const RawAddress& bd_addr) override; - void GetPlayerAppValuesTextCallback(uint8_t attr_id, uint8_t num_val, - uint8_t* p_vals, - const RawAddress& bd_addr) override; - void SetPlayerAppValueCallback(btrc_player_settings_t* p_vals, - const RawAddress& bd_addr) override; - void GetElementAttrCallback(uint8_t num_attr, btrc_media_attr_t* p_attrs, - const RawAddress& bd_addr) override; - void RegisterNotificationCallback(btrc_event_id_t event_id, uint32_t param, - const RawAddress& bd_addr) override; - void VolumeChangeCallback(uint8_t volume, uint8_t ctype, - const RawAddress& bd_addr) override; - void PassthroughCmdCallback(int id, int key_state, - const RawAddress& bd_addr) override; - - // See getters for documentation. - const Uuid app_identifier_; - - // Mutex that synchronizes access to the entries below. - std::mutex mutex_; - - // Raw handle to the Delegate, which must outlive this AvrcpTarget instance. - std::mutex delegate_mutex_; - Delegate* delegate_ = nullptr; -}; - -// AvrcpTargetFactory is used to register and obtain a per-application -// AvrcpTarget -// instance. Users should call RegisterClient to obtain their own unique -// AvrcpTarget instance that has been registered with the Bluetooth stack. -class AvrcpTargetFactory - : public BluetoothInstanceFactory, - private hal::BluetoothAvrcpInterface::TargetObserver { - public: - // Don't construct/destruct directly except in tests. Instead, obtain a handle - // from an Adapter instance. - AvrcpTargetFactory(); - AvrcpTargetFactory(const AvrcpTargetFactory&) = delete; - AvrcpTargetFactory& operator=(const AvrcpTargetFactory&) = delete; - - ~AvrcpTargetFactory() override; - - // BluetoothInstanceFactory override: - bool RegisterInstance(const Uuid& uuid, - const RegisterCallback& callback) override; -}; - -} // namespace bluetooth diff --git a/system/service/bluetooth_instance.h b/system/service/bluetooth_instance.h deleted file mode 100644 index 5728d5e02b..0000000000 --- a/system/service/bluetooth_instance.h +++ /dev/null @@ -1,74 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <functional> -#include <memory> - -#include <bluetooth/uuid.h> - -#include "service/common/bluetooth/low_energy_constants.h" - -namespace bluetooth { - -// A BluetoothInstance represents an application's handle to an instance -// that is registered with the underlying Bluetooth stack using a Uuid and has a -// stack-assigned integer "instance_id" ID associated with it. -class BluetoothInstance { - public: - BluetoothInstance(const BluetoothInstance&) = delete; - BluetoothInstance& operator=(const BluetoothInstance&) = delete; - - virtual ~BluetoothInstance() = default; - - // Returns the app-specific unique ID used while registering this instance. - virtual const Uuid& GetAppIdentifier() const = 0; - - // Returns the HAL "interface ID" assigned to this instance by the stack. - virtual int GetInstanceId() const = 0; - - protected: - // Constructor shouldn't be called directly as instances are meant to be - // obtained from the factory. - BluetoothInstance() = default; -}; - -// A BluetoothInstanceFactory provides a common interface for factory -// classes that handle asynchronously registering a per-application instance of -// a BluetoothInstance with the underlying stack. -class BluetoothInstanceFactory { - public: - BluetoothInstanceFactory() = default; - BluetoothInstanceFactory(const BluetoothInstanceFactory&) = delete; - BluetoothInstanceFactory& operator=(const BluetoothInstanceFactory&) = delete; - - virtual ~BluetoothInstanceFactory() = default; - - // Callback invoked as a result of a call to RegisterInstance. - using RegisterCallback = - std::function<void(BLEStatus status, const Uuid& app_uuid, - std::unique_ptr<BluetoothInstance> instance)>; - - // Registers an instance for the given unique identifier |app_uuid|. - // On success, this asynchronously invokes |callback| with a unique pointer - // to a BluetoothInstance whose ownership can be taken by the caller. In - // the case of an error, the pointer will contain nullptr. - virtual bool RegisterInstance(const Uuid& app_uuid, - const RegisterCallback& callback) = 0; -}; - -} // namespace bluetooth diff --git a/system/service/bluetoothtbd.rc b/system/service/bluetoothtbd.rc deleted file mode 100644 index f613711dcb..0000000000 --- a/system/service/bluetoothtbd.rc +++ /dev/null @@ -1,4 +0,0 @@ -service bluetoothtbd /system/bin/bluetoothtbd - class main - user bluetooth - group wakelock net_bt_admin bluetooth net_admin diff --git a/system/service/client/main.cc b/system/service/client/main.cc deleted file mode 100644 index b08136997a..0000000000 --- a/system/service/client/main.cc +++ /dev/null @@ -1,1147 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include <iostream> -#include <string> - -#include <base/at_exit.h> -#include <base/command_line.h> -#include <base/logging.h> -#include <base/strings/string_number_conversions.h> -#include <base/strings/string_split.h> -#include <base/strings/string_util.h> -#include <binder/IPCThreadState.h> -#include <binder/IServiceManager.h> -#include <binder/ProcessState.h> - -#include <android/bluetooth/BnBluetoothCallback.h> -#include <android/bluetooth/BnBluetoothGattClientCallback.h> -#include <android/bluetooth/BnBluetoothLeAdvertiserCallback.h> -#include <android/bluetooth/BnBluetoothLeScannerCallback.h> -#include <android/bluetooth/BnBluetoothLowEnergyCallback.h> -#include <android/bluetooth/IBluetooth.h> -#include <android/bluetooth/IBluetoothGattClient.h> -#include <android/bluetooth/IBluetoothLeAdvertiser.h> -#include <android/bluetooth/IBluetoothLeScanner.h> -#include <android/bluetooth/IBluetoothLowEnergy.h> -#include <bluetooth/adapter_state.h> -#include <bluetooth/low_energy_constants.h> -#include <bluetooth/scan_filter.h> -#include <bluetooth/scan_settings.h> -#include <bluetooth/uuid.h> - -#include "notreached.h" - -using namespace std; - -using android::sp; -using android::String8; -using android::String16; -using android::binder::Status; -using android::OK; -using android::getService; - -using android::bluetooth::IBluetooth; -using android::bluetooth::IBluetoothGattClient; -using android::bluetooth::IBluetoothLeAdvertiser; -using android::bluetooth::IBluetoothLeScanner; -using android::bluetooth::IBluetoothLowEnergy; - -namespace { - -#define COLOR_OFF "\x1B[0m" -#define COLOR_RED "\x1B[0;91m" -#define COLOR_GREEN "\x1B[0;92m" -#define COLOR_YELLOW "\x1B[0;93m" -#define COLOR_BLUE "\x1B[0;94m" -#define COLOR_MAGENTA "\x1B[0;95m" -#define COLOR_BOLDGRAY "\x1B[1;30m" -#define COLOR_BOLDWHITE "\x1B[1;37m" -#define COLOR_BOLDYELLOW "\x1B[1;93m" -#define CLEAR_LINE "\x1B[2K" - -#define CHECK_ARGS_COUNT(args, op, num, msg) \ - if (!((args).size() op num)) { \ - PrintError(msg); \ - return; \ - } -#define CHECK_NO_ARGS(args) \ - CHECK_ARGS_COUNT(args, ==, 0, "Expected no arguments") - -// TODO(armansito): Clean up this code. Right now everything is in this -// monolithic file. We should organize this into different classes for command -// handling, console output/printing, callback handling, etc. -// (See http://b/23387611) - -// Used to synchronize the printing of the command-line prompt and incoming -// Binder callbacks. -std::atomic_bool showing_prompt(false); - -// The registered IBluetoothLowEnergy client handle. If |ble_registering| is -// true then an operation to register the client is in progress. -std::atomic_bool ble_registering(false); -std::atomic_int ble_client_id(0); - -// The registered IBluetoothLeAdvertiser handle. If |ble_advertiser_registering| -// is true then an operation to register the advertiser is in progress. -const int invalid_advertiser_id = -1; -std::atomic_bool ble_advertiser_registering(false); -std::atomic_int ble_advertiser_id(invalid_advertiser_id); - -// The registered IBluetoothLeScanner handle. If |ble_scanner_registering| is -// true then an operation to register the scanner is in progress. -std::atomic_bool ble_scanner_registering(false); -std::atomic_int ble_scanner_id(0); - -// The registered IBluetoothGattClient client handle. If |gatt_registering| is -// true then an operation to register the client is in progress. -std::atomic_bool gatt_registering(false); -std::atomic_int gatt_client_id(0); - -// True if we should dump the scan record bytes for incoming scan results. -std::atomic_bool dump_scan_record(false); - -// True if the remote process has died and we should exit. -std::atomic_bool should_exit(false); - -std::string kServiceName = "bluetooth-service"; - -void PrintPrompt() { cout << COLOR_BLUE "[FCLI] " COLOR_OFF << flush; } - -void PrintError(const string& message) { - cout << COLOR_RED << message << COLOR_OFF << endl; -} - -void PrintOpStatus(const std::string& op, bool status) { - cout << COLOR_BOLDWHITE << op << " status: " COLOR_OFF - << (status ? (COLOR_GREEN "success") : (COLOR_RED "failure")) - << COLOR_OFF << endl; -} - -inline void BeginAsyncOut() { - if (showing_prompt.load()) cout << CLEAR_LINE << "\r"; -} - -inline void EndAsyncOut() { - std::flush(cout); - if (showing_prompt.load()) - PrintPrompt(); - else - cout << endl; -} - -class CLIBluetoothCallback : public android::bluetooth::BnBluetoothCallback { - public: - CLIBluetoothCallback() = default; - CLIBluetoothCallback(const CLIBluetoothCallback&) = delete; - CLIBluetoothCallback& operator=(const CLIBluetoothCallback&) = delete; - ~CLIBluetoothCallback() override = default; - - // IBluetoothCallback overrides: - Status OnBluetoothStateChange(int32_t prev_state, - int32_t new_state) override { - BeginAsyncOut(); - cout << COLOR_BOLDWHITE "Adapter state changed: " COLOR_OFF << COLOR_MAGENTA - << AdapterStateToString(bluetooth::AdapterState(prev_state)) - << COLOR_OFF << COLOR_BOLDWHITE " -> " COLOR_OFF << COLOR_BOLDYELLOW - << AdapterStateToString(bluetooth::AdapterState(new_state)) - << COLOR_OFF; - EndAsyncOut(); - - return Status::ok(); - } - - Status OnSspRequest(const String16& device_address, - const String16& device_name, int32_t cod, - int32_t pairing_variant, int32_t pass_key) override { - // no-op - return Status::ok(); - } - - Status OnGetBondedDevices( - int32_t status, - const ::std::vector<String16>& device_addresses) override { - BeginAsyncOut(); - std::cout << "Bonded devices:\n"; - for (const auto& device_address : device_addresses) { - std::cout << " " << device_address << "\n"; - } - EndAsyncOut(); - return Status::ok(); - } - - Status OnBondStateChanged(int32_t status, const String16& device_address, - int32_t state) override { - BeginAsyncOut(); - std::cout << COLOR_BOLDWHITE "Device address: " << COLOR_BOLDYELLOW "[" - << device_address << " bond state: " << state << " ] " - << COLOR_BOLDWHITE "- status: " - << (status == 0 ? "SUCCESS" : "FAIL") << COLOR_OFF; - EndAsyncOut(); - return Status::ok(); - } - - Status OnGetRemoteDeviceProperties( - int32_t status, const String16& device_address, - const android::bluetooth::BluetoothRemoteDeviceProps& props) override { - // no-op - return Status::ok(); - } - - Status OnDeviceFound( - const android::bluetooth::BluetoothRemoteDeviceProps& props) override { - // no-op - return Status::ok(); - } - - Status OnDeviceConnectionStateChanged(const String16& device_address, - bool connected) override { - // no-op - return Status::ok(); - } - - Status OnScanEnableChanged(bool scan_enabled) override { - // no-op - return Status::ok(); - } -}; - -class CLIBluetoothLowEnergyCallback - : public android::bluetooth::BnBluetoothLowEnergyCallback { - public: - CLIBluetoothLowEnergyCallback() = default; - CLIBluetoothLowEnergyCallback(const CLIBluetoothLowEnergyCallback&) = delete; - CLIBluetoothLowEnergyCallback& operator=( - const CLIBluetoothLowEnergyCallback&) = delete; - ~CLIBluetoothLowEnergyCallback() override = default; - - // IBluetoothLowEnergyCallback overrides: - Status OnClientRegistered(int status, int client_id) override { - BeginAsyncOut(); - if (status != bluetooth::BLE_STATUS_SUCCESS) { - PrintError("Failed to register BLE client"); - } else { - ble_client_id = client_id; - cout << COLOR_BOLDWHITE "Registered BLE client with ID: " COLOR_OFF - << COLOR_GREEN << client_id << COLOR_OFF; - } - EndAsyncOut(); - - ble_registering = false; - return Status::ok(); - } - - Status OnConnectionState(int status, int client_id, const String16& address, - bool connected) override { - BeginAsyncOut(); - cout << COLOR_BOLDWHITE "Connection state: " << COLOR_BOLDYELLOW "[" - << address << " connected: " << (connected ? "true" : "false") << " ] " - << COLOR_BOLDWHITE "- status: " << status - << COLOR_BOLDWHITE " - client_id: " << client_id << COLOR_OFF; - EndAsyncOut(); - return Status::ok(); - } - - Status OnMtuChanged(int status, const String16& address, int mtu) override { - BeginAsyncOut(); - cout << COLOR_BOLDWHITE "MTU changed: " << COLOR_BOLDYELLOW "[" << address - << " ] " << COLOR_BOLDWHITE " - status: " << status - << COLOR_BOLDWHITE " - mtu: " << mtu << COLOR_OFF; - EndAsyncOut(); - return Status::ok(); - } -}; - -class CLIBluetoothLeAdvertiserCallback - : public android::bluetooth::BnBluetoothLeAdvertiserCallback { - public: - CLIBluetoothLeAdvertiserCallback() = default; - CLIBluetoothLeAdvertiserCallback(const CLIBluetoothLeAdvertiserCallback&) = - delete; - CLIBluetoothLeAdvertiserCallback& operator=( - const CLIBluetoothLeAdvertiserCallback&) = delete; - ~CLIBluetoothLeAdvertiserCallback() override = default; - - // IBluetoothLowEnergyCallback overrides: - Status OnAdvertiserRegistered(int status, int advertiser_id) override { - BeginAsyncOut(); - if (status != bluetooth::BLE_STATUS_SUCCESS) { - PrintError("Failed to register BLE advertiser"); - } else { - ble_advertiser_id = advertiser_id; - cout << COLOR_BOLDWHITE "Registered BLE advertiser with ID: " COLOR_OFF - << COLOR_GREEN << advertiser_id << COLOR_OFF; - } - EndAsyncOut(); - - ble_advertiser_registering = false; - return Status::ok(); - } - - Status OnMultiAdvertiseCallback( - int status, bool is_start, - const android::bluetooth::AdvertiseSettings& /* settings */) { - BeginAsyncOut(); - std::string op = is_start ? "start" : "stop"; - - PrintOpStatus("Advertising " + op, status == bluetooth::BLE_STATUS_SUCCESS); - EndAsyncOut(); - return Status::ok(); - } -}; - -class CLIBluetoothLeScannerCallback - : public android::bluetooth::BnBluetoothLeScannerCallback { - public: - CLIBluetoothLeScannerCallback() = default; - CLIBluetoothLeScannerCallback(const CLIBluetoothLeScannerCallback&) = delete; - CLIBluetoothLeScannerCallback& operator=( - const CLIBluetoothLeScannerCallback&) = delete; - ~CLIBluetoothLeScannerCallback() override = default; - - // IBluetoothLowEnergyCallback overrides: - Status OnScannerRegistered(int status, int scanner_id) override { - BeginAsyncOut(); - if (status != bluetooth::BLE_STATUS_SUCCESS) { - PrintError("Failed to register BLE client"); - } else { - ble_scanner_id = scanner_id; - cout << COLOR_BOLDWHITE "Registered BLE client with ID: " COLOR_OFF - << COLOR_GREEN << scanner_id << COLOR_OFF; - } - EndAsyncOut(); - - ble_scanner_registering = false; - return Status::ok(); - } - - Status OnScanResult( - const android::bluetooth::ScanResult& scan_result) override { - BeginAsyncOut(); - cout << COLOR_BOLDWHITE "Scan result: " << COLOR_BOLDYELLOW "[" - << scan_result.device_address() << "] " - << COLOR_BOLDWHITE "- RSSI: " << scan_result.rssi() << COLOR_OFF; - - if (dump_scan_record) { - cout << " - Record: " - << base::HexEncode(scan_result.scan_record().data(), - scan_result.scan_record().size()); - } - EndAsyncOut(); - return Status::ok(); - } -}; - -class CLIGattClientCallback - : public android::bluetooth::BnBluetoothGattClientCallback { - public: - CLIGattClientCallback() = default; - CLIGattClientCallback(const CLIGattClientCallback&) = delete; - CLIGattClientCallback& operator=(const CLIGattClientCallback&) = delete; - ~CLIGattClientCallback() override = default; - - // IBluetoothGattClientCallback overrides: - Status OnClientRegistered(int status, int client_id) override { - BeginAsyncOut(); - if (status != bluetooth::BLE_STATUS_SUCCESS) { - PrintError("Failed to register GATT client"); - } else { - gatt_client_id = client_id; - cout << COLOR_BOLDWHITE "Registered GATT client with ID: " COLOR_OFF - << COLOR_GREEN << client_id << COLOR_OFF; - } - EndAsyncOut(); - - gatt_registering = false; - return Status::ok(); - } -}; - -void PrintCommandStatus(bool status) { PrintOpStatus("Command", status); } - -void PrintFieldAndValue(const string& field, const string& value) { - cout << COLOR_BOLDWHITE << field << ": " << COLOR_BOLDYELLOW << value - << COLOR_OFF << endl; -} - -void PrintFieldAndBoolValue(const string& field, bool value) { - PrintFieldAndValue(field, (value ? "true" : "false")); -} - -void HandleDisable(IBluetooth* bt_iface, const vector<string>& args) { - CHECK_NO_ARGS(args); - bool status; - bt_iface->Disable(&status); - PrintCommandStatus(status); -} - -void HandleEnable(IBluetooth* bt_iface, const vector<string>& args) { - bool status; - bt_iface->Enable(&status); - PrintCommandStatus(status); -} - -void HandleGetState(IBluetooth* bt_iface, const vector<string>& args) { - CHECK_NO_ARGS(args); - - int32_t st; - bt_iface->GetState(&st); - bluetooth::AdapterState state = static_cast<bluetooth::AdapterState>(st); - PrintFieldAndValue("Adapter state", bluetooth::AdapterStateToString(state)); -} - -void HandleIsEnabled(IBluetooth* bt_iface, const vector<string>& args) { - CHECK_NO_ARGS(args); - bool enabled; - bt_iface->IsEnabled(&enabled); - PrintFieldAndBoolValue("Adapter enabled", enabled); -} - -void HandleGetLocalAddress(IBluetooth* bt_iface, const vector<string>& args) { - CHECK_NO_ARGS(args); - String16 address; - bt_iface->GetAddress(&address); - PrintFieldAndValue("Adapter address", std::string(String8(address).string())); -} - -void HandleSetLocalName(IBluetooth* bt_iface, const vector<string>& args) { - CHECK_ARGS_COUNT(args, >=, 1, "No name was given"); - - std::string name; - for (const auto& arg : args) name += arg + " "; - - base::TrimWhitespaceASCII(name, base::TRIM_TRAILING, &name); - - bool status; - bt_iface->SetName(String16(String8(name.c_str())), &status); - PrintCommandStatus(status); -} - -void HandleGetLocalName(IBluetooth* bt_iface, const vector<string>& args) { - CHECK_NO_ARGS(args); - String16 name; - bt_iface->GetName(&name); - PrintFieldAndValue("Adapter name", std::string(String8(name).string())); -} - -void HandleAdapterInfo(IBluetooth* bt_iface, const vector<string>& args) { - CHECK_NO_ARGS(args); - - cout << COLOR_BOLDWHITE "Adapter Properties: " COLOR_OFF << endl; - - String16 address; - bt_iface->GetAddress(&address); - PrintFieldAndValue("\tAddress", std::string(String8(address).string())); - - int adapter_state; - bt_iface->GetState(&adapter_state); - PrintFieldAndValue("\tState", - bluetooth::AdapterStateToString( - static_cast<bluetooth::AdapterState>(adapter_state))); - - String16 name; - bt_iface->GetName(&name); - PrintFieldAndValue("\tName", std::string(String8(name).string())); - - bool multi_adv; - bt_iface->IsMultiAdvertisementSupported(&multi_adv); - PrintFieldAndBoolValue("\tMulti-Adv. supported", multi_adv); -} - -void HandleSupportsMultiAdv(IBluetooth* bt_iface, const vector<string>& args) { - CHECK_NO_ARGS(args); - - bool multi_adv; - bt_iface->IsMultiAdvertisementSupported(&multi_adv); - PrintFieldAndBoolValue("Multi-advertisement support", multi_adv); -} - -void HandleRegisterBLEAdvertiser(IBluetooth* bt_iface, - const vector<string>& args) { - CHECK_NO_ARGS(args); - - if (ble_advertiser_registering.load()) { - PrintError("In progress"); - return; - } - - if (ble_advertiser_id.load() != invalid_advertiser_id) { - PrintError("Already registered"); - return; - } - - sp<IBluetoothLeAdvertiser> ble_advertiser_iface; - bt_iface->GetLeAdvertiserInterface(&ble_advertiser_iface); - if (!ble_advertiser_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth Le Advertiser interface"); - return; - } - - bool status; - ble_advertiser_iface->RegisterAdvertiser( - new CLIBluetoothLeAdvertiserCallback(), &status); - ble_advertiser_registering = status; - PrintCommandStatus(status); -} - -void HandleUnregisterBLEAdvertiser(IBluetooth* bt_iface, - const vector<string>& args) { - CHECK_NO_ARGS(args); - - if (ble_advertiser_id.load() == invalid_advertiser_id) { - PrintError("Not registered"); - return; - } - - sp<IBluetoothLeAdvertiser> ble_advertiser_iface; - bt_iface->GetLeAdvertiserInterface(&ble_advertiser_iface); - if (!ble_advertiser_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth Low Energy interface"); - return; - } - - ble_advertiser_iface->UnregisterAdvertiser(ble_advertiser_id.load()); - ble_advertiser_id = invalid_advertiser_id; - PrintCommandStatus(true); -} - -void HandleRegisterBLE(IBluetooth* bt_iface, const vector<string>& args) { - CHECK_NO_ARGS(args); - - if (ble_registering.load()) { - PrintError("In progress"); - return; - } - - if (ble_client_id.load()) { - PrintError("Already registered"); - return; - } - - sp<IBluetoothLowEnergy> ble_iface; - bt_iface->GetLowEnergyInterface(&ble_iface); - if (!ble_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth Low Energy interface"); - return; - } - - bool status; - ble_iface->RegisterClient(new CLIBluetoothLowEnergyCallback(), &status); - ble_registering = status; - PrintCommandStatus(status); -} - -void HandleUnregisterBLE(IBluetooth* bt_iface, const vector<string>& args) { - CHECK_NO_ARGS(args); - - if (!ble_client_id.load()) { - PrintError("Not registered"); - return; - } - - sp<IBluetoothLowEnergy> ble_iface; - bt_iface->GetLowEnergyInterface(&ble_iface); - if (!ble_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth Low Energy interface"); - return; - } - - ble_iface->UnregisterClient(ble_client_id.load()); - ble_client_id = 0; - PrintCommandStatus(true); -} - -void HandleUnregisterAllBLE(IBluetooth* bt_iface, const vector<string>& args) { - CHECK_NO_ARGS(args); - - sp<IBluetoothLowEnergy> ble_iface; - bt_iface->GetLowEnergyInterface(&ble_iface); - if (!ble_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth Low Energy interface"); - return; - } - - ble_iface->UnregisterAll(); - PrintCommandStatus(true); -} - -void HandleRegisterGATT(IBluetooth* bt_iface, const vector<string>& args) { - CHECK_NO_ARGS(args); - - if (gatt_registering.load()) { - PrintError("In progress"); - return; - } - - if (gatt_client_id.load()) { - PrintError("Already registered"); - return; - } - - sp<IBluetoothGattClient> gatt_iface; - bt_iface->GetGattClientInterface(&gatt_iface); - if (!gatt_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth GATT Client interface"); - return; - } - - bool status; - gatt_iface->RegisterClient(new CLIGattClientCallback(), &status); - gatt_registering = status; - PrintCommandStatus(status); -} - -void HandleUnregisterGATT(IBluetooth* bt_iface, const vector<string>& args) { - CHECK_NO_ARGS(args); - - if (!gatt_client_id.load()) { - PrintError("Not registered"); - return; - } - - sp<IBluetoothGattClient> gatt_iface; - bt_iface->GetGattClientInterface(&gatt_iface); - if (!gatt_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth GATT Client interface"); - return; - } - - gatt_iface->UnregisterClient(gatt_client_id.load()); - gatt_client_id = 0; - PrintCommandStatus(true); -} - -void HandleStartAdv(IBluetooth* bt_iface, const vector<string>& args) { - bool include_name = false; - bool include_tx_power = false; - bool connectable = false; - bool set_manufacturer_data = false; - bool set_uuid = false; - bluetooth::Uuid uuid; - - for (auto iter = args.begin(); iter != args.end(); ++iter) { - const std::string& arg = *iter; - if (arg == "-n") - include_name = true; - else if (arg == "-t") - include_tx_power = true; - else if (arg == "-c") - connectable = true; - else if (arg == "-m") - set_manufacturer_data = true; - else if (arg == "-u") { - // This flag has a single argument. - ++iter; - if (iter == args.end()) { - PrintError("Expected a Uuid after -u"); - return; - } - - std::string uuid_str = *iter; - bool is_valid = false; - uuid = bluetooth::Uuid::FromString(uuid_str, &is_valid); - if (!is_valid) { - PrintError("Invalid Uuid: " + uuid_str); - return; - } - - set_uuid = true; - } else if (arg == "-h") { - static const char kUsage[] = - "Usage: start-adv [flags]\n" - "\n" - "Flags:\n" - "\t-n\tInclude device name\n" - "\t-t\tInclude TX power\n" - "\t-c\tSend connectable adv. packets (default is non-connectable)\n" - "\t-m\tInclude random manufacturer data\n" - "\t-h\tShow this help message\n"; - cout << kUsage << endl; - return; - } else { - PrintError("Unrecognized option: " + arg); - return; - } - } - - if (ble_advertiser_id.load() == invalid_advertiser_id) { - PrintError("BLE advertiser not registered"); - return; - } - - sp<IBluetoothLeAdvertiser> ble_advertiser_iface; - bt_iface->GetLeAdvertiserInterface(&ble_advertiser_iface); - if (!ble_advertiser_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth Le Advertiser interface"); - return; - } - - std::vector<uint8_t> data; - if (set_manufacturer_data) { - data = {{0x07, bluetooth::kEIRTypeManufacturerSpecificData, 0xe0, 0x00, 'T', - 'e', 's', 't'}}; - } - - if (set_uuid) { - // Determine the type and length bytes. - int uuid_size = uuid.GetShortestRepresentationSize(); - uint8_t type; - if (uuid_size == bluetooth::Uuid::kNumBytes128) - type = bluetooth::kEIRTypeComplete128BitUuids; - else if (uuid_size == bluetooth::Uuid::kNumBytes32) - type = bluetooth::kEIRTypeComplete32BitUuids; - else if (uuid_size == bluetooth::Uuid::kNumBytes16) - type = bluetooth::kEIRTypeComplete16BitUuids; - else - NOTREACHED() << "Unexpected size: " << uuid_size; - - data.push_back(uuid_size + 1); - data.push_back(type); - - auto uuid_bytes = uuid.To128BitLE(); - int index = (uuid_size == 16) ? 0 : 12; - data.insert(data.end(), uuid_bytes.data() + index, - uuid_bytes.data() + index + uuid_size); - } - - base::TimeDelta timeout; - - bluetooth::AdvertiseSettings settings( - bluetooth::AdvertiseSettings::MODE_LOW_POWER, timeout, - bluetooth::AdvertiseSettings::TX_POWER_LEVEL_MEDIUM, connectable); - - if (include_tx_power) { - data.push_back(0x02); - data.push_back(bluetooth::kEIRTypeTxPower); - data.push_back(0x00); - } - - bluetooth::AdvertiseData adv_data(data); - - if (include_name) { - String16 name_param; - bt_iface->GetName(&name_param); - std::string name(String8(name_param).string()); - data.push_back(name.length() + 1); - data.push_back(bluetooth::kEIRTypeCompleteLocalName); - data.insert(data.begin(), name.c_str(), name.c_str() + name.length()); - } - - bluetooth::AdvertiseData scan_rsp; - - bool status; - ble_advertiser_iface->StartMultiAdvertising( - ble_advertiser_id.load(), adv_data, scan_rsp, settings, &status); - PrintCommandStatus(status); -} - -void HandleStopAdv(IBluetooth* bt_iface, const vector<string>& args) { - if (ble_advertiser_id.load() == invalid_advertiser_id) { - PrintError("BLE advertiser not registered"); - return; - } - - sp<IBluetoothLeAdvertiser> ble_advertiser_iface; - bt_iface->GetLeAdvertiserInterface(&ble_advertiser_iface); - if (!ble_advertiser_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth Low Energy interface"); - return; - } - - bool status; - ble_advertiser_iface->StopMultiAdvertising(ble_advertiser_id.load(), &status); - PrintCommandStatus(status); -} - -void HandleConnect(IBluetooth* bt_iface, const vector<string>& args) { - string address; - - if (args.size() != 1) { - PrintError("Expected MAC address as only argument"); - return; - } - - address = args[0]; - - if (!ble_client_id.load()) { - PrintError("BLE not registered"); - return; - } - - sp<IBluetoothLowEnergy> ble_iface; - bt_iface->GetLowEnergyInterface(&ble_iface); - if (!ble_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth Low Energy interface"); - return; - } - - bool status; - ble_iface->Connect(ble_client_id.load(), - String16(address.c_str(), address.length()), - false /* is_direct */, &status); - - PrintCommandStatus(status); -} - -void HandleDisconnect(IBluetooth* bt_iface, const vector<string>& args) { - string address; - - if (args.size() != 1) { - PrintError("Expected MAC address as only argument"); - return; - } - - address = args[0]; - - if (!ble_client_id.load()) { - PrintError("BLE not registered"); - return; - } - - sp<IBluetoothLowEnergy> ble_iface; - bt_iface->GetLowEnergyInterface(&ble_iface); - if (!ble_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth Low Energy interface"); - return; - } - - bool status; - ble_iface->Disconnect(ble_client_id.load(), - String16(address.c_str(), address.length()), &status); - PrintCommandStatus(status); -} - -void HandleSetMtu(IBluetooth* bt_iface, const vector<string>& args) { - string address; - int mtu; - - if (args.size() != 2) { - PrintError("Usage: set-mtu [address] [mtu]"); - return; - } - - address = args[0]; - mtu = std::stoi(args[1]); - - if (mtu < 23) { - PrintError("MTU must be 23 or larger"); - return; - } - - if (!ble_client_id.load()) { - PrintError("BLE not registered"); - return; - } - - sp<IBluetoothLowEnergy> ble_iface; - bt_iface->GetLowEnergyInterface(&ble_iface); - if (!ble_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth Low Energy interface"); - return; - } - - bool status; - ble_iface->SetMtu(ble_client_id.load(), - String16(address.c_str(), address.length()), mtu, &status); - PrintCommandStatus(status); -} - -void HandleRegisterBLEScanner(IBluetooth* bt_iface, - const vector<string>& args) { - CHECK_NO_ARGS(args); - - if (ble_scanner_registering.load()) { - PrintError("In progress"); - return; - } - - if (ble_scanner_id.load()) { - PrintError("Already registered"); - return; - } - - sp<IBluetoothLeScanner> ble_scanner_iface; - bt_iface->GetLeScannerInterface(&ble_scanner_iface); - if (!ble_scanner_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth LE Scanner interface"); - return; - } - - bool status; - ble_scanner_iface->RegisterScanner(new CLIBluetoothLeScannerCallback(), - &status); - ble_scanner_registering = status; - PrintCommandStatus(status); -} - -void HandleUnregisterBLEScanner(IBluetooth* bt_iface, - const vector<string>& args) { - CHECK_NO_ARGS(args); - - if (!ble_scanner_id.load()) { - PrintError("Not registered"); - return; - } - - sp<IBluetoothLeScanner> ble_scanner_iface; - bt_iface->GetLeScannerInterface(&ble_scanner_iface); - if (!ble_scanner_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth LE scanner interface"); - return; - } - - ble_scanner_iface->UnregisterScanner(ble_scanner_id.load()); - ble_scanner_id = 0; - PrintCommandStatus(true); -} - -void HandleStartLeScan(IBluetooth* bt_iface, const vector<string>& args) { - if (!ble_client_id.load()) { - PrintError("BLE not registered"); - return; - } - - for (const auto& arg : args) { - if (arg == "-d") { - dump_scan_record = true; - } else if (arg == "-h") { - static const char kUsage[] = - "Usage: start-le-scan [flags]\n" - "\n" - "Flags:\n" - "\t-d\tDump scan record\n" - "\t-h\tShow this help message\n"; - cout << kUsage << endl; - return; - } - } - - sp<IBluetoothLeScanner> ble_scanner_iface; - bt_iface->GetLeScannerInterface(&ble_scanner_iface); - if (!ble_scanner_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth LE scanner interface"); - return; - } - - bluetooth::ScanSettings settings; - std::vector<android::bluetooth::ScanFilter> filters; - - bool status; - ble_scanner_iface->StartScan(ble_scanner_id.load(), settings, filters, - &status); - PrintCommandStatus(status); -} - -void HandleStopLeScan(IBluetooth* bt_iface, const vector<string>& args) { - if (!ble_client_id.load()) { - PrintError("BLE not registered"); - return; - } - - sp<IBluetoothLeScanner> ble_scanner_iface; - bt_iface->GetLeScannerInterface(&ble_scanner_iface); - if (!ble_scanner_iface.get()) { - PrintError("Failed to obtain handle to Bluetooth LE scanner interface"); - return; - } - - bool status; - ble_scanner_iface->StopScan(ble_scanner_id.load(), &status); - PrintCommandStatus(status); -} - -void HandleHelp(IBluetooth* bt_iface, const vector<string>& args); - -struct { - string command; - void (*func)(IBluetooth*, const vector<string>& args); - string help; -} kCommandMap[] = { - {"help", HandleHelp, "\t\t\tDisplay this message"}, - {"disable", HandleDisable, "\t\t\tDisable Bluetooth"}, - {"enable", HandleEnable, "\t\t\tEnable Bluetooth (-h for options)"}, - {"get-state", HandleGetState, "\t\tGet the current adapter state"}, - {"is-enabled", HandleIsEnabled, "\t\tReturn if Bluetooth is enabled"}, - {"get-local-address", HandleGetLocalAddress, - "\tGet the local adapter address"}, - {"set-local-name", HandleSetLocalName, "\t\tSet the local adapter name"}, - {"get-local-name", HandleGetLocalName, "\t\tGet the local adapter name"}, - {"adapter-info", HandleAdapterInfo, "\t\tPrint adapter properties"}, - {"supports-multi-adv", HandleSupportsMultiAdv, - "\tWhether multi-advertisement is currently supported"}, - {"register-le-advertiser", HandleRegisterBLEAdvertiser, - "\t\tRegister with the Bluetooth Low Energy Advertiser interface"}, - {"unregister-le-advertiser", HandleUnregisterBLEAdvertiser, - "\t\tUnregister from the Bluetooth LE Advertiser interface"}, - {"register-ble", HandleRegisterBLE, - "\t\tRegister with the Bluetooth Low Energy interface"}, - {"unregister-ble", HandleUnregisterBLE, - "\t\tUnregister from the Bluetooth Low Energy interface"}, - {"unregister-all-ble", HandleUnregisterAllBLE, - "\tUnregister all clients from the Bluetooth Low Energy interface"}, - {"register-gatt", HandleRegisterGATT, - "\t\tRegister with the Bluetooth GATT Client interface"}, - {"unregister-gatt", HandleUnregisterGATT, - "\t\tUnregister from the Bluetooth GATT Client interface"}, - {"connect-le", HandleConnect, "\t\tConnect to LE device (-h for options)"}, - {"disconnect-le", HandleDisconnect, - "\t\tDisconnect LE device (-h for options)"}, - {"set-mtu", HandleSetMtu, "\t\tSet MTU (-h for options)"}, - {"start-adv", HandleStartAdv, "\t\tStart advertising (-h for options)"}, - {"stop-adv", HandleStopAdv, "\t\tStop advertising"}, - {"register-le-scanner", HandleRegisterBLEScanner, - "\t\tRegister with the Bluetooth Low Energy scanner interface"}, - {"unregister-le-scanner", HandleUnregisterBLEScanner, - "\t\tUnregister from the Bluetooth LE scanner interface"}, - {"start-le-scan", HandleStartLeScan, - "\t\tStart LE device scan (-h for options)"}, - {"stop-le-scan", HandleStopLeScan, "\t\tStop LE device scan"}, - {}, -}; - -void HandleHelp(IBluetooth* /* bt_iface */, const vector<string>& /* args */) { - cout << endl; - for (int i = 0; kCommandMap[i].func; i++) - cout << "\t" << kCommandMap[i].command << kCommandMap[i].help << endl; - cout << endl; -} - -const char kExecuteLong[] = "exec"; -const char kExecuteShort[] = "e"; - -bool ExecuteCommand(const sp<IBluetooth>& bt_iface, std::string& command) { - vector<string> args = base::SplitString(command, " ", base::TRIM_WHITESPACE, - base::SPLIT_WANT_ALL); - - if (args.empty()) return true; - - // The first argument is the command while the remaining are what we pass to - // the handler functions. - command = args[0]; - args.erase(args.begin()); - - for (int i = 0; kCommandMap[i].func; i++) { - if (command == kCommandMap[i].command) { - kCommandMap[i].func(bt_iface.get(), args); - return true; - } - } - - cout << "Unrecognized command: " << command << endl; - return false; -} - -} // namespace - -class BluetoothDeathRecipient : public android::IBinder::DeathRecipient { - public: - BluetoothDeathRecipient() = default; - BluetoothDeathRecipient(const BluetoothDeathRecipient&) = delete; - BluetoothDeathRecipient& operator=(const BluetoothDeathRecipient&) = delete; - ~BluetoothDeathRecipient() override = default; - - // android::IBinder::DeathRecipient override: - void binderDied(const android::wp<android::IBinder>& /* who */) override { - BeginAsyncOut(); - cout << COLOR_BOLDWHITE "The Bluetooth daemon has died" COLOR_OFF << endl; - cout << "\nPress 'ENTER' to exit."; - EndAsyncOut(); - - android::IPCThreadState::self()->stopProcess(); - should_exit = true; - } -}; - -int main(int argc, char* argv[]) { - base::AtExitManager exit_manager; - base::CommandLine::Init(argc, argv); - logging::LoggingSettings log_settings; - - if (!logging::InitLogging(log_settings)) { - LOG(ERROR) << "Failed to set up logging"; - return EXIT_FAILURE; - } - - sp<IBluetooth> bt_iface; - status_t status = getService(String16(kServiceName.c_str()), &bt_iface); - if (status != OK) { - LOG(ERROR) << "Failed to get service binder: '" << kServiceName - << "' status=" << status; - return EXIT_FAILURE; - } - - sp<BluetoothDeathRecipient> dr(new BluetoothDeathRecipient()); - if (android::IInterface::asBinder(bt_iface.get())->linkToDeath(dr) != - android::NO_ERROR) { - LOG(ERROR) << "Failed to register DeathRecipient for IBluetooth"; - return EXIT_FAILURE; - } - - // Initialize the Binder process thread pool. We have to set this up, - // otherwise, incoming callbacks from IBluetoothCallback will block the main - // thread (in other words, we have to do this as we are a "Binder server"). - android::ProcessState::self()->startThreadPool(); - - // Register Adapter state-change callback - sp<CLIBluetoothCallback> callback = new CLIBluetoothCallback(); - bt_iface->RegisterCallback(callback); - - cout << COLOR_BOLDWHITE << "Fluoride Command-Line Interface\n" - << COLOR_OFF << endl - << "Type \"help\" to see possible commands.\n" - << endl; - - string command; - - // Add commands from the command line, if they exist. - auto command_line = base::CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(kExecuteLong)) { - command += command_line->GetSwitchValueASCII(kExecuteLong); - } - - if (command_line->HasSwitch(kExecuteShort)) { - if (!command.empty()) command += " ; "; - command += command_line->GetSwitchValueASCII(kExecuteShort); - } - - while (true) { - vector<string> commands = base::SplitString( - command, ";", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); - for (string command : commands) { - if (!ExecuteCommand(bt_iface, command)) break; - } - - commands.clear(); - - PrintPrompt(); - - showing_prompt = true; - auto& istream = getline(cin, command); - showing_prompt = false; - - if (istream.eof() || should_exit.load()) { - cout << "\nExiting" << endl; - return EXIT_SUCCESS; - } - - if (!istream.good()) { - LOG(ERROR) << "An error occured while reading input"; - return EXIT_FAILURE; - } - } - - return EXIT_SUCCESS; -} diff --git a/system/service/common/Android.bp b/system/service/common/Android.bp deleted file mode 100644 index b61e4ffba7..0000000000 --- a/system/service/common/Android.bp +++ /dev/null @@ -1,111 +0,0 @@ -// Bluetooth types -package { - // See: http://go/android-license-faq - // A large-scale-change added 'default_applicable_licenses' to import - // all of the 'license_kinds' from "system_bt_license" - // to get the below license kinds: - // SPDX-license-identifier-Apache-2.0 - default_applicable_licenses: ["system_bt_license"], -} - -cc_library_static { - name: "libbluetooth-common", - defaults: ["fluoride_defaults"], - cflags: [ - /* we export all classes, so change default visibility, instead of having EXPORT_SYMBOL on each class*/ - "-fvisibility=default", - ], - host_supported: true, - header_libs: ["libbluetooth_headers"], - srcs: [ - "bluetooth/a2dp_codec_config.cc", - "bluetooth/adapter_state.cc", - "bluetooth/advertise_data.cc", - "bluetooth/advertise_settings.cc", - "bluetooth/avrcp_int_value.cc", - "bluetooth/avrcp_media_attr.cc", - "bluetooth/avrcp_register_notification_response.cc", - "bluetooth/characteristic.cc", - "bluetooth/descriptor.cc", - "bluetooth/remote_device_props.cc", - "bluetooth/scan_filter.cc", - "bluetooth/scan_result.cc", - "bluetooth/scan_settings.cc", - "bluetooth/service.cc", - "bluetooth/util/atomic_string.cc", - ], - export_include_dirs: ["./"], - include_dirs: ["packages/modules/Bluetooth/system"], - shared_libs: [ - "libbase", - ], -} - -// Bluetooth Binder shared library -cc_library_static { - name: "libbluetooth-binder-common", - visibility:[ - "//packages/apps/Test/connectivity/sl4n", - "//packages/modules/Bluetooth:__subpackages__", - ], - defaults: ["fluoride_defaults"], - cflags: [ - /* we export all classes, so change default visibility, instead of having EXPORT_SYMBOL on each class*/ - "-fvisibility=default", - ], - header_libs: ["libbluetooth_headers"], - srcs: [ - "android/bluetooth/IBluetooth.aidl", - "android/bluetooth/IBluetoothA2dpSink.aidl", - "android/bluetooth/IBluetoothA2dpSinkCallback.aidl", - "android/bluetooth/IBluetoothA2dpSource.aidl", - "android/bluetooth/IBluetoothA2dpSourceCallback.aidl", - "android/bluetooth/IBluetoothAvrcpControl.aidl", - "android/bluetooth/IBluetoothAvrcpControlCallback.aidl", - "android/bluetooth/IBluetoothAvrcpTarget.aidl", - "android/bluetooth/IBluetoothAvrcpTargetCallback.aidl", - "android/bluetooth/IBluetoothCallback.aidl", - "android/bluetooth/IBluetoothGattClient.aidl", - "android/bluetooth/IBluetoothGattClientCallback.aidl", - "android/bluetooth/IBluetoothGattServer.aidl", - "android/bluetooth/IBluetoothGattServerCallback.aidl", - "android/bluetooth/IBluetoothLeAdvertiser.aidl", - "android/bluetooth/IBluetoothLeAdvertiserCallback.aidl", - "android/bluetooth/IBluetoothLeScanner.aidl", - "android/bluetooth/IBluetoothLeScannerCallback.aidl", - "android/bluetooth/IBluetoothLowEnergy.aidl", - "android/bluetooth/IBluetoothLowEnergyCallback.aidl", - "android/bluetooth/advertise_data.cc", - "android/bluetooth/advertise_settings.cc", - "android/bluetooth/bluetooth_a2dp_codec_config.cc", - "android/bluetooth/bluetooth_avrcp_int_value.cc", - "android/bluetooth/bluetooth_avrcp_media_attr.cc", - "android/bluetooth/bluetooth_avrcp_register_notification_response.cc", - "android/bluetooth/bluetooth_avrcp_string_value.cc", - "android/bluetooth/bluetooth_gatt_characteristic.cc", - "android/bluetooth/bluetooth_gatt_descriptor.cc", - "android/bluetooth/bluetooth_gatt_included_service.cc", - "android/bluetooth/bluetooth_gatt_service.cc", - "android/bluetooth/bluetooth_remote_device_props.cc", - "android/bluetooth/scan_filter.cc", - "android/bluetooth/scan_result.cc", - "android/bluetooth/scan_settings.cc", - "android/bluetooth/uuid.cc", - ], - aidl: { - export_aidl_headers: true, - include_dirs: [ - "frameworks/native/aidl/binder", - "packages/modules/Bluetooth/system/service/common", - ], - }, - export_include_dirs: ["./"], - whole_static_libs: ["libbluetooth-common"], - shared_libs: [ - "libbase", - "libbinder", - ], - static_libs: [ - "libbluetooth-types", - ], -} diff --git a/system/service/common/BUILD.gn b/system/service/common/BUILD.gn deleted file mode 100644 index 06101d7664..0000000000 --- a/system/service/common/BUILD.gn +++ /dev/null @@ -1,42 +0,0 @@ -# -# Copyright 2021 Google -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at: -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -source_set("libbluetooth_common") { - sources = [ - "bluetooth/a2dp_codec_config.cc", - "bluetooth/adapter_state.cc", - "bluetooth/advertise_data.cc", - "bluetooth/advertise_settings.cc", - "bluetooth/avrcp_int_value.cc", - "bluetooth/avrcp_media_attr.cc", - "bluetooth/avrcp_register_notification_response.cc", - "bluetooth/characteristic.cc", - "bluetooth/descriptor.cc", - "bluetooth/remote_device_props.cc", - "bluetooth/scan_filter.cc", - "bluetooth/scan_result.cc", - "bluetooth/scan_settings.cc", - "bluetooth/service.cc", - "bluetooth/util/atomic_string.cc", - ] - - include_dirs = [ - ".", - "//bt/system", - ] - - configs += ["//bt/system:target_defaults"] -} diff --git a/system/service/common/README b/system/service/common/README deleted file mode 100644 index 55f95fa607..0000000000 --- a/system/service/common/README +++ /dev/null @@ -1,12 +0,0 @@ -This directory contains all the "common" sources between the bluetooth daemon -and our client library. All source files here are under the "bluetooth" -subdirectory, which is the exported root path for the client static library. -Only common files should go here. All headers that go into common/bluetooth must -only include other headers from common/bluetooth and must use "bluetooth" as the -root path, e.g.: - -#include <bluetooth/uuid.h> - -This is so that client applications that link against the client library have -one common include path exported to them, and our headers can find eachother -within that. diff --git a/system/service/common/android/bluetooth/AdvertiseData.aidl b/system/service/common/android/bluetooth/AdvertiseData.aidl deleted file mode 100644 index 9250f568d8..0000000000 --- a/system/service/common/android/bluetooth/AdvertiseData.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable AdvertiseData cpp_header "android/bluetooth/advertise_data.h"; diff --git a/system/service/common/android/bluetooth/AdvertiseSettings.aidl b/system/service/common/android/bluetooth/AdvertiseSettings.aidl deleted file mode 100644 index cc801ec71b..0000000000 --- a/system/service/common/android/bluetooth/AdvertiseSettings.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable AdvertiseSettings cpp_header "android/bluetooth/advertise_settings.h"; diff --git a/system/service/common/android/bluetooth/BluetoothA2dpCodecConfig.aidl b/system/service/common/android/bluetooth/BluetoothA2dpCodecConfig.aidl deleted file mode 100644 index 083cd75128..0000000000 --- a/system/service/common/android/bluetooth/BluetoothA2dpCodecConfig.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable BluetoothA2dpCodecConfig cpp_header "android/bluetooth/bluetooth_a2dp_codec_config.h"; diff --git a/system/service/common/android/bluetooth/BluetoothAvrcpIntValue.aidl b/system/service/common/android/bluetooth/BluetoothAvrcpIntValue.aidl deleted file mode 100644 index e126393e3a..0000000000 --- a/system/service/common/android/bluetooth/BluetoothAvrcpIntValue.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable BluetoothAvrcpIntValue cpp_header "android/bluetooth/bluetooth_avrcp_int_value.h"; diff --git a/system/service/common/android/bluetooth/BluetoothAvrcpMediaAttr.aidl b/system/service/common/android/bluetooth/BluetoothAvrcpMediaAttr.aidl deleted file mode 100644 index 03355ac5b4..0000000000 --- a/system/service/common/android/bluetooth/BluetoothAvrcpMediaAttr.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable BluetoothAvrcpMediaAttr cpp_header "android/bluetooth/bluetooth_avrcp_media_attr.h"; diff --git a/system/service/common/android/bluetooth/BluetoothAvrcpRegisterNotificationResponse.aidl b/system/service/common/android/bluetooth/BluetoothAvrcpRegisterNotificationResponse.aidl deleted file mode 100644 index 147a1876b2..0000000000 --- a/system/service/common/android/bluetooth/BluetoothAvrcpRegisterNotificationResponse.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable BluetoothAvrcpRegisterNotificationResponse cpp_header "android/bluetooth/bluetooth_avrcp_register_notification_response.h"; diff --git a/system/service/common/android/bluetooth/BluetoothAvrcpStringValue.aidl b/system/service/common/android/bluetooth/BluetoothAvrcpStringValue.aidl deleted file mode 100644 index 5bbfbd4b78..0000000000 --- a/system/service/common/android/bluetooth/BluetoothAvrcpStringValue.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable BluetoothAvrcpStringValue cpp_header "android/bluetooth/bluetooth_avrcp_string_value.h"; diff --git a/system/service/common/android/bluetooth/BluetoothGattCharacteristic.aidl b/system/service/common/android/bluetooth/BluetoothGattCharacteristic.aidl deleted file mode 100644 index 6c6922e9fd..0000000000 --- a/system/service/common/android/bluetooth/BluetoothGattCharacteristic.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable BluetoothGattCharacteristic cpp_header "android/bluetooth/bluetooth_gatt_characteristic.h"; diff --git a/system/service/common/android/bluetooth/BluetoothGattDescriptor.aidl b/system/service/common/android/bluetooth/BluetoothGattDescriptor.aidl deleted file mode 100644 index 5f6ed2740e..0000000000 --- a/system/service/common/android/bluetooth/BluetoothGattDescriptor.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable BluetoothGattDescriptor cpp_header "android/bluetooth/bluetooth_gatt_descriptor.h"; diff --git a/system/service/common/android/bluetooth/BluetoothGattIncludedService.aidl b/system/service/common/android/bluetooth/BluetoothGattIncludedService.aidl deleted file mode 100644 index 44fded017b..0000000000 --- a/system/service/common/android/bluetooth/BluetoothGattIncludedService.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable BluetoothGattIncludedService cpp_header "android/bluetooth/bluetooth_gatt_included_service.h"; diff --git a/system/service/common/android/bluetooth/BluetoothGattService.aidl b/system/service/common/android/bluetooth/BluetoothGattService.aidl deleted file mode 100644 index 04dba09444..0000000000 --- a/system/service/common/android/bluetooth/BluetoothGattService.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable BluetoothGattService cpp_header "android/bluetooth/bluetooth_gatt_service.h"; diff --git a/system/service/common/android/bluetooth/BluetoothRemoteDeviceProps.aidl b/system/service/common/android/bluetooth/BluetoothRemoteDeviceProps.aidl deleted file mode 100644 index db8029595e..0000000000 --- a/system/service/common/android/bluetooth/BluetoothRemoteDeviceProps.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable BluetoothRemoteDeviceProps cpp_header "android/bluetooth/bluetooth_remote_device_props.h"; diff --git a/system/service/common/android/bluetooth/IBluetooth.aidl b/system/service/common/android/bluetooth/IBluetooth.aidl deleted file mode 100644 index 46c7654b21..0000000000 --- a/system/service/common/android/bluetooth/IBluetooth.aidl +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.IBluetoothCallback; -import android.bluetooth.IBluetoothLowEnergy; -import android.bluetooth.IBluetoothLeAdvertiser; -import android.bluetooth.IBluetoothLeScanner; -import android.bluetooth.IBluetoothGattClient; -import android.bluetooth.IBluetoothGattServer; -import android.bluetooth.IBluetoothA2dpSink; -import android.bluetooth.IBluetoothA2dpSource; -import android.bluetooth.IBluetoothAvrcpControl; -import android.bluetooth.IBluetoothAvrcpTarget; - -import android.bluetooth.UUID; - -interface IBluetooth { - boolean IsEnabled(); - int GetState(); - boolean Enable(); - boolean EnableNoAutoConnect(); - boolean Disable(); - - String GetAddress(); - UUID[] GetUUIDs(); - boolean SetName(String name); - String GetName(); - boolean SetScanMode(int scan_mode); - boolean SetScanEnable(boolean scan_enable); - boolean SspReply( - String device_address, - int variant, - boolean accept, - int passkey); - boolean CreateBond(String device_address, int transport); - boolean GetBondedDevices(); - boolean RemoveBond(String device_address); - boolean GetRemoteDeviceProperties(String device_address); - - void RegisterCallback(IBluetoothCallback callback); - void UnregisterCallback(IBluetoothCallback callback); - - boolean IsMultiAdvertisementSupported(); - - IBluetoothLowEnergy GetLowEnergyInterface(); - IBluetoothLeAdvertiser GetLeAdvertiserInterface(); - IBluetoothLeScanner GetLeScannerInterface(); - IBluetoothGattClient GetGattClientInterface(); - IBluetoothGattServer GetGattServerInterface(); - IBluetoothA2dpSink GetA2dpSinkInterface(); - IBluetoothA2dpSource GetA2dpSourceInterface(); - IBluetoothAvrcpControl GetAvrcpControlInterface(); - IBluetoothAvrcpTarget GetAvrcpTargetInterface(); -} diff --git a/system/service/common/android/bluetooth/IBluetoothA2dpSink.aidl b/system/service/common/android/bluetooth/IBluetoothA2dpSink.aidl deleted file mode 100644 index dec7d28ace..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothA2dpSink.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.IBluetoothA2dpSinkCallback; - -interface IBluetoothA2dpSink { - boolean Register(in IBluetoothA2dpSinkCallback callback); - void Unregister(); - - boolean Enable(); - boolean Disable(); - boolean Connect(String device_address); - boolean Disconnect(String device_address); - boolean SetAudioFocusState(int state); - boolean SetAudioTrackGain(float gain); -} diff --git a/system/service/common/android/bluetooth/IBluetoothA2dpSinkCallback.aidl b/system/service/common/android/bluetooth/IBluetoothA2dpSinkCallback.aidl deleted file mode 100644 index e12be244a8..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothA2dpSinkCallback.aidl +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -oneway interface IBluetoothA2dpSinkCallback { - void OnRegistered(int status); - void OnConnectionState(String device_address, int state); - void OnAudioState(String device_address, int state); - void OnAudioConfig(String device_address, int sample_rate, int channel_count); -} diff --git a/system/service/common/android/bluetooth/IBluetoothA2dpSource.aidl b/system/service/common/android/bluetooth/IBluetoothA2dpSource.aidl deleted file mode 100644 index 344292c438..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothA2dpSource.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.IBluetoothA2dpSourceCallback; -import android.bluetooth.BluetoothA2dpCodecConfig; - -interface IBluetoothA2dpSource { - boolean Register(in IBluetoothA2dpSourceCallback callback); - void Unregister(); - - boolean Enable(in BluetoothA2dpCodecConfig[] codec_priorities); - boolean Disable(); - boolean Connect(String device_address); - boolean Disconnect(String device_address); - boolean ConfigCodec(String device_address, - in BluetoothA2dpCodecConfig[] codec_preferences); - -} diff --git a/system/service/common/android/bluetooth/IBluetoothA2dpSourceCallback.aidl b/system/service/common/android/bluetooth/IBluetoothA2dpSourceCallback.aidl deleted file mode 100644 index 4d4a82de2a..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothA2dpSourceCallback.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.BluetoothA2dpCodecConfig; - -oneway interface IBluetoothA2dpSourceCallback { - void OnRegistered(int status); - void OnConnectionState(String device_address, int state); - void OnAudioState(String device_address, int state); - void OnAudioConfig( - String device_address, - in BluetoothA2dpCodecConfig codec_config, - in BluetoothA2dpCodecConfig[] codecs_local_capabilities, - in BluetoothA2dpCodecConfig[] codecs_selectable_capabilities); -} diff --git a/system/service/common/android/bluetooth/IBluetoothAvrcpControl.aidl b/system/service/common/android/bluetooth/IBluetoothAvrcpControl.aidl deleted file mode 100644 index 0e65a71796..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothAvrcpControl.aidl +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.IBluetoothAvrcpControlCallback; - -interface IBluetoothAvrcpControl { - boolean Register(in IBluetoothAvrcpControlCallback callback); - void Unregister(int id); - void UnregisterAll(); - - boolean Enable(int id); - boolean Disable(int id); - - boolean SendPassThroughCommand(int id, String device_address, - int key_code, boolean key_pressed); - - boolean SetAbsVolumeResponse(int id, String device_address, int abs_vol, - int label); - - boolean RegisterForAbsVolumeCallbackResponse(int id, String device_address, - int response_type, int abs_vol, int label); -} diff --git a/system/service/common/android/bluetooth/IBluetoothAvrcpControlCallback.aidl b/system/service/common/android/bluetooth/IBluetoothAvrcpControlCallback.aidl deleted file mode 100644 index 68f0db2a04..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothAvrcpControlCallback.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.BluetoothAvrcpMediaAttr; - -oneway interface IBluetoothAvrcpControlCallback { - void OnRegistered(int status, int id); - void OnConnectionState( - boolean rc_connect, - boolean bt_connect, - String device_address); - - void OnTrackChanged(String device_address, in BluetoothAvrcpMediaAttr track_info); - void OnSetAbsVolumeRequest(String device_address, int abs_vol, int label); - void OnRegisterForAbsVolumeCallbackRequest(String device_address, int label); -} diff --git a/system/service/common/android/bluetooth/IBluetoothAvrcpTarget.aidl b/system/service/common/android/bluetooth/IBluetoothAvrcpTarget.aidl deleted file mode 100644 index 6654f868ac..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothAvrcpTarget.aidl +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.IBluetoothAvrcpTargetCallback; - -import android.bluetooth.BluetoothAvrcpIntValue; -import android.bluetooth.BluetoothAvrcpStringValue; -import android.bluetooth.BluetoothAvrcpRegisterNotificationResponse; - -interface IBluetoothAvrcpTarget { - boolean Register(in IBluetoothAvrcpTargetCallback callback); - void Unregister(int id); - void UnregisterAll(); - - boolean Enable(); - boolean Disable(); - - boolean GetPlayStatusResponse(String addr, - int play_status, int song_len, int song_pos); - - boolean ListPlayerAppAttrResponse(String addr, in int[] attrs); - - boolean GetPlayerAppValueResponse(String addr, - in BluetoothAvrcpIntValue[] values); - - boolean GetPlayerAppAttrTextResponse(String addr, - in BluetoothAvrcpStringValue[] attrs); - - boolean GetPlayerAppValueTextResponse(String addr, - in BluetoothAvrcpStringValue[] values); - - boolean GetElementAttrResponse(String addr, - in BluetoothAvrcpStringValue[] attrs); - - boolean SetPlayerAppValueResponse(String addr, int rsp_status); - - boolean RegisterNotificationResponse( - int event_id, - int type, - in BluetoothAvrcpRegisterNotificationResponse param); - - boolean SetVolume(int volume); -} diff --git a/system/service/common/android/bluetooth/IBluetoothAvrcpTargetCallback.aidl b/system/service/common/android/bluetooth/IBluetoothAvrcpTargetCallback.aidl deleted file mode 100644 index 15d45f382b..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothAvrcpTargetCallback.aidl +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.BluetoothAvrcpIntValue; - -oneway interface IBluetoothAvrcpTargetCallback { - void OnRegistered(int status); - void OnGetRemoteFeatures(String addr, int features); - void OnGetPlayStatus(String addr); - void OnListPlayerAppAttr(String addr); - void OnListPlayerAppValues(String addr, int attr_id); - void OnGetPlayerAppValue(String addr, in int[] attrs); - void OnGetPlayerAppAttrsText(String addr, in int[] attrs); - void OnGetPlayerAppValuesText(String addr, int attr_id, in int[] values); - void OnSetPlayerAppValue(String addr, in BluetoothAvrcpIntValue[] values); - void OnGetElementAttrs(String addr, in int[] attrs); - void OnRegisterNotification(String addr, int event_id, int param); - void OnVolumeChange(String addr, int volume, int ctype); - void OnPassThroughCommand(String addr, int id, int key_state); -} diff --git a/system/service/common/android/bluetooth/IBluetoothCallback.aidl b/system/service/common/android/bluetooth/IBluetoothCallback.aidl deleted file mode 100644 index a83d5d8179..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothCallback.aidl +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.BluetoothRemoteDeviceProps; - -oneway interface IBluetoothCallback { - void OnBluetoothStateChange(int prev_state, int new_state); - void OnScanEnableChanged(boolean scan_enabled); - void OnDeviceConnectionStateChanged( - String device_address, - boolean connected); - void OnSspRequest( - String device_address, - String device_name, - int cod, - int pairing_variant, - int pass_key); - void OnGetBondedDevices(int status, in String[] device_addresses); - void OnBondStateChanged(int status, String device_address, int state); - void OnGetRemoteDeviceProperties( - int status, - String device_address, - in BluetoothRemoteDeviceProps props); - void OnDeviceFound( - in BluetoothRemoteDeviceProps props); -} diff --git a/system/service/common/android/bluetooth/IBluetoothGattClient.aidl b/system/service/common/android/bluetooth/IBluetoothGattClient.aidl deleted file mode 100644 index 3af3831caf..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothGattClient.aidl +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.IBluetoothGattClientCallback; - -interface IBluetoothGattClient { - - boolean RegisterClient(in IBluetoothGattClientCallback callback); - void UnregisterClient(int client_id); - void UnregisterAll(); -} diff --git a/system/service/common/android/bluetooth/IBluetoothGattClientCallback.aidl b/system/service/common/android/bluetooth/IBluetoothGattClientCallback.aidl deleted file mode 100644 index c4f46336de..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothGattClientCallback.aidl +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -oneway interface IBluetoothGattClientCallback { - void OnClientRegistered(int status, int client_id); -} diff --git a/system/service/common/android/bluetooth/IBluetoothGattServer.aidl b/system/service/common/android/bluetooth/IBluetoothGattServer.aidl deleted file mode 100644 index e48fd86d07..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothGattServer.aidl +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.BluetoothGattService; -import android.bluetooth.IBluetoothGattServerCallback; -import android.bluetooth.UUID; - -interface IBluetoothGattServer { - - boolean RegisterServer(in IBluetoothGattServerCallback callback); - void UnregisterServer(int server_id); - void UnregisterAll(); - - boolean AddService(int server_id, in BluetoothGattService service); - - boolean SendResponse( - int server_id, - String device_address, - int request_id, - int status, int offset, - in byte[] value); - - boolean SendNotification( - int server_id, - String device_address, - int handle, - boolean confirm, - in byte[] value); -} diff --git a/system/service/common/android/bluetooth/IBluetoothGattServerCallback.aidl b/system/service/common/android/bluetooth/IBluetoothGattServerCallback.aidl deleted file mode 100644 index 9c91770983..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothGattServerCallback.aidl +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.BluetoothGattService; - -oneway interface IBluetoothGattServerCallback { - void OnServerRegistered(int status, int server_id); - - void OnServiceAdded(int status, in BluetoothGattService service); - - void OnCharacteristicReadRequest(String device_address, - int request_id, int offset, boolean is_long, int handle); - - void OnDescriptorReadRequest(String device_address, - int request_id, int offset, boolean is_long, int handle); - - void OnCharacteristicWriteRequest(String device_address, - int request_id, int offset, boolean is_prepare_write, boolean need_response, - in byte[] value, int handle); - - void OnDescriptorWriteRequest(String device_address, - int request_id, int offset, boolean is_prepare_write, boolean need_response, - in byte[] value, int handle); - - void OnExecuteWriteRequest(String device_address, - int request_id, boolean is_execute); - - void OnNotificationSent(String device_address, - int status); - - void OnConnectionStateChanged(String device_address, boolean connected); - } diff --git a/system/service/common/android/bluetooth/IBluetoothLeAdvertiser.aidl b/system/service/common/android/bluetooth/IBluetoothLeAdvertiser.aidl deleted file mode 100644 index d5e4fca1e1..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothLeAdvertiser.aidl +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.IBluetoothLeAdvertiserCallback; - -import android.bluetooth.AdvertiseData; -import android.bluetooth.AdvertiseSettings; - -interface IBluetoothLeAdvertiser { - boolean RegisterAdvertiser(in IBluetoothLeAdvertiserCallback callback); - void UnregisterAdvertiser(int advertiser_id); - void UnregisterAll(); - - boolean StartMultiAdvertising( - int advertiser_id, - in AdvertiseData advertise_data, - in AdvertiseData scan_response, - in AdvertiseSettings settings); - boolean StopMultiAdvertising(int advertiser_id); -}
\ No newline at end of file diff --git a/system/service/common/android/bluetooth/IBluetoothLeAdvertiserCallback.aidl b/system/service/common/android/bluetooth/IBluetoothLeAdvertiserCallback.aidl deleted file mode 100644 index d9032e2944..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothLeAdvertiserCallback.aidl +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.AdvertiseSettings; - -oneway interface IBluetoothLeAdvertiserCallback { - void OnAdvertiserRegistered(int status, int advertiser_id); - void OnMultiAdvertiseCallback(int status, boolean is_start, in AdvertiseSettings settings); -}
\ No newline at end of file diff --git a/system/service/common/android/bluetooth/IBluetoothLeScanner.aidl b/system/service/common/android/bluetooth/IBluetoothLeScanner.aidl deleted file mode 100644 index 7d300e2386..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothLeScanner.aidl +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.IBluetoothLeScannerCallback; -import android.bluetooth.ScanFilter; -import android.bluetooth.ScanSettings; - -interface IBluetoothLeScanner { - boolean RegisterScanner(in IBluetoothLeScannerCallback callback); - void UnregisterScanner(int scanner_id); - void UnregisterAll(); - - boolean StartScan(int client_id, - in ScanSettings settings, - in ScanFilter[] filters); - boolean StopScan(int client_id); -} diff --git a/system/service/common/android/bluetooth/IBluetoothLeScannerCallback.aidl b/system/service/common/android/bluetooth/IBluetoothLeScannerCallback.aidl deleted file mode 100644 index 868b9cb22a..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothLeScannerCallback.aidl +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.ScanResult; - -oneway interface IBluetoothLeScannerCallback { - void OnScannerRegistered(int status, int client_id); - void OnScanResult(in ScanResult scan_result); -}
\ No newline at end of file diff --git a/system/service/common/android/bluetooth/IBluetoothLowEnergy.aidl b/system/service/common/android/bluetooth/IBluetoothLowEnergy.aidl deleted file mode 100644 index 63470d0b64..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothLowEnergy.aidl +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.IBluetoothLowEnergyCallback; - -import android.bluetooth.AdvertiseData; -import android.bluetooth.AdvertiseSettings; - -interface IBluetoothLowEnergy { - boolean RegisterClient(in IBluetoothLowEnergyCallback callback); - void UnregisterClient(int client_if); - void UnregisterAll(); - - boolean Connect(int client_id, String address, boolean is_direct); - boolean Disconnect(int client_id, String address); - - boolean SetMtu(int client_id, String address, int mtu); -}
\ No newline at end of file diff --git a/system/service/common/android/bluetooth/IBluetoothLowEnergyCallback.aidl b/system/service/common/android/bluetooth/IBluetoothLowEnergyCallback.aidl deleted file mode 100644 index ed9803bf08..0000000000 --- a/system/service/common/android/bluetooth/IBluetoothLowEnergyCallback.aidl +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -import android.bluetooth.ScanResult; -import android.bluetooth.AdvertiseSettings; - -oneway interface IBluetoothLowEnergyCallback { - void OnClientRegistered(int status, int client_id); - void OnConnectionState(int status, int client_id, String address, boolean connected); - void OnMtuChanged(int status, String address, int mtu); -}
\ No newline at end of file diff --git a/system/service/common/android/bluetooth/ScanFilter.aidl b/system/service/common/android/bluetooth/ScanFilter.aidl deleted file mode 100644 index 27d1ad87ac..0000000000 --- a/system/service/common/android/bluetooth/ScanFilter.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable ScanFilter cpp_header "android/bluetooth/scan_filter.h"; diff --git a/system/service/common/android/bluetooth/ScanResult.aidl b/system/service/common/android/bluetooth/ScanResult.aidl deleted file mode 100644 index 3eac01b93e..0000000000 --- a/system/service/common/android/bluetooth/ScanResult.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable ScanResult cpp_header "android/bluetooth/scan_result.h"; diff --git a/system/service/common/android/bluetooth/ScanSettings.aidl b/system/service/common/android/bluetooth/ScanSettings.aidl deleted file mode 100644 index 19b24c9658..0000000000 --- a/system/service/common/android/bluetooth/ScanSettings.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable ScanSettings cpp_header "android/bluetooth/scan_settings.h"; diff --git a/system/service/common/android/bluetooth/UUID.aidl b/system/service/common/android/bluetooth/UUID.aidl deleted file mode 100644 index be09aaa339..0000000000 --- a/system/service/common/android/bluetooth/UUID.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.bluetooth; - -parcelable UUID cpp_header "android/bluetooth/uuid.h"; diff --git a/system/service/common/android/bluetooth/advertise_data.cc b/system/service/common/android/bluetooth/advertise_data.cc deleted file mode 100644 index 75e5c59e17..0000000000 --- a/system/service/common/android/bluetooth/advertise_data.cc +++ /dev/null @@ -1,35 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/advertise_data.h" - -using android::OK; - -namespace android { -namespace bluetooth { - -status_t AdvertiseData::writeToParcel(Parcel* parcel) const { - status_t status = parcel->writeByteVector(data_); - return status; -} - -status_t AdvertiseData::readFromParcel(const Parcel* parcel) { - status_t status = parcel->readByteVector(&data_); - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/advertise_data.h b/system/service/common/android/bluetooth/advertise_data.h deleted file mode 100644 index 7543f050ce..0000000000 --- a/system/service/common/android/bluetooth/advertise_data.h +++ /dev/null @@ -1,54 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include "bluetooth/advertise_data.h" - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class AdvertiseData : public Parcelable, public ::bluetooth::AdvertiseData { - public: - // NOLINT, implicit converter - AdvertiseData(const ::bluetooth::AdvertiseData& advertise_data) // NOLINT - : ::bluetooth::AdvertiseData(advertise_data){}; - AdvertiseData() = default; - ~AdvertiseData() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; -}; -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/advertise_settings.cc b/system/service/common/android/bluetooth/advertise_settings.cc deleted file mode 100644 index affc7be0eb..0000000000 --- a/system/service/common/android/bluetooth/advertise_settings.cc +++ /dev/null @@ -1,67 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/advertise_settings.h" - -using android::OK; - -namespace android { -namespace bluetooth { - -status_t AdvertiseSettings::writeToParcel(Parcel* parcel) const { - status_t status = parcel->writeInt32(mode_); - if (status != OK) return status; - - status = parcel->writeInt32(tx_power_level_); - if (status != OK) return status; - - status = parcel->writeInt32(connectable_); - if (status != OK) return status; - - status = parcel->writeInt32(timeout_.InMilliseconds()); - return status; -} - -status_t AdvertiseSettings::readFromParcel(const Parcel* parcel) { - int32_t value; - status_t status = parcel->readInt32(&value); - if (status != OK) return status; - - mode_ = static_cast<AdvertiseSettings::Mode>(value); - - status = parcel->readInt32(&value); - if (status != OK) return status; - - tx_power_level_ = static_cast<AdvertiseSettings::TxPowerLevel>(value); - - status = parcel->readInt32(&value); - if (status != OK) return status; - - connectable_ = static_cast<bool>(value); - - status = parcel->readInt32(&value); - if (status != OK) return status; - -#if BASE_VER < 931007 - timeout_ = ::base::TimeDelta::FromMilliseconds(value); -#else - timeout_ = ::base::Milliseconds(value); -#endif - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/advertise_settings.h b/system/service/common/android/bluetooth/advertise_settings.h deleted file mode 100644 index 9ee71b2a21..0000000000 --- a/system/service/common/android/bluetooth/advertise_settings.h +++ /dev/null @@ -1,56 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include "bluetooth/advertise_settings.h" - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class AdvertiseSettings : public Parcelable, - public ::bluetooth::AdvertiseSettings { - public: - // NOLINT, implicit converter - AdvertiseSettings( - const ::bluetooth::AdvertiseSettings& advertise_settings) // NOLINT - : ::bluetooth::AdvertiseSettings(advertise_settings){}; - AdvertiseSettings() = default; - ~AdvertiseSettings() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; -}; -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_a2dp_codec_config.cc b/system/service/common/android/bluetooth/bluetooth_a2dp_codec_config.cc deleted file mode 100644 index 8e7b709cf9..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_a2dp_codec_config.cc +++ /dev/null @@ -1,103 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/bluetooth_a2dp_codec_config.h" - -#include <utils/String16.h> -#include <utils/String8.h> - -using android::OK; -using android::String16; -using android::String8; - -namespace android { -namespace bluetooth { - -status_t BluetoothA2dpCodecConfig::writeToParcel(Parcel* parcel) const { - status_t status = parcel->writeInt32(codec_type_); - if (status != OK) return status; - - status = parcel->writeInt32(codec_priority_); - if (status != OK) return status; - - status = parcel->writeInt32(sample_rate_); - if (status != OK) return status; - - status = parcel->writeInt32(bits_per_sample_); - if (status != OK) return status; - - status = parcel->writeInt32(channel_mode_); - if (status != OK) return status; - - status = parcel->writeInt64(codec_specific_1_); - if (status != OK) return status; - - status = parcel->writeInt64(codec_specific_2_); - if (status != OK) return status; - - status = parcel->writeInt64(codec_specific_3_); - if (status != OK) return status; - - status = parcel->writeInt64(codec_specific_4_); - if (status != OK) return status; - - return status; -} - -status_t BluetoothA2dpCodecConfig::readFromParcel(const Parcel* parcel) { - int32_t tmp; - status_t status = parcel->readInt32(&tmp); - if (status != OK) return status; - codec_type_ = tmp; - - status = parcel->readInt32(&tmp); - if (status != OK) return status; - codec_priority_ = tmp; - - status = parcel->readInt32(&tmp); - if (status != OK) return status; - sample_rate_ = tmp; - - status = parcel->readInt32(&tmp); - if (status != OK) return status; - bits_per_sample_ = tmp; - - status = parcel->readInt32(&tmp); - if (status != OK) return status; - channel_mode_ = tmp; - - int64_t tmp64; - status = parcel->readInt64(&tmp64); - if (status != OK) return status; - codec_specific_1_ = tmp64; - - status = parcel->readInt64(&tmp64); - if (status != OK) return status; - codec_specific_2_ = tmp64; - - status = parcel->readInt64(&tmp64); - if (status != OK) return status; - codec_specific_3_ = tmp64; - - status = parcel->readInt64(&tmp64); - if (status != OK) return status; - codec_specific_4_ = tmp64; - - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_a2dp_codec_config.h b/system/service/common/android/bluetooth/bluetooth_a2dp_codec_config.h deleted file mode 100644 index 0071d670e7..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_a2dp_codec_config.h +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -#include "bluetooth/a2dp_codec_config.h" - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class BluetoothA2dpCodecConfig : public Parcelable, - public ::bluetooth::A2dpCodecConfig { - public: - BluetoothA2dpCodecConfig() = default; - BluetoothA2dpCodecConfig(const ::bluetooth::A2dpCodecConfig& other) - : ::bluetooth::A2dpCodecConfig(other) {} // NOLINT(implicit) - BluetoothA2dpCodecConfig(const BluetoothA2dpCodecConfig& other) - : ::bluetooth::A2dpCodecConfig(other) {} // NOLINT(implicit) - ~BluetoothA2dpCodecConfig() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; -}; - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_avrcp_int_value.cc b/system/service/common/android/bluetooth/bluetooth_avrcp_int_value.cc deleted file mode 100644 index c2a895c916..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_avrcp_int_value.cc +++ /dev/null @@ -1,53 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/bluetooth_avrcp_int_value.h" - -#include <utils/String16.h> -#include <utils/String8.h> - -using android::OK; -using android::String16; -using android::String8; - -namespace android { -namespace bluetooth { - -status_t BluetoothAvrcpIntValue::writeToParcel(Parcel* parcel) const { - status_t status = parcel->writeInt32(id_); - if (status != OK) return status; - - status = parcel->writeInt32(value_); - if (status != OK) return status; - - return status; -} - -status_t BluetoothAvrcpIntValue::readFromParcel(const Parcel* parcel) { - int32_t tmp; - status_t status = parcel->readInt32(&tmp); - if (status != OK) return status; - id_ = tmp; - - status = parcel->readInt32(&tmp); - if (status != OK) return status; - value_ = tmp; - - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_avrcp_int_value.h b/system/service/common/android/bluetooth/bluetooth_avrcp_int_value.h deleted file mode 100644 index 80eed7cdff..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_avrcp_int_value.h +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -#include "bluetooth/avrcp_int_value.h" - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class BluetoothAvrcpIntValue : public Parcelable, - public ::bluetooth::AvrcpIntValue { - public: - BluetoothAvrcpIntValue() = default; - BluetoothAvrcpIntValue(const ::bluetooth::AvrcpIntValue& other) - : ::bluetooth::AvrcpIntValue(other) {} // NOLINT(implicit) - BluetoothAvrcpIntValue(const BluetoothAvrcpIntValue& other) - : ::bluetooth::AvrcpIntValue(other) {} // NOLINT(implicit) - ~BluetoothAvrcpIntValue() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; -}; - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_avrcp_media_attr.cc b/system/service/common/android/bluetooth/bluetooth_avrcp_media_attr.cc deleted file mode 100644 index b29204eabc..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_avrcp_media_attr.cc +++ /dev/null @@ -1,93 +0,0 @@ -// -// Copyright 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/bluetooth_avrcp_media_attr.h" - -#include <utils/String16.h> -#include <utils/String8.h> - -using android::OK; -using android::String16; -using android::String8; - -namespace android { -namespace bluetooth { - -status_t BluetoothAvrcpMediaAttr::writeToParcel(Parcel* parcel) const { - status_t status = - parcel->writeString16(String16(title_.c_str(), title_.size())); - if (status != OK) return status; - - status = parcel->writeString16(String16(artist_.c_str(), artist_.size())); - if (status != OK) return status; - - status = parcel->writeString16(String16(album_.c_str(), album_.size())); - if (status != OK) return status; - - status = parcel->writeString16(String16(genre_.c_str(), genre_.size())); - if (status != OK) return status; - - status = parcel->writeInt32(track_num_); - if (status != OK) return status; - - status = parcel->writeInt32(num_tracks_); - if (status != OK) return status; - - status = parcel->writeInt32(play_time_); - if (status != OK) return status; - - return status; -} - -status_t BluetoothAvrcpMediaAttr::readFromParcel(const Parcel* parcel) { - String16 title; - status_t status = parcel->readString16(&title); - if (status != OK) return status; - title_ = String8(title).string(); - - String16 artist; - status = parcel->readString16(&artist); - if (status != OK) return status; - artist_ = String8(artist).string(); - - String16 album; - status = parcel->readString16(&album); - if (status != OK) return status; - album_ = String8(album).string(); - - String16 genre; - status = parcel->readString16(&genre); - if (status != OK) return status; - genre_ = String8(genre).string(); - - int32_t tmp; - status = parcel->readInt32(&tmp); - if (status != OK) return status; - track_num_ = tmp; - - status = parcel->readInt32(&tmp); - if (status != OK) return status; - num_tracks_ = tmp; - - status = parcel->readInt32(&tmp); - if (status != OK) return status; - play_time_ = tmp; - - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_avrcp_media_attr.h b/system/service/common/android/bluetooth/bluetooth_avrcp_media_attr.h deleted file mode 100644 index d41fef64ae..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_avrcp_media_attr.h +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -#include "bluetooth/avrcp_media_attr.h" - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class BluetoothAvrcpMediaAttr : public Parcelable, - public ::bluetooth::AvrcpMediaAttr { - public: - BluetoothAvrcpMediaAttr() = default; - BluetoothAvrcpMediaAttr(const ::bluetooth::AvrcpMediaAttr& other) - : ::bluetooth::AvrcpMediaAttr(other) {} // NOLINT(implicit) - BluetoothAvrcpMediaAttr(const BluetoothAvrcpMediaAttr& other) - : ::bluetooth::AvrcpMediaAttr(other) {} // NOLINT(implicit) - ~BluetoothAvrcpMediaAttr() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; -}; - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_avrcp_register_notification_response.cc b/system/service/common/android/bluetooth/bluetooth_avrcp_register_notification_response.cc deleted file mode 100644 index 2ff5a173d4..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_avrcp_register_notification_response.cc +++ /dev/null @@ -1,46 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/bluetooth_avrcp_register_notification_response.h" - -#include <utils/String16.h> -#include <utils/String8.h> - -using android::OK; -using android::String16; -using android::String8; - -namespace android { -namespace bluetooth { - -status_t BluetoothAvrcpRegisterNotificationResponse::writeToParcel( - Parcel* parcel) const { - status_t status = parcel->write(&data_, sizeof(data_)); - if (status != OK) return status; - - return status; -} - -status_t BluetoothAvrcpRegisterNotificationResponse::readFromParcel( - const Parcel* parcel) { - status_t status = parcel->read(&data_, sizeof(data_)); - if (status != OK) return status; - - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_avrcp_register_notification_response.h b/system/service/common/android/bluetooth/bluetooth_avrcp_register_notification_response.h deleted file mode 100644 index 0a34d1e224..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_avrcp_register_notification_response.h +++ /dev/null @@ -1,60 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -#include "bluetooth/avrcp_register_notification_response.h" - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class BluetoothAvrcpRegisterNotificationResponse - : public Parcelable, - public ::bluetooth::AvrcpRegisterNotificationResponse { - public: - BluetoothAvrcpRegisterNotificationResponse() = default; - BluetoothAvrcpRegisterNotificationResponse( - const AvrcpRegisterNotificationResponse& other) - : ::bluetooth::AvrcpRegisterNotificationResponse(other) {} - BluetoothAvrcpRegisterNotificationResponse( - const BluetoothAvrcpRegisterNotificationResponse& other) - : ::bluetooth::AvrcpRegisterNotificationResponse(other) {} - ~BluetoothAvrcpRegisterNotificationResponse() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; -}; - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_avrcp_string_value.cc b/system/service/common/android/bluetooth/bluetooth_avrcp_string_value.cc deleted file mode 100644 index ded9105192..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_avrcp_string_value.cc +++ /dev/null @@ -1,54 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/bluetooth_avrcp_string_value.h" - -#include <utils/String16.h> -#include <utils/String8.h> - -using android::OK; -using android::String16; -using android::String8; - -namespace android { -namespace bluetooth { - -status_t BluetoothAvrcpStringValue::writeToParcel(Parcel* parcel) const { - status_t status = parcel->writeInt32(id_); - if (status != OK) return status; - - status = parcel->writeString16(String16(value_.c_str(), value_.size())); - if (status != OK) return status; - - return status; -} - -status_t BluetoothAvrcpStringValue::readFromParcel(const Parcel* parcel) { - int32_t tmp; - status_t status = parcel->readInt32(&tmp); - if (status != OK) return status; - id_ = tmp; - - String16 value; - status = parcel->readString16(&value); - if (status != OK) return status; - value_ = String8(value).string(); - - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_avrcp_string_value.h b/system/service/common/android/bluetooth/bluetooth_avrcp_string_value.h deleted file mode 100644 index 8f7e952eea..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_avrcp_string_value.h +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -#include "bluetooth/avrcp_string_value.h" - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class BluetoothAvrcpStringValue : public Parcelable, - public ::bluetooth::AvrcpStringValue { - public: - BluetoothAvrcpStringValue() = default; - BluetoothAvrcpStringValue(const ::bluetooth::AvrcpStringValue& other) - : ::bluetooth::AvrcpStringValue(other) {} // NOLINT(implicit) - BluetoothAvrcpStringValue(const BluetoothAvrcpStringValue& other) - : ::bluetooth::AvrcpStringValue(other) {} // NOLINT(implicit) - ~BluetoothAvrcpStringValue() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; -}; - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_gatt_characteristic.cc b/system/service/common/android/bluetooth/bluetooth_gatt_characteristic.cc deleted file mode 100644 index 9dbc0769f7..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_gatt_characteristic.cc +++ /dev/null @@ -1,84 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/bluetooth_gatt_characteristic.h" -#include "android/bluetooth/bluetooth_gatt_descriptor.h" -#include "android/bluetooth/uuid.h" - -#include <utils/String16.h> -#include <utils/String8.h> - -using android::OK; -using android::String8; -using android::String16; - -namespace android { -namespace bluetooth { - -status_t BluetoothGattCharacteristic::writeToParcel(Parcel* parcel) const { - status_t status = parcel->writeInt32(handle_); - if (status != OK) return status; - - status = parcel->writeParcelable((UUID)uuid_); - if (status != OK) return status; - - status = parcel->writeInt32(properties_); - if (status != OK) return status; - - status = parcel->writeInt32(permissions_); - if (status != OK) return status; - - std::vector<BluetoothGattDescriptor> descriptors; - for (const auto& desc : descriptors_) { - descriptors.push_back(desc); - } - - status = parcel->writeParcelableVector(descriptors); - return status; -} - -status_t BluetoothGattCharacteristic::readFromParcel(const Parcel* parcel) { - int32_t tmp; - status_t status = parcel->readInt32(&tmp); - if (status != OK) return status; - handle_ = tmp; - - UUID uuid; - status = parcel->readParcelable(&uuid); - if (status != OK) return status; - uuid_ = uuid.uuid; - - status = parcel->readInt32(&tmp); - if (status != OK) return status; - properties_ = tmp; - - status = parcel->readInt32(&tmp); - if (status != OK) return status; - permissions_ = tmp; - - std::vector<BluetoothGattDescriptor> descriptors; - status = parcel->readParcelableVector(&descriptors); - if (status != OK) return status; - - for (const auto& desc : descriptors) { - descriptors_.push_back(desc); - } - - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_gatt_characteristic.h b/system/service/common/android/bluetooth/bluetooth_gatt_characteristic.h deleted file mode 100644 index 954fe95dae..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_gatt_characteristic.h +++ /dev/null @@ -1,55 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include "bluetooth/characteristic.h" - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class BluetoothGattCharacteristic : public Parcelable, - public ::bluetooth::Characteristic { - public: - BluetoothGattCharacteristic() = default; - BluetoothGattCharacteristic( - const ::bluetooth::Characteristic& characteristic) // NOLINT(implicit) - : ::bluetooth::Characteristic(characteristic){}; - ~BluetoothGattCharacteristic() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; -}; -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_gatt_descriptor.cc b/system/service/common/android/bluetooth/bluetooth_gatt_descriptor.cc deleted file mode 100644 index e3ec03dfdb..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_gatt_descriptor.cc +++ /dev/null @@ -1,60 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/bluetooth_gatt_descriptor.h" -#include "android/bluetooth/uuid.h" - -#include <utils/String16.h> -#include <utils/String8.h> - -using android::OK; -using android::String8; -using android::String16; - -namespace android { -namespace bluetooth { - -status_t BluetoothGattDescriptor::writeToParcel(Parcel* parcel) const { - status_t status = parcel->writeParcelable((UUID)uuid_); - if (status != OK) return status; - - status = parcel->writeInt32(handle_); - if (status != OK) return status; - - status = parcel->writeInt32(permissions_); - return status; -} - -status_t BluetoothGattDescriptor::readFromParcel(const Parcel* parcel) { - UUID uuid; - status_t status = parcel->readParcelable(&uuid); - if (status != OK) return status; - uuid_ = uuid.uuid; - - int32_t tmp; - status = parcel->readInt32(&tmp); - if (status != OK) return status; - handle_ = tmp; - - status = parcel->readInt32(&tmp); - if (status != OK) return status; - permissions_ = tmp; - - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_gatt_descriptor.h b/system/service/common/android/bluetooth/bluetooth_gatt_descriptor.h deleted file mode 100644 index 4321f9d1a5..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_gatt_descriptor.h +++ /dev/null @@ -1,55 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include "bluetooth/descriptor.h" - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class BluetoothGattDescriptor : public Parcelable, - public ::bluetooth::Descriptor { - public: - BluetoothGattDescriptor() = default; - BluetoothGattDescriptor( - const ::bluetooth::Descriptor& characteristic) // NOLINT(implicit) - : ::bluetooth::Descriptor(characteristic){}; - ~BluetoothGattDescriptor() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; -}; -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_gatt_included_service.cc b/system/service/common/android/bluetooth/bluetooth_gatt_included_service.cc deleted file mode 100644 index 21cf19a2b9..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_gatt_included_service.cc +++ /dev/null @@ -1,58 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/bluetooth_gatt_characteristic.h" -#include "android/bluetooth/bluetooth_gatt_service.h" -#include "android/bluetooth/uuid.h" - -#include <utils/String16.h> -#include <utils/String8.h> - -using android::OK; -using android::String8; -using android::String16; - -namespace android { -namespace bluetooth { - -status_t BluetoothGattIncludedService::writeToParcel(Parcel* parcel) const { - status_t status = parcel->writeParcelable((UUID)uuid_); - if (status != OK) return status; - - status = parcel->writeInt32(handle_); - if (status != OK) return status; - - status = parcel->writeBool(primary_); - return status; -} - -status_t BluetoothGattIncludedService::readFromParcel(const Parcel* parcel) { - UUID uuid; - status_t status = parcel->readParcelable(&uuid); - if (status != OK) return status; - uuid_ = uuid.uuid; - - int32_t tmp; - status = parcel->readInt32(&tmp); - if (status != OK) return status; - handle_ = tmp; - - status = parcel->readBool(&primary_); - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_gatt_included_service.h b/system/service/common/android/bluetooth/bluetooth_gatt_included_service.h deleted file mode 100644 index b01153294e..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_gatt_included_service.h +++ /dev/null @@ -1,67 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include "bluetooth/service.h" - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -using ::bluetooth::Uuid; - -namespace android { -namespace bluetooth { - -class BluetoothGattIncludedService : public Parcelable { - public: - BluetoothGattIncludedService() = default; - BluetoothGattIncludedService( - const ::bluetooth::Service& service) // NOLINT(implicit) - : handle_(service.handle()), - uuid_(service.uuid()), - primary_(service.primary()){}; - ~BluetoothGattIncludedService() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; - - uint16_t handle() const { return handle_; } - bool primary() const { return primary_; } - Uuid uuid() const { return uuid_; } - - protected: - uint16_t handle_; - Uuid uuid_; - bool primary_; -}; -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_gatt_service.cc b/system/service/common/android/bluetooth/bluetooth_gatt_service.cc deleted file mode 100644 index 820ef43844..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_gatt_service.cc +++ /dev/null @@ -1,86 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/bluetooth_gatt_service.h" -#include "android/bluetooth/bluetooth_gatt_characteristic.h" -#include "android/bluetooth/uuid.h" - -#include <utils/String16.h> -#include <utils/String8.h> - -using android::OK; -using android::String8; -using android::String16; - -namespace android { -namespace bluetooth { - -status_t BluetoothGattService::writeToParcel(Parcel* parcel) const { - status_t status = parcel->writeInt32(handle_); - if (status != OK) return status; - - status = parcel->writeBool(primary_); - if (status != OK) return status; - - status = parcel->writeParcelable((UUID)uuid_); - if (status != OK) return status; - - std::vector<BluetoothGattCharacteristic> characteristics; - for (const auto& chrc : characteristics_) characteristics.push_back(chrc); - - status = parcel->writeParcelableVector(characteristics); - - std::vector<BluetoothGattIncludedService> includedServices; - for (const auto& service : included_services_) - includedServices.push_back(service); - - status = parcel->writeParcelableVector(includedServices); - - return status; -} - -status_t BluetoothGattService::readFromParcel(const Parcel* parcel) { - int32_t tmp; - status_t status = parcel->readInt32(&tmp); - if (status != OK) return status; - handle_ = tmp; - - status = parcel->readBool(&primary_); - if (status != OK) return status; - - UUID uuid; - status = parcel->readParcelable(&uuid); - if (status != OK) return status; - uuid_ = uuid.uuid; - - std::vector<BluetoothGattCharacteristic> characteristics; - status = parcel->readParcelableVector(&characteristics); - if (status != OK) return status; - - for (const auto& chrc : characteristics) characteristics_.push_back(chrc); - - std::vector<BluetoothGattIncludedService> includedServices; - status = parcel->readParcelableVector(&includedServices); - if (status != OK) return status; - - for (const auto& srvc : includedServices) - included_services_.push_back(BluetoothGattService(srvc)); - - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_gatt_service.h b/system/service/common/android/bluetooth/bluetooth_gatt_service.h deleted file mode 100644 index a17b6da0a1..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_gatt_service.h +++ /dev/null @@ -1,59 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include "android/bluetooth/bluetooth_gatt_included_service.h" -#include "bluetooth/service.h" - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class BluetoothGattService : public Parcelable, public ::bluetooth::Service { - public: - BluetoothGattService() = default; - BluetoothGattService(const ::bluetooth::Service& service) - : ::bluetooth::Service(service){}; // NOLINT(implicit) - BluetoothGattService( - const BluetoothGattIncludedService& includedService) // NOLINT(implicit) - : ::bluetooth::Service(includedService.handle(), - includedService.primary(), includedService.uuid(), - {}, {}){}; - ~BluetoothGattService() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; -}; -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_remote_device_props.cc b/system/service/common/android/bluetooth/bluetooth_remote_device_props.cc deleted file mode 100644 index 21974da9a7..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_remote_device_props.cc +++ /dev/null @@ -1,91 +0,0 @@ -// -// Copyright 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/bluetooth_remote_device_props.h" - -#include <utils/String16.h> -#include <utils/String8.h> - -#include "android/bluetooth/uuid.h" - -using android::OK; -using android::String16; -using android::String8; - -namespace android { -namespace bluetooth { - -status_t BluetoothRemoteDeviceProps::writeToParcel(Parcel* parcel) const { - status_t status = - parcel->writeString16(String16(name_.c_str(), name_.size())); - if (status != OK) return status; - - status = parcel->writeString16(String16(address_.c_str(), address_.size())); - if (status != OK) return status; - - std::vector<UUID> uuids; - for (const auto& uuid : service_uuids_) { - uuids.push_back(uuid); - } - - status = parcel->writeParcelableVector(uuids); - if (status != OK) return status; - - status = parcel->writeInt32(device_class_); - if (status != OK) return status; - - status = parcel->writeInt32(device_type_); - if (status != OK) return status; - - status = parcel->writeInt32(rssi_); - if (status != OK) return status; - - return status; -} - -status_t BluetoothRemoteDeviceProps::readFromParcel(const Parcel* parcel) { - String16 name; - status_t status = parcel->readString16(&name); - if (status != OK) return status; - name_ = String8(name).string(); - - String16 address; - status = parcel->readString16(&address); - if (status != OK) return status; - address_ = String8(address).string(); - - std::vector<UUID> uuids; - status = parcel->readParcelableVector(&uuids); - if (status != OK) return status; - - for (const auto& uuid : uuids) { - service_uuids_.push_back(uuid.uuid); - } - - status = parcel->readInt32(&device_class_); - if (status != OK) return status; - - status = parcel->readInt32(&device_type_); - if (status != OK) return status; - - status = parcel->readInt32(&rssi_); - if (status != OK) return status; - - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/bluetooth_remote_device_props.h b/system/service/common/android/bluetooth/bluetooth_remote_device_props.h deleted file mode 100644 index e2ad3462dd..0000000000 --- a/system/service/common/android/bluetooth/bluetooth_remote_device_props.h +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -#include "bluetooth/remote_device_props.h" - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class BluetoothRemoteDeviceProps : public Parcelable, - public ::bluetooth::RemoteDeviceProps { - public: - BluetoothRemoteDeviceProps() = default; - BluetoothRemoteDeviceProps(const ::bluetooth::RemoteDeviceProps& other) - : ::bluetooth::RemoteDeviceProps(other) {} // NOLINT(implicit) - BluetoothRemoteDeviceProps(const BluetoothRemoteDeviceProps& other) - : ::bluetooth::RemoteDeviceProps(other) {} // NOLINT(implicit) - ~BluetoothRemoteDeviceProps() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; -}; - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/scan_filter.cc b/system/service/common/android/bluetooth/scan_filter.cc deleted file mode 100644 index ad8bea64b1..0000000000 --- a/system/service/common/android/bluetooth/scan_filter.cc +++ /dev/null @@ -1,84 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/scan_filter.h" -#include "android/bluetooth/uuid.h" - -#include <binder/Parcel.h> -#include <utils/String16.h> -#include <utils/String8.h> - -using android::Parcelable; -using android::Parcel; -using android::String8; -using android::String16; -using android::status_t; -using android::OK; - -namespace android { -namespace bluetooth { - -status_t ScanFilter::writeToParcel(Parcel* parcel) const { - status_t status = - parcel->writeString16(String16(String8(device_name_.c_str()))); - if (status != OK) return status; - - status = parcel->writeString16(String16(String8(device_address_.c_str()))); - if (status != OK) return status; - - // TODO(jpawlowski) make type casting nicer - // uuid won't really keep ownership, it's just for type casting - std::optional<UUID> uuid; - - if (service_uuid_) { - uuid = *service_uuid_; - } - status = parcel->writeNullableParcelable(uuid); - if (status != OK) return status; - - uuid.reset(); - if (service_uuid_mask_) { - uuid = *service_uuid_mask_; - } - status = parcel->writeNullableParcelable(uuid); - return status; -} - -status_t ScanFilter::readFromParcel(const Parcel* parcel) { - String16 name; - status_t status = parcel->readString16(&name); - if (status != OK) return status; - device_name_ = std::string(String8(name).string()); - - String16 addr; - status = parcel->readString16(&addr); - if (status != OK) return status; - device_address_ = std::string(String8(addr).string()); - - UUID uuid; - status = parcel->readParcelable(&uuid); - if (status != OK) return status; - service_uuid_.reset(new ::bluetooth::Uuid(uuid.uuid)); - - status = parcel->readParcelable(&uuid); - if (status != OK) return status; - service_uuid_mask_.reset(new ::bluetooth::Uuid(uuid.uuid)); - - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/scan_filter.h b/system/service/common/android/bluetooth/scan_filter.h deleted file mode 100644 index ebf34a4ffa..0000000000 --- a/system/service/common/android/bluetooth/scan_filter.h +++ /dev/null @@ -1,54 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include "bluetooth/scan_filter.h" - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class ScanFilter : public Parcelable, public ::bluetooth::ScanFilter { - public: - ScanFilter() = default; - // NOLINT, implicit converter - ScanFilter(const ::bluetooth::ScanFilter& scan_filter) // NOLINT - : ::bluetooth::ScanFilter(scan_filter){}; - ~ScanFilter() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; -}; -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/scan_result.cc b/system/service/common/android/bluetooth/scan_result.cc deleted file mode 100644 index 5693ead663..0000000000 --- a/system/service/common/android/bluetooth/scan_result.cc +++ /dev/null @@ -1,60 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/scan_result.h" - -#include <base/logging.h> -#include <binder/Parcel.h> -#include <utils/String16.h> -#include <utils/String8.h> - -using android::Parcelable; -using android::Parcel; -using android::String8; -using android::String16; -using android::status_t; -using android::OK; - -namespace android { -namespace bluetooth { - -status_t ScanResult::writeToParcel(Parcel* parcel) const { - status_t status = - parcel->writeString16(String16(String8(device_address_.c_str()))); - if (status != OK) return status; - - status = parcel->writeByteVector(scan_record_); - if (status != OK) return status; - - status = parcel->writeInt32(rssi_); - return status; -} - -status_t ScanResult::readFromParcel(const Parcel* parcel) { - String16 addr; - status_t status = parcel->readString16(&addr); - if (status != OK) return status; - device_address_ = std::string(String8(addr).string()); - - status = parcel->readByteVector(&scan_record_); - if (status != OK) return status; - - status = parcel->readInt32(&rssi_); - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/scan_result.h b/system/service/common/android/bluetooth/scan_result.h deleted file mode 100644 index 1a58b3e15e..0000000000 --- a/system/service/common/android/bluetooth/scan_result.h +++ /dev/null @@ -1,54 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include "bluetooth/scan_result.h" - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class ScanResult : public Parcelable, public ::bluetooth::ScanResult { - public: - ScanResult() = default; - // NOLINT, implicit converter - ScanResult(const ::bluetooth::ScanResult& scan_result) // NOLINT - : ::bluetooth::ScanResult(scan_result){}; - ~ScanResult() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; -}; -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/scan_settings.cc b/system/service/common/android/bluetooth/scan_settings.cc deleted file mode 100644 index 7aca56521f..0000000000 --- a/system/service/common/android/bluetooth/scan_settings.cc +++ /dev/null @@ -1,84 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/scan_settings.h" - -#include <binder/Parcel.h> - -using android::Parcelable; -using android::Parcel; -using android::String16; -using android::status_t; -using android::OK; - -namespace android { -namespace bluetooth { - -status_t ScanSettings::writeToParcel(Parcel* parcel) const { - status_t status = parcel->writeInt32(mode_); - if (status != OK) return status; - - status = parcel->writeInt32(callback_type_); - if (status != OK) return status; - - status = parcel->writeInt32(result_type_); - if (status != OK) return status; - - status = parcel->writeInt64(report_delay_ms_.InMilliseconds()); - if (status != OK) return status; - - status = parcel->writeInt32(match_mode_); - if (status != OK) return status; - - status = parcel->writeInt32(match_count_per_filter_); - return status; -} - -status_t ScanSettings::readFromParcel(const Parcel* parcel) { - int value; - status_t status = parcel->readInt32(&value); - if (status != OK) return status; - mode_ = static_cast<ScanSettings::Mode>(value); - - status = parcel->readInt32(&value); - if (status != OK) return status; - callback_type_ = static_cast<ScanSettings::CallbackType>(value); - - status = parcel->readInt32(&value); - if (status != OK) return status; - result_type_ = static_cast<ScanSettings::ResultType>(value); - - int64_t value64; - status = parcel->readInt64(&value64); -#if BASE_VER < 931007 - report_delay_ms_ = ::base::TimeDelta::FromMilliseconds(value64); -#else - report_delay_ms_ = ::base::Milliseconds(value64); -#endif - - status = parcel->readInt32(&value); - if (status != OK) return status; - match_mode_ = static_cast<ScanSettings::MatchMode>(value); - - status = parcel->readInt32(&value); - if (status != OK) return status; - match_count_per_filter_ = static_cast<ScanSettings::MatchCount>(value); - - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/scan_settings.h b/system/service/common/android/bluetooth/scan_settings.h deleted file mode 100644 index 53af9ee9d6..0000000000 --- a/system/service/common/android/bluetooth/scan_settings.h +++ /dev/null @@ -1,54 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include "bluetooth/scan_settings.h" - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class ScanSettings : public Parcelable, public ::bluetooth::ScanSettings { - public: - ScanSettings() = default; - // NOLINT, implicit converter - ScanSettings(const ::bluetooth::ScanSettings& scan_settings) // NOLINT - : ::bluetooth::ScanSettings(scan_settings){}; - ~ScanSettings() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; -}; -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/uuid.cc b/system/service/common/android/bluetooth/uuid.cc deleted file mode 100644 index 077dd2b7f5..0000000000 --- a/system/service/common/android/bluetooth/uuid.cc +++ /dev/null @@ -1,90 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "android/bluetooth/uuid.h" - -#include <binder/Parcel.h> - -using android::Parcelable; -using android::Parcel; -using android::String16; -using android::status_t; -using android::OK; - -namespace android { -namespace bluetooth { - -status_t UUID::writeToParcel(Parcel* parcel) const { - // The scheme used by android.os.ParcelUuid is to wrote the most significant - // bits first as one 64-bit integer, followed by the least significant bits in - // a second 64-bit integer. This is the same as writing the raw-bytes in - // sequence, but we don't want to assume any host-endianness here. So follow - // the same scheme and use the same Parcel APIs. - ::bluetooth::Uuid::UUID128Bit bytes = uuid.To128BitBE(); - - uint64_t most_sig_bits = - ((((uint64_t)bytes[0]) << 56) | (((uint64_t)bytes[1]) << 48) | - (((uint64_t)bytes[2]) << 40) | (((uint64_t)bytes[3]) << 32) | - (((uint64_t)bytes[4]) << 24) | (((uint64_t)bytes[5]) << 16) | - (((uint64_t)bytes[6]) << 8) | bytes[7]); - - uint64_t least_sig_bits = - ((((uint64_t)bytes[8]) << 56) | (((uint64_t)bytes[9]) << 48) | - (((uint64_t)bytes[10]) << 40) | (((uint64_t)bytes[11]) << 32) | - (((uint64_t)bytes[12]) << 24) | (((uint64_t)bytes[13]) << 16) | - (((uint64_t)bytes[14]) << 8) | bytes[15]); - - status_t status = parcel->writeUint64(most_sig_bits); - if (status != OK) return status; - - status = parcel->writeUint64(least_sig_bits); - return status; -} - -status_t UUID::readFromParcel(const Parcel* parcel) { - ::bluetooth::Uuid::UUID128Bit bytes; - - uint64_t most_sig_bits, least_sig_bits; - status_t status = parcel->readUint64(&most_sig_bits); - if (status != OK) return status; - - status = parcel->readUint64(&least_sig_bits); - if (status != OK) return status; - - bytes[0] = (most_sig_bits >> 56) & 0xFF; - bytes[1] = (most_sig_bits >> 48) & 0xFF; - bytes[2] = (most_sig_bits >> 40) & 0xFF; - bytes[3] = (most_sig_bits >> 32) & 0xFF; - bytes[4] = (most_sig_bits >> 24) & 0xFF; - bytes[5] = (most_sig_bits >> 16) & 0xFF; - bytes[6] = (most_sig_bits >> 8) & 0xFF; - bytes[7] = most_sig_bits & 0xFF; - - bytes[8] = (least_sig_bits >> 56) & 0xFF; - bytes[9] = (least_sig_bits >> 48) & 0xFF; - bytes[10] = (least_sig_bits >> 40) & 0xFF; - bytes[11] = (least_sig_bits >> 32) & 0xFF; - bytes[12] = (least_sig_bits >> 24) & 0xFF; - bytes[13] = (least_sig_bits >> 16) & 0xFF; - bytes[14] = (least_sig_bits >> 8) & 0xFF; - bytes[15] = least_sig_bits & 0xFF; - - uuid = ::bluetooth::Uuid::From128BitBE(bytes); - return status; -} - -} // namespace bluetooth -} // namespace android diff --git a/system/service/common/android/bluetooth/uuid.h b/system/service/common/android/bluetooth/uuid.h deleted file mode 100644 index 1e84d19276..0000000000 --- a/system/service/common/android/bluetooth/uuid.h +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include "bluetooth/uuid.h" - -#include <binder/Parcel.h> -#include <binder/Parcelable.h> - -using android::Parcel; -using android::Parcelable; -using android::status_t; - -namespace android { -namespace bluetooth { - -class UUID : public Parcelable { - public: - UUID() = default; - // NOLINT, implicit converter - UUID(const ::bluetooth::Uuid& uuid) : uuid(uuid){}; // NOLINT - ~UUID() = default; - - // Write |this| parcelable to the given |parcel|. Keep in mind that - // implementations of writeToParcel must be manually kept in sync - // with readFromParcel and the Java equivalent versions of these methods. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t writeToParcel(Parcel* parcel) const override; - - // Read data from the given |parcel| into |this|. After readFromParcel - // completes, |this| should have equivalent state to the object that - // wrote itself to the parcel. - // - // Returns android::OK on success and an appropriate error otherwise. - status_t readFromParcel(const Parcel* parcel) override; - - bool operator==(::bluetooth::Uuid rhs) const { return uuid == rhs; } - - ::bluetooth::Uuid uuid; -}; -} // namespace bluetooth -} // namespace android - -inline bool operator==(const ::bluetooth::Uuid& lhs, - const android::bluetooth::UUID& rhs) { - return lhs == rhs.uuid; -} diff --git a/system/service/common/bluetooth/a2dp_codec_config.cc b/system/service/common/bluetooth/a2dp_codec_config.cc deleted file mode 100644 index 2b5e5ba666..0000000000 --- a/system/service/common/bluetooth/a2dp_codec_config.cc +++ /dev/null @@ -1,41 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "bluetooth/a2dp_codec_config.h" - -namespace bluetooth { - -A2dpCodecConfig::A2dpCodecConfig() = default; -A2dpCodecConfig::A2dpCodecConfig(const A2dpCodecConfig& other) = default; -A2dpCodecConfig::A2dpCodecConfig(int codec_type, int codec_priority, - int sample_rate, int bits_per_sample, - int channel_mode, int64_t codec_specific_1, - int64_t codec_specific_2, - int64_t codec_specific_3, - int64_t codec_specific_4) - : codec_type_(codec_type), - codec_priority_(codec_priority), - sample_rate_(sample_rate), - bits_per_sample_(bits_per_sample), - channel_mode_(channel_mode), - codec_specific_1_(codec_specific_1), - codec_specific_2_(codec_specific_2), - codec_specific_3_(codec_specific_3), - codec_specific_4_(codec_specific_4) {} - -A2dpCodecConfig::~A2dpCodecConfig() = default; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/a2dp_codec_config.h b/system/service/common/bluetooth/a2dp_codec_config.h deleted file mode 100644 index 10dbfcb655..0000000000 --- a/system/service/common/bluetooth/a2dp_codec_config.h +++ /dev/null @@ -1,56 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <cstdint> - -namespace bluetooth { - -// Should match btav_a2dp_codec_config_t in bt_av.h -class A2dpCodecConfig { - public: - A2dpCodecConfig(); - A2dpCodecConfig(const A2dpCodecConfig& other); - A2dpCodecConfig(int codec_type, int codec_priority, int sample_rate, - int bits_per_sample, int channel_mode, - int64_t codec_specific_1, int64_t codec_specific_2, - int64_t codec_specific_3, int64_t codec_specific_4); - ~A2dpCodecConfig(); - - int codec_type() const { return codec_type_; } - int codec_priority() const { return codec_priority_; } - int sample_rate() const { return sample_rate_; } - int bits_per_sample() const { return bits_per_sample_; } - int channel_mode() const { return channel_mode_; } - int64_t codec_specific_1() const { return codec_specific_1_; } - int64_t codec_specific_2() const { return codec_specific_2_; } - int64_t codec_specific_3() const { return codec_specific_3_; } - int64_t codec_specific_4() const { return codec_specific_4_; } - - protected: - int codec_type_ = 0; - int codec_priority_ = 0; - int sample_rate_ = 0; - int bits_per_sample_ = 0; - int channel_mode_ = 0; - int64_t codec_specific_1_ = 0; - int64_t codec_specific_2_ = 0; - int64_t codec_specific_3_ = 0; - int64_t codec_specific_4_ = 0; -}; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/adapter_state.cc b/system/service/common/bluetooth/adapter_state.cc deleted file mode 100644 index a8866d3bb5..0000000000 --- a/system/service/common/bluetooth/adapter_state.cc +++ /dev/null @@ -1,44 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "bluetooth/adapter_state.h" - -namespace bluetooth { - -std::string AdapterStateToString(AdapterState state) { - switch (state) { - case ADAPTER_STATE_DISCONNECTED: - return "ADAPTER_STATE_DISCONNECTED"; - case ADAPTER_STATE_CONNECTING: - return "ADAPTER_STATE_CONNECTING"; - case ADAPTER_STATE_CONNECTED: - return "ADAPTER_STATE_CONNECTED"; - case ADAPTER_STATE_DISCONNECTING: - return "ADAPTER_STATE_DISCONNECTING"; - case ADAPTER_STATE_OFF: - return "ADAPTER_STATE_OFF"; - case ADAPTER_STATE_TURNING_ON: - return "ADAPTER_STATE_TURNING_ON"; - case ADAPTER_STATE_ON: - return "ADAPTER_STATE_ON"; - case ADAPTER_STATE_TURNING_OFF: - return "ADAPTER_STATE_TURNING_OFF"; - default: - return "unknown state"; - } -} - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/adapter_state.h b/system/service/common/bluetooth/adapter_state.h deleted file mode 100644 index 42897ad06d..0000000000 --- a/system/service/common/bluetooth/adapter_state.h +++ /dev/null @@ -1,43 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <string> - -namespace bluetooth { - -// Possible Adapter states. The values for each enumration have been copied -// from frameworks/base/core/java/android/bluetooth/BluetoothAdapter.java. -// These values need to match their android.bluetooth.BluetoothAdapter -// counterparts for this to be compatible with the framework, hence we -// redeclare them here. -enum AdapterState { - ADAPTER_STATE_DISCONNECTED = 0, - ADAPTER_STATE_CONNECTING = 1, - ADAPTER_STATE_CONNECTED = 2, - ADAPTER_STATE_DISCONNECTING = 3, - ADAPTER_STATE_OFF = 10, - ADAPTER_STATE_TURNING_ON = 11, - ADAPTER_STATE_ON = 12, - ADAPTER_STATE_TURNING_OFF = 13, - ADAPTER_STATE_INVALID = 0xFFFF -}; - -// Returns a string for the given Adapter state |state|. -std::string AdapterStateToString(AdapterState state); - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/advertise_data.cc b/system/service/common/bluetooth/advertise_data.cc deleted file mode 100644 index 83b3c2f1ac..0000000000 --- a/system/service/common/bluetooth/advertise_data.cc +++ /dev/null @@ -1,83 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "bluetooth/advertise_data.h" - -#include <base/logging.h> - -#include "stack/include/bt_types.h" -#include "stack/include/hcidefs.h" - -namespace bluetooth { - -AdvertiseData::AdvertiseData(const std::vector<uint8_t>& data) : data_(data) {} - -AdvertiseData::AdvertiseData() {} - -AdvertiseData::AdvertiseData(const AdvertiseData& other) : data_(other.data_) {} - -bool AdvertiseData::IsValid() const { - size_t len = data_.size(); - - // Consider empty data as valid. - if (!len) return true; - - for (size_t i = 0, field_len = 0; i < len; i += (field_len + 1)) { - field_len = data_[i]; - - // If the length of the current field would exceed the total data length, - // then the data is badly formatted. - if (i + field_len >= len) { - VLOG(1) << "Advertising data badly formatted"; - return false; - } - - // A field length of 0 would be invalid as it should at least contain the - // EIR field type. - if (field_len < 1) return false; - - uint8_t type = data_[i + 1]; - - // Clients are not allowed to set the following EIR fields as these are - // managed by stack. - switch (type) { - case HCI_EIR_FLAGS_TYPE: - case HCI_EIR_OOB_BD_ADDR_TYPE: - case HCI_EIR_OOB_COD_TYPE: - case HCI_EIR_OOB_SSP_HASH_C_TYPE: - case HCI_EIR_OOB_SSP_RAND_R_TYPE: - VLOG(1) << "Cannot set EIR field type: " << type; - return false; - default: - break; - } - } - - return true; -} - -bool AdvertiseData::operator==(const AdvertiseData& rhs) const { - return data_ == rhs.data_; -} - -AdvertiseData& AdvertiseData::operator=(const AdvertiseData& other) { - if (this == &other) return *this; - - data_ = other.data_; - return *this; -} - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/advertise_data.h b/system/service/common/bluetooth/advertise_data.h deleted file mode 100644 index 796f7dcc15..0000000000 --- a/system/service/common/bluetooth/advertise_data.h +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <stdint.h> - -#include <vector> - -namespace bluetooth { - -// Represents a data packet for Bluetooth Low Energy advertisements. This is the -// native equivalent of the Android framework class defined in -// frameworks/base/core/j/android/bluetooth/le/AdvertiseData.java -class AdvertiseData { - public: - // Constructs an AdvertiseData with the given parameters. |data| can only - // contain the "Service Uuids", "Service Data", "Manufacturer Data", - // "Tx Power" and "Device name" fields as specified in the Core Specification - // Supplement. |data| must be properly formatted according to the supplement - // and contains the data as it will be sent over the wire. - // - // Tx Power field value will be filled with proper value. - explicit AdvertiseData(const std::vector<uint8_t>& data); - - // Default constructor initializes all fields to be empty/false. - AdvertiseData(); - AdvertiseData(const AdvertiseData& other); - virtual ~AdvertiseData() = default; - - // Returns true if the advertising data is formatted correctly according to - // the TLV format. - bool IsValid() const; - - // data() returns the current advertising data contained by this instance. The - // data is in the TLV format as specified in the Bluetooth Core Specification. - const std::vector<uint8_t>& data() const { return data_; } - - // Comparison operator. - bool operator==(const AdvertiseData& rhs) const; - - // Assignment operator - AdvertiseData& operator=(const AdvertiseData& other); - - protected: - std::vector<uint8_t> data_; -}; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/advertise_settings.cc b/system/service/common/bluetooth/advertise_settings.cc deleted file mode 100644 index 5ecc7b481f..0000000000 --- a/system/service/common/bluetooth/advertise_settings.cc +++ /dev/null @@ -1,47 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "bluetooth/advertise_settings.h" - -namespace bluetooth { - -AdvertiseSettings::AdvertiseSettings(Mode mode, base::TimeDelta timeout, - TxPowerLevel tx_power_level, - bool connectable) - : mode_(mode), - timeout_(timeout), - tx_power_level_(tx_power_level), - connectable_(connectable) {} - -// Default values are taken from the AdvertiseSettings.java -AdvertiseSettings::AdvertiseSettings() - : mode_(MODE_LOW_POWER), - tx_power_level_(TX_POWER_LEVEL_MEDIUM), - connectable_(true) {} - -bool AdvertiseSettings::operator==(const AdvertiseSettings& rhs) const { - if (mode_ != rhs.mode_) return false; - - if (timeout_ != rhs.timeout_) return false; - - if (tx_power_level_ != rhs.tx_power_level_) return false; - - if (connectable_ != rhs.connectable_) return false; - - return true; -} - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/advertise_settings.h b/system/service/common/bluetooth/advertise_settings.h deleted file mode 100644 index e4aee5377a..0000000000 --- a/system/service/common/bluetooth/advertise_settings.h +++ /dev/null @@ -1,95 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <base/time/time.h> - -namespace bluetooth { - -// AdvertiseSettings provides a way to adjust advertising preferences for each -// Bluetooth LE advertisement instance. This is the native equivalent of the -// Android framework class defined in -// frameworks/base/core/java/android/bluetooth/le/AdvertiseSettings.java -class AdvertiseSettings { - public: - // Advertising mode describes power consumption mode used for advertising. - enum Mode { - // Perform Bluetooth LE advertising in low power mode. This is the default - // and preferred advertising mode as it consumes the least power. - MODE_LOW_POWER = 0x00, - - // Perform Bluetooth LE advertising in balanced power mode. This is balanced - // between advertising frequency and power consumption. - MODE_BALANCED = 0x01, - - // Perform Bluetooth LE advertising in low latency, high power mode. This - // has the highest power consumption and should not be used for continuous - // background advertising. - MODE_LOW_LATENCY = 0x02, - }; - - // Levels that can be set for advertising transmission power. - enum TxPowerLevel { - // Advertise using the lowest transmission (TX) power level. Low - // transmission power can be used to restrict the visibility range of - // advertising packets. - TX_POWER_LEVEL_ULTRA_LOW = 0x00, - - // Advertise using low TX power level. - TX_POWER_LEVEL_LOW = 0x01, - - // Advertise using medium TX power level. - TX_POWER_LEVEL_MEDIUM = 0x02, - - // Advertise using high TX power level. This corresponds to largest - // visibility range of the advertising packet. - TX_POWER_LEVEL_HIGH = 0x03, - }; - - AdvertiseSettings(Mode mode, base::TimeDelta timeout, - TxPowerLevel tx_power_level, bool connectable); - - // The default constructor sets all fields to defaults: - // mode: MODE_LOW_POWER - // TX power level: TX_POWER_LEVEL_MEDIUM - // connectable: true - AdvertiseSettings(); - virtual ~AdvertiseSettings() = default; - - // Returns the advertise mode. - Mode mode() const { return mode_; } - - // Returns the advertising time limit in milliseconds. - const base::TimeDelta& timeout() const { return timeout_; } - - // Returns the TX power level for advertising. - TxPowerLevel tx_power_level() const { return tx_power_level_; } - - // Returns whether the advertisement will indicate connectable. - bool connectable() const { return connectable_; } - - // Comparison operator. - bool operator==(const AdvertiseSettings& rhs) const; - - protected: - Mode mode_; - base::TimeDelta timeout_; - TxPowerLevel tx_power_level_; - bool connectable_; -}; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/avrcp_int_value.cc b/system/service/common/bluetooth/avrcp_int_value.cc deleted file mode 100644 index 5ea07d4370..0000000000 --- a/system/service/common/bluetooth/avrcp_int_value.cc +++ /dev/null @@ -1,26 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "bluetooth/avrcp_int_value.h" - -namespace bluetooth { - -AvrcpIntValue::AvrcpIntValue() = default; -AvrcpIntValue::AvrcpIntValue(const AvrcpIntValue& other) = default; -AvrcpIntValue::AvrcpIntValue(int id, int value) : id_(id), value_(value) {} -AvrcpIntValue::~AvrcpIntValue() = default; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/avrcp_int_value.h b/system/service/common/bluetooth/avrcp_int_value.h deleted file mode 100644 index d9cf510e9c..0000000000 --- a/system/service/common/bluetooth/avrcp_int_value.h +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -namespace bluetooth { - -class AvrcpIntValue { - public: - AvrcpIntValue(); - AvrcpIntValue(const AvrcpIntValue& other); - AvrcpIntValue(int id, int value); - ~AvrcpIntValue(); - - int id() const { return id_; } - int value() const { return value_; } - - protected: - int id_ = 0; - int value_ = 0; -}; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/avrcp_media_attr.cc b/system/service/common/bluetooth/avrcp_media_attr.cc deleted file mode 100644 index fc50957dce..0000000000 --- a/system/service/common/bluetooth/avrcp_media_attr.cc +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "bluetooth/avrcp_media_attr.h" - -namespace bluetooth { - -AvrcpMediaAttr::AvrcpMediaAttr() = default; -AvrcpMediaAttr::AvrcpMediaAttr(const AvrcpMediaAttr& other) = default; -AvrcpMediaAttr::AvrcpMediaAttr(const std::string& title, - const std::string& artist, - const std::string& album, - const std::string& genre, int track_num, - int num_tracks, int play_time) - : title_(title), - artist_(artist), - album_(album), - genre_(genre), - track_num_(track_num), - num_tracks_(num_tracks), - play_time_(play_time) {} - -AvrcpMediaAttr::~AvrcpMediaAttr() = default; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/avrcp_media_attr.h b/system/service/common/bluetooth/avrcp_media_attr.h deleted file mode 100644 index 31a7cfd321..0000000000 --- a/system/service/common/bluetooth/avrcp_media_attr.h +++ /dev/null @@ -1,50 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <string> - -namespace bluetooth { - -class AvrcpMediaAttr { - public: - AvrcpMediaAttr(); - AvrcpMediaAttr(const AvrcpMediaAttr& other); - AvrcpMediaAttr(const std::string& title, const std::string& artist, - const std::string& album, const std::string& genre, - int track_num, int num_tracks, int play_time); - ~AvrcpMediaAttr(); - - const std::string& title() const { return title_; } - const std::string& artist() const { return artist_; } - const std::string& album() const { return album_; } - const std::string& genre() const { return genre_; } - int track_num() const { return track_num_; } - int num_tracks() const { return num_tracks_; } - int play_time() const { return play_time_; } - - protected: - std::string title_; - std::string artist_; - std::string album_; - std::string genre_; - int track_num_ = -1; - int num_tracks_ = -1; - int play_time_ = -1; -}; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/avrcp_register_notification_response.cc b/system/service/common/bluetooth/avrcp_register_notification_response.cc deleted file mode 100644 index 6200f77608..0000000000 --- a/system/service/common/bluetooth/avrcp_register_notification_response.cc +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "bluetooth/avrcp_register_notification_response.h" - -namespace bluetooth { - -AvrcpRegisterNotificationResponse::AvrcpRegisterNotificationResponse() = - default; -AvrcpRegisterNotificationResponse::AvrcpRegisterNotificationResponse( - const AvrcpRegisterNotificationResponse& other) = default; -AvrcpRegisterNotificationResponse::AvrcpRegisterNotificationResponse( - const btrc_register_notification_t& data) - : data_(data) {} -AvrcpRegisterNotificationResponse::~AvrcpRegisterNotificationResponse() = - default; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/avrcp_register_notification_response.h b/system/service/common/bluetooth/avrcp_register_notification_response.h deleted file mode 100644 index 3c78da2847..0000000000 --- a/system/service/common/bluetooth/avrcp_register_notification_response.h +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <hardware/bt_common_types.h> -#include <hardware/bt_rc.h> - -namespace bluetooth { - -class AvrcpRegisterNotificationResponse { - public: - AvrcpRegisterNotificationResponse(); - AvrcpRegisterNotificationResponse( - const AvrcpRegisterNotificationResponse& other); - AvrcpRegisterNotificationResponse(const btrc_register_notification_t& data); - ~AvrcpRegisterNotificationResponse(); - - const btrc_register_notification_t& data() const { return data_; } - - protected: - btrc_register_notification_t data_; -}; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/avrcp_string_value.h b/system/service/common/bluetooth/avrcp_string_value.h deleted file mode 100644 index 0b5cca443d..0000000000 --- a/system/service/common/bluetooth/avrcp_string_value.h +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <string> - -namespace bluetooth { - -class AvrcpStringValue { - public: - AvrcpStringValue() = default; - AvrcpStringValue(const AvrcpStringValue& other) = default; - AvrcpStringValue(int id, const std::string& value) : id_(id), value_(value){}; - ~AvrcpStringValue() = default; - - int id() const { return id_; } - const std::string& value() const { return value_; } - - protected: - int id_ = 0; - std::string value_; -}; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/characteristic.cc b/system/service/common/bluetooth/characteristic.cc deleted file mode 100644 index 28d02bc54d..0000000000 --- a/system/service/common/bluetooth/characteristic.cc +++ /dev/null @@ -1,54 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include <bluetooth/characteristic.h> - -namespace bluetooth { -Characteristic::Characteristic(const Characteristic& other) { - handle_ = other.handle_; - uuid_ = other.uuid_; - properties_ = other.properties_; - permissions_ = other.permissions_; - descriptors_ = other.descriptors_; -} - -Characteristic& Characteristic::operator=(const Characteristic& other) { - if (*this == other) return *this; - - handle_ = other.handle_; - uuid_ = other.uuid_; - properties_ = other.properties_; - permissions_ = other.permissions_; - descriptors_ = other.descriptors_; - - return *this; -} - -bool Characteristic::Equals(const Characteristic& other) const { - return handle_ == other.handle_ && uuid_ == other.uuid_ && - properties_ == other.properties_ && - permissions_ == other.permissions_ && - descriptors_ == other.descriptors_; -} - -bool Characteristic::operator==(const Characteristic& rhs) const { - return Equals(rhs); -} - -bool Characteristic::operator!=(const Characteristic& rhs) const { - return !Equals(rhs); -} -} diff --git a/system/service/common/bluetooth/characteristic.h b/system/service/common/bluetooth/characteristic.h deleted file mode 100644 index e6221b3c00..0000000000 --- a/system/service/common/bluetooth/characteristic.h +++ /dev/null @@ -1,59 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <bluetooth/descriptor.h> -#include <bluetooth/uuid.h> - -#include <vector> - -namespace bluetooth { -class Characteristic { - public: - Characteristic() = default; - Characteristic(const Characteristic& other); - Characteristic(uint16_t handle, const Uuid& uuid, uint8_t properties, - uint16_t permissions, - const std::vector<Descriptor>& descriptors) - : handle_(handle), - uuid_(uuid), - properties_(properties), - permissions_(permissions), - descriptors_(descriptors){}; - Characteristic& operator=(const Characteristic& other); - virtual ~Characteristic() = default; - - // Comparison function and operator. - bool Equals(const Characteristic& other) const; - bool operator==(const Characteristic& rhs) const; - bool operator!=(const Characteristic& rhs) const; - - uint16_t handle() const { return handle_; } - const Uuid& uuid() const { return uuid_; } - uint8_t properties() const { return properties_; } - uint16_t permissions() const { return permissions_; } - const std::vector<Descriptor>& descriptors() const { return descriptors_; } - std::vector<Descriptor>& descriptors() { return descriptors_; } - - protected: - uint16_t handle_; - Uuid uuid_; - uint8_t properties_; - uint16_t permissions_; - std::vector<Descriptor> descriptors_; -}; -} diff --git a/system/service/common/bluetooth/descriptor.cc b/system/service/common/bluetooth/descriptor.cc deleted file mode 100644 index b437cc3b4d..0000000000 --- a/system/service/common/bluetooth/descriptor.cc +++ /dev/null @@ -1,46 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include <bluetooth/descriptor.h> - -namespace bluetooth { -Descriptor::Descriptor(const Descriptor& other) { - handle_ = other.handle_; - uuid_ = other.uuid_; - permissions_ = other.permissions_; -} - -Descriptor& Descriptor::operator=(const Descriptor& other) { - if (*this == other) return *this; - - handle_ = other.handle_; - uuid_ = other.uuid_; - permissions_ = other.permissions_; - - return *this; -} - -bool Descriptor::Equals(const Descriptor& other) const { - return handle_ == other.handle_ && uuid_ == other.uuid_ && - permissions_ == other.permissions_; -} - -bool Descriptor::operator==(const Descriptor& rhs) const { return Equals(rhs); } - -bool Descriptor::operator!=(const Descriptor& rhs) const { - return !Equals(rhs); -} -} diff --git a/system/service/common/bluetooth/descriptor.h b/system/service/common/bluetooth/descriptor.h deleted file mode 100644 index 26338200a6..0000000000 --- a/system/service/common/bluetooth/descriptor.h +++ /dev/null @@ -1,45 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <bluetooth/uuid.h> - -namespace bluetooth { -class Descriptor { - public: - Descriptor() = default; - Descriptor(const Descriptor& other); - Descriptor& operator=(const Descriptor& other); - Descriptor(uint16_t handle, const Uuid& uuid, uint16_t permissions) - : handle_(handle), uuid_(uuid), permissions_(permissions){}; - virtual ~Descriptor() = default; - - // Comparison function and operator. - bool Equals(const Descriptor& other) const; - bool operator==(const Descriptor& rhs) const; - bool operator!=(const Descriptor& rhs) const; - - uint16_t handle() const { return handle_; } - uint16_t permissions() const { return permissions_; } - const Uuid& uuid() const { return uuid_; } - - protected: - uint16_t handle_; - Uuid uuid_; - uint16_t permissions_; -}; -} diff --git a/system/service/common/bluetooth/low_energy_constants.h b/system/service/common/bluetooth/low_energy_constants.h deleted file mode 100644 index 9ec0aee76f..0000000000 --- a/system/service/common/bluetooth/low_energy_constants.h +++ /dev/null @@ -1,125 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <stdint.h> - -namespace bluetooth { - -// Defined here are various status codes that can be returned from the stack for -// BLE operations. -enum BLEStatus { - BLE_STATUS_SUCCESS = 0, - BLE_STATUS_ADV_ERROR_DATA_TOO_LARGE = 1, - BLE_STATUS_ADV_ERROR_TOO_MANY_ADVERTISERS = 2, - BLE_STATUS_ADV_ERROR_ALREADY_STARTED = 3, - BLE_STATUS_ADV_ERROR_FEATURE_UNSUPPORTED = 5, - BLE_STATUS_FAILURE = 0x101, -}; - -enum GATTError { - GATT_ERROR_NONE = 0, - GATT_ERROR_INVALID_HANDLE = 0x01, - GATT_ERROR_READ_NOT_PERMITTED = 0x02, - GATT_ERROR_WRITE_NOT_PERMITTED = 0x03, - GATT_ERROR_INVALID_PDU = 0x04, - GATT_ERROR_INSUFFICIENT_AUTHEN = 0x05, - GATT_ERROR_REQUEST_NOT_SUPPORTED = 0x06, - GATT_ERROR_INVALID_OFFSET = 0x07, - GATT_ERROR_INSUFFICIENT_AUTHOR = 0x08, - GATT_ERROR_PREP_QUEUE_FULL = 0x09, - GATT_ERROR_ATTRIBUTE_NOT_FOUND = 0x0a, - GATT_ERROR_ATTRIBUTE_NOT_LONG = 0x0b, - GATT_ERROR_INSUFFICIENT_KEY_SIZE = 0x0c, - GATT_ERROR_INVALID_ATTRIBUTE_LENGTH = 0x0d, - GATT_ERROR_UNLIKELY = 0x0e, - GATT_ERROR_INSUFFICIENT_ENCR = 0x0f, - GATT_ERROR_UNSUPPORTED_GRP_TYPE = 0x10, - GATT_ERROR_INSUFFICIENT_RESOURCES = 0x11, - GATT_ERROR_CCCD_IMPROPERLY_CONFIGURED = 0xFD, - GATT_ERROR_PROCEDURE_IN_PROGRESS = 0xFE, - GATT_ERROR_OUT_OF_RANGE = 0xFF -}; - -enum Transport { TRANSPORT_AUTO = 0, TRANSPORT_BREDR = 1, TRANSPORT_LE = 2 }; - -// Android attribute permission values -const uint16_t kAttributePermissionNone = 0x0; -const uint16_t kAttributePermissionRead = 0x1; -const uint16_t kAttributePermissionReadEncrypted = 0x2; -const uint16_t kAttributePermissionReadEncryptedMITM = 0x4; -const uint16_t kAttributePermissionWrite = 0x10; -const uint16_t kAttributePermissionWriteEncrypted = 0x20; -const uint16_t kAttributePermissionWriteEncryptedMITM = 0x40; -const uint16_t kAttributePermissionWriteSigned = 0x80; -const uint16_t kAttributePermissionWriteSignedMITM = 0x100; - -// GATT characteristic properties bit-field values (not including the -// characteristic extended properties). -const uint8_t kCharacteristicPropertyNone = 0x0; -const uint8_t kCharacteristicPropertyBroadcast = 0x1; -const uint8_t kCharacteristicPropertyRead = 0x2; -const uint8_t kCharacteristicPropertyWriteNoResponse = 0x4; -const uint8_t kCharacteristicPropertyWrite = 0x8; -const uint8_t kCharacteristicPropertyNotify = 0x10; -const uint8_t kCharacteristicPropertyIndicate = 0x20; -const uint8_t kCharacteristicPropertySignedWrite = 0x40; -const uint8_t kCharacteristicPropertyExtendedProps = 0x80; - -// Advertising interval for different modes. -const int kAdvertisingIntervalHighMs = 1000; -const int kAdvertisingIntervalMediumMs = 250; -const int kAdvertisingIntervalLowMs = 100; - -// Add some randomness to the advertising min/max interval so the controller can -// do some optimization. -// TODO(armansito): I took this directly from packages/apps/Bluetooth but based -// on code review comments this constant and the accompanying logic doesn't make -// sense. Let's remove this constant and figure out how to properly calculate -// the Max. Adv. Interval. (See http://b/24344075). -const int kAdvertisingIntervalDeltaUnit = 10; - -// Legacy Advertising types (ADV_IND, ADV_SCAN_IND, etc.) that are exposed to -// applications. -const uint16_t kAdvertisingEventTypeLegacyConnectable = 0x0013; -const uint16_t kAdvertisingEventTypeLegacyScannable = 0x0012; -const uint16_t kAdvertisingEventTypeLegacyNonConnectable = 0x0010; - -// Advertising channels. These should be kept the same as those defined in the -// stack. -const int kAdvertisingChannel37 = (1 << 0); -const int kAdvertisingChannel38 = (1 << 1); -const int kAdvertisingChannel39 = (1 << 2); -const int kAdvertisingChannelAll = - (kAdvertisingChannel37 | kAdvertisingChannel38 | kAdvertisingChannel39); - -// Various Extended Inquiry Response fields types that are used for advertising -// data fields as defined in the Core Specification Supplement. -const uint8_t kEIRTypeFlags = 0x01; -const uint8_t kEIRTypeIncomplete16BitUuids = 0x02; -const uint8_t kEIRTypeComplete16BitUuids = 0x03; -const uint8_t kEIRTypeIncomplete32BitUuids = 0x04; -const uint8_t kEIRTypeComplete32BitUuids = 0x05; -const uint8_t kEIRTypeIncomplete128BitUuids = 0x06; -const uint8_t kEIRTypeComplete128BitUuids = 0x07; -const uint8_t kEIRTypeShortenedLocalName = 0x08; -const uint8_t kEIRTypeCompleteLocalName = 0x09; -const uint8_t kEIRTypeTxPower = 0x0A; -const uint8_t kEIRTypeServiceData = 0x16; -const uint8_t kEIRTypeManufacturerSpecificData = 0xFF; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/remote_device_props.cc b/system/service/common/bluetooth/remote_device_props.cc deleted file mode 100644 index 930421fbf9..0000000000 --- a/system/service/common/bluetooth/remote_device_props.cc +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "bluetooth/remote_device_props.h" - -using std::string; - -namespace bluetooth { - -RemoteDeviceProps::RemoteDeviceProps() = default; -RemoteDeviceProps::RemoteDeviceProps(const RemoteDeviceProps& other) = default; -RemoteDeviceProps::RemoteDeviceProps(const std::string& name, - const std::string& address, - const std::vector<Uuid>& service_uuids, - int32_t device_class, int32_t device_type, - int32_t rssi) - : name_(name), - address_(address), - service_uuids_(service_uuids), - device_class_(device_class), - device_type_(device_type), - rssi_(rssi) {} -RemoteDeviceProps::~RemoteDeviceProps() = default; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/remote_device_props.h b/system/service/common/bluetooth/remote_device_props.h deleted file mode 100644 index f8b3b1bce1..0000000000 --- a/system/service/common/bluetooth/remote_device_props.h +++ /dev/null @@ -1,53 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <string> -#include <vector> - -#include "bluetooth/uuid.h" - -namespace bluetooth { - -class RemoteDeviceProps { - public: - RemoteDeviceProps(); - RemoteDeviceProps(const RemoteDeviceProps& other); - RemoteDeviceProps(const std::string& name, const std::string& address, - const std::vector<Uuid>& service_uuids, - int32_t device_class, int32_t device_type, int32_t rssi); - ~RemoteDeviceProps(); - - void set_address(const std::string& address) { address_ = address; } - - const std::string& name() const { return name_; } - const std::string& address() const { return address_; } - const std::vector<Uuid>& service_uuids() const { return service_uuids_; } - int32_t device_class() const { return device_class_; } - int32_t device_type() const { return device_type_; } - int32_t rssi() const { return rssi_; } - - protected: - std::string name_; - std::string address_; - std::vector<Uuid> service_uuids_; - int32_t device_class_ = -1; - int32_t device_type_ = -1; - int32_t rssi_ = -1; -}; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/scan_filter.cc b/system/service/common/bluetooth/scan_filter.cc deleted file mode 100644 index 5aa4e9c39d..0000000000 --- a/system/service/common/bluetooth/scan_filter.cc +++ /dev/null @@ -1,92 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "bluetooth/scan_filter.h" - -#include <raw_address.h> - -namespace bluetooth { - -ScanFilter::ScanFilter(const ScanFilter& other) { - device_name_ = other.device_name_; - device_address_ = other.device_address_; - - if (other.service_uuid_) service_uuid_.reset(new Uuid(*other.service_uuid_)); - - if (other.service_uuid_mask_) - service_uuid_mask_.reset(new Uuid(*other.service_uuid_mask_)); -} - -ScanFilter& ScanFilter::operator=(const ScanFilter& other) { - device_name_ = other.device_name_; - device_address_ = other.device_address_; - - if (other.service_uuid_) - service_uuid_.reset(new Uuid(*other.service_uuid_)); - else - service_uuid_ = nullptr; - - if (other.service_uuid_mask_) - service_uuid_mask_.reset(new Uuid(*other.service_uuid_mask_)); - else - service_uuid_mask_ = nullptr; - - return *this; -} - -bool ScanFilter::SetDeviceAddress(const std::string& device_address) { - if (!RawAddress::IsValidAddress(device_address)) return false; - - device_address_ = device_address; - return true; -} - -void ScanFilter::SetServiceUuid(const Uuid& service_uuid) { - service_uuid_.reset(new Uuid(service_uuid)); - service_uuid_mask_.reset(); -} - -void ScanFilter::SetServiceUuidWithMask(const Uuid& service_uuid, - const Uuid& mask) { - service_uuid_.reset(new Uuid(service_uuid)); - service_uuid_mask_.reset(new Uuid(mask)); -} - -bool ScanFilter::operator==(const ScanFilter& rhs) const { - if (device_name_ != rhs.device_name_) return false; - - if (device_address_ != rhs.device_address_) return false; - - // Both must be either NULL or non-NULL. If only one of them is NULL, then - // return false. - if (!!service_uuid_ != !!rhs.service_uuid_) return false; - - if (service_uuid_ && rhs.service_uuid_ && - *service_uuid_ != *rhs.service_uuid_) - return false; - - // Both must be either NULL or non-NULL. If only one of them is NULL, then - // return false. - if (!!service_uuid_mask_ != !!rhs.service_uuid_mask_) return false; - - if (service_uuid_mask_ && rhs.service_uuid_mask_ && - *service_uuid_mask_ != *rhs.service_uuid_mask_) - return false; - - return true; -} - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/scan_filter.h b/system/service/common/bluetooth/scan_filter.h deleted file mode 100644 index e0afaa7267..0000000000 --- a/system/service/common/bluetooth/scan_filter.h +++ /dev/null @@ -1,77 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <memory> - -#include <bluetooth/uuid.h> - -namespace bluetooth { - -// Used for filtering scan results by allowing clients to restrict scan results -// to only those that are of interest to them. -class ScanFilter { - public: - ScanFilter() = default; - virtual ~ScanFilter() = default; - - // Copy constructor and assignment operator. - ScanFilter(const ScanFilter& other); - ScanFilter& operator=(const ScanFilter& other); - - // The device name used while filtering scan results. - const std::string& device_name() const { return device_name_; } - void set_device_name(const std::string& name) { device_name_ = name; } - - // The device address used while filtering scan results. Address should be in - // the XX:XX:XX:XX:XX:XX where X is a hexadecimal digit. - const std::string& device_address() const { return device_address_; } - - // Sets the device address used for filtering. Returns false if - // |device_address| is in an illegal format. - bool SetDeviceAddress(const std::string& device_address); - - // The service Uuid and its mask used while filtering scan results. See - // SetServiceUuidWithMask for what this mask does. The raw pointer returned - // from these getters belongs to the ScanFilter object. nullptr will be - // returned if these fields have not been set on this filter. - const Uuid* service_uuid() const { return service_uuid_.get(); } - const Uuid* service_uuid_mask() const { return service_uuid_mask_.get(); } - - // Sets the service Uuid for this filter. - void SetServiceUuid(const Uuid& service_uuid); - - // Sets the service Uuid for this filter with a 128-bit mask. The mask allows - // the caller to partially filter scanned service Uuids. For any of the - // 128-bits of a Uuid, set the corresponding bit in the mask to 1 to match the - // advertised value, and 0 to ignore that bit. - void SetServiceUuidWithMask(const Uuid& service_uuid, const Uuid& mask); - - // Comparison operator. - bool operator==(const ScanFilter& rhs) const; - - protected: - std::string device_name_; - std::string device_address_; - - std::unique_ptr<Uuid> service_uuid_; - std::unique_ptr<Uuid> service_uuid_mask_; - - // TODO(armansito): Add service and manufacturer data filter fields. -}; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/scan_result.cc b/system/service/common/bluetooth/scan_result.cc deleted file mode 100644 index 525889756e..0000000000 --- a/system/service/common/bluetooth/scan_result.cc +++ /dev/null @@ -1,41 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "bluetooth/scan_result.h" -#include "raw_address.h" - -#include <base/logging.h> - -namespace bluetooth { - -ScanResult::ScanResult(const std::string& device_address, - const std::vector<uint8_t>& scan_record, int rssi) - : device_address_(device_address), scan_record_(scan_record), rssi_(rssi) { - CHECK(RawAddress::IsValidAddress(device_address)) << "Invalid BD_ADDR given: " - << device_address; -} - -bool ScanResult::operator==(const ScanResult& rhs) const { - if (device_address_ != rhs.device_address_) return false; - - if (scan_record_ != rhs.scan_record_) return false; - - if (rssi_ != rhs.rssi_) return false; - - return true; -} - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/scan_result.h b/system/service/common/bluetooth/scan_result.h deleted file mode 100644 index 7fc62efca5..0000000000 --- a/system/service/common/bluetooth/scan_result.h +++ /dev/null @@ -1,54 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <stdint.h> - -#include <string> -#include <vector> - -namespace bluetooth { - -// ScanResult represents a single Bluetooth LE device scan result. It -// encapsulates information about discovered LE devices. -class ScanResult { - public: - ScanResult(const std::string& device_address, - const std::vector<uint8_t>& scan_record, int rssi); - ScanResult() = default; - virtual ~ScanResult() = default; - - // Returns the remote BD_ADDR associated with this scan result. - const std::string& device_address() const { return device_address_; } - - // Returns the scan record (advertising +scan-response data) associated with - // this scan result. - const std::vector<uint8_t>& scan_record() const { return scan_record_; } - - // Returns the RSSI associated with this scan result. - int rssi() const { return rssi_; } - - // Comparison operator. - bool operator==(const ScanResult& rhs) const; - - protected: - std::string device_address_; - std::vector<uint8_t> scan_record_; - int rssi_; -}; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/scan_settings.cc b/system/service/common/bluetooth/scan_settings.cc deleted file mode 100644 index 7f9aa906a2..0000000000 --- a/system/service/common/bluetooth/scan_settings.cc +++ /dev/null @@ -1,55 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "bluetooth/scan_settings.h" - -namespace bluetooth { - -ScanSettings::ScanSettings() - : mode_(MODE_LOW_POWER), - callback_type_(CALLBACK_TYPE_ALL_MATCHES), - result_type_(RESULT_TYPE_FULL), - match_count_per_filter_(MATCH_COUNT_MAX_ADVERTISEMENTS) {} - -ScanSettings::ScanSettings(Mode mode, CallbackTypeBitField callback_type, - ResultType result_type, - base::TimeDelta report_delay_ms, - MatchMode match_mode, - MatchCount match_count_per_filter) - : mode_(mode), - callback_type_(callback_type), - result_type_(result_type), - report_delay_ms_(report_delay_ms), - match_mode_(match_mode), - match_count_per_filter_(match_count_per_filter) {} - -bool ScanSettings::operator==(const ScanSettings& rhs) const { - if (mode_ != rhs.mode_) return false; - - if (callback_type_ != rhs.callback_type_) return false; - - if (result_type_ != rhs.result_type_) return false; - - if (report_delay_ms_ != rhs.report_delay_ms_) return false; - - if (match_mode_ != rhs.match_mode_) return false; - - if (match_count_per_filter_ != rhs.match_count_per_filter_) return false; - - return true; -} - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/scan_settings.h b/system/service/common/bluetooth/scan_settings.h deleted file mode 100644 index 30f98ba682..0000000000 --- a/system/service/common/bluetooth/scan_settings.h +++ /dev/null @@ -1,161 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <base/time/time.h> - -namespace bluetooth { - -// ScanSettings encapsulates Bluetooth LE device scan parameters. This is the -// native equivalent of the Android framework class defined in -// frameworks/base/core/java/android/bluetooth/le/ScanSettings.java. -class ScanSettings { - public: - // A scan mode describes the power consumption involved in LE scans. - enum Mode { - // A special Bluetooth LE scan mode. Applications using this scan mode will - // passively listen for other scan results without starting BLE scans - // themselves. - MODE_OPPORTUNISTIC = -1, - - // Perform Bluetooth LE scan in low power mode. This is the default scan - // mode as it consumes the least power. - MODE_LOW_POWER = 0, - - // Perform Bluetooth LE scan in balanced power mode. Scan results are - // returned at a rate that provides a good trade-off between scan frequency - // and power consumption. - MODE_BALANCED = 1, - - // Scan using the highest duty cycle. It's recommended to only use this mode - // when the application is running in the foreground. - MODE_LOW_LATENCY = 2, - }; - - // A callback type describes how scan results will be reported to applications - // in asynchronous callbacks. - enum CallbackType { - // Trigger a callback for every Bluetooth advertisement found that matches - // the filter criteria. If no filter is active, all advertisement packets - // are reported. - CALLBACK_TYPE_ALL_MATCHES = 1, - - // A result callback is only triggered for the first advertisement packet - // received that matches the filter criteria. This requires that the - // hardware support the offloaded filtering feature. - CALLBACK_TYPE_FIRST_MATCH = 2, - - // Receive a callback when advertisements are no longer received from a - // device that has been previously reported by a first match callback. This - // requires that the hardware support the offloaded filtering feature. - CALLBACK_TYPE_MATCH_LOST = 4, - }; - using CallbackTypeBitField = int; - - // Determines how many advertisements to match per filter. - enum MatchCount { - // Match one advertisement per filter. - MATCH_COUNT_ONE_ADVERTISEMENT = 1, - - // Match few advertisements per filter depending on the current capability - // and availability of hardware resources. - MATCH_COUNT_FEW_ADVERTISEMENTS = 2, - - // Match as many advertisements per filter as the underlying hardware can - // allow, depending on the current capability and availability of hardware - // resources. - MATCH_COUNT_MAX_ADVERTISEMENTS = 3, - }; - - // Hardware filter match mode. - enum MatchMode { - // In aggressive mode the hardware will determine a match sooner even with - // feeble signal strength and a low number of sightings in a duration. - MATCH_MODE_AGGRESSIVE = 1, - - // In sticky mode a higher threshold of signal strength and sightings is - // required before a scan result is reported by the hardware. - MATCH_MODE_STICKY = 2, - }; - - // Scan result type describes the contents of each scan result. - enum ResultType { - // Request full scan results which contain the device name, RSSI, - // advertising data, scan response data, and the scan timestamp. - RESULT_TYPE_FULL = 0, - - // Request abbreviated scan results which contain the device name, RSSI, and - // scan timestamp. - // Note: It is possible for an application to get more scan results than it - // asked for, if there are multiple apps using this type. - RESULT_TYPE_ABBREVIATED = 1, - }; - - // The default constructor sets all fields to defaults: - // mode: MODE_LOW_POWER - // callback_type: CALLBACK_TYPE_ALL_MATCHES - // result_type: RESULT_TYPE_FULL - // report_delay_ms: 0 - // match_mode: MATCH_MODE_AGGRESSIVE - // match_count_per_filter: MATCH_COUNT_MAX_ADVERTISEMENTS - ScanSettings(); - ScanSettings(Mode mode, CallbackTypeBitField callback_type, - ResultType result_type, base::TimeDelta report_delay_ms, - MatchMode match_mode, MatchCount match_count_per_filter); - virtual ~ScanSettings() = default; - - // Returns the scan mode. - Mode mode() const { return mode_; } - void set_mode(Mode mode) { mode_ = mode; } - - // Returns the callback type. - CallbackTypeBitField callback_type() const { return callback_type_; } - void set_callback_type(CallbackTypeBitField type) { callback_type_ = type; } - - // Returns the scan result type. - ResultType result_type() const { return result_type_; } - void set_result_type(ResultType type) { result_type_ = type; } - - // Returns the report delay value in milliseconds. - const base::TimeDelta& report_delay() const { return report_delay_ms_; } - void set_report_delay(const base::TimeDelta& delay) { - report_delay_ms_ = delay; - } - - // Returns the hardware filter match mode. - MatchMode match_mode() const { return match_mode_; } - void set_match_mode(MatchMode mode) { match_mode_ = mode; } - - // Returns the count of advertisements to match per filter. - MatchCount match_count_per_filter() const { return match_count_per_filter_; } - void set_match_count_per_filter(MatchCount count) { - match_count_per_filter_ = count; - } - - // Comparison operator. - bool operator==(const ScanSettings& rhs) const; - - protected: - Mode mode_; - CallbackTypeBitField callback_type_; - ResultType result_type_; - base::TimeDelta report_delay_ms_; - MatchMode match_mode_; - MatchCount match_count_per_filter_; -}; - -} // namespace bluetooth diff --git a/system/service/common/bluetooth/service.cc b/system/service/common/bluetooth/service.cc deleted file mode 100644 index e9b3091e58..0000000000 --- a/system/service/common/bluetooth/service.cc +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include <bluetooth/service.h> - -namespace bluetooth { -Service::Service(const Service& other) { - handle_ = other.handle_; - primary_ = other.primary_; - uuid_ = other.uuid_; - characteristics_ = other.characteristics_; - included_services_ = other.included_services_; -} - -Service& Service::operator=(const Service& other) { - if (*this == other) return *this; - - handle_ = other.handle_; - primary_ = other.primary_; - uuid_ = other.uuid_; - characteristics_ = other.characteristics_; - included_services_ = other.included_services_; - return *this; -} - -bool Service::Equals(const Service& other) const { - return handle_ == other.handle_ && primary_ == other.primary_ && - uuid_ == other.uuid_ && characteristics_ == other.characteristics_ && - included_services_ == other.included_services_; -} - -bool Service::operator==(const Service& rhs) const { return Equals(rhs); } - -bool Service::operator!=(const Service& rhs) const { return !Equals(rhs); } -} diff --git a/system/service/common/bluetooth/service.h b/system/service/common/bluetooth/service.h deleted file mode 100644 index 9143d6deeb..0000000000 --- a/system/service/common/bluetooth/service.h +++ /dev/null @@ -1,63 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <bluetooth/characteristic.h> -#include <bluetooth/uuid.h> - -#include <vector> - -namespace bluetooth { -class Service { - public: - Service() = default; - Service(const Service& other); - Service(uint16_t handle, bool primary, const Uuid& uuid, - const std::vector<Characteristic>& characteristics, - const std::vector<Service>& included_services) - : handle_(handle), - primary_(primary), - uuid_(uuid), - characteristics_(characteristics), - included_services_(included_services){}; - Service& operator=(const Service& other); - virtual ~Service() = default; - - // Comparison function and operator. - bool Equals(const Service& other) const; - bool operator==(const Service& rhs) const; - bool operator!=(const Service& rhs) const; - - uint16_t handle() const { return handle_; } - bool primary() const { return primary_; } - const Uuid& uuid() const { return uuid_; } - const std::vector<Characteristic>& characteristics() const { - return characteristics_; - } - std::vector<Characteristic>& characteristics() { return characteristics_; } - const std::vector<Service>& included_services() const { - return included_services_; - } - - protected: - uint16_t handle_; - bool primary_; - Uuid uuid_; - std::vector<Characteristic> characteristics_; - std::vector<Service> included_services_; -}; -} diff --git a/system/service/common/bluetooth/util/atomic_string.cc b/system/service/common/bluetooth/util/atomic_string.cc deleted file mode 100644 index e431b4008c..0000000000 --- a/system/service/common/bluetooth/util/atomic_string.cc +++ /dev/null @@ -1,34 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/common/bluetooth/util/atomic_string.h" - -namespace util { - -AtomicString::AtomicString(const std::string& str) : str_(str) {} - -std::string AtomicString::Get() const { - std::mutex* mutex = const_cast<std::mutex*>(&lock_); - std::lock_guard<std::mutex> lock(*mutex); - return str_; -} - -void AtomicString::Set(const std::string& str) { - std::lock_guard<std::mutex> lock(lock_); - str_ = str; -} - -} // namespace util diff --git a/system/service/common/bluetooth/util/atomic_string.h b/system/service/common/bluetooth/util/atomic_string.h deleted file mode 100644 index f5ed1c3ba4..0000000000 --- a/system/service/common/bluetooth/util/atomic_string.h +++ /dev/null @@ -1,42 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <mutex> -#include <string> - -namespace util { - -// A simple atomic container class for std::string. -class AtomicString final { - public: - explicit AtomicString(const std::string& str); - - AtomicString(const AtomicString&) = delete; - AtomicString& operator=(const AtomicString&) = delete; - - ~AtomicString() = default; - - std::string Get() const; - void Set(const std::string& str); - - private: - std::mutex lock_; - std::string str_; -}; - -} // namespace util diff --git a/system/service/daemon.cc b/system/service/daemon.cc deleted file mode 100644 index 11bfae1722..0000000000 --- a/system/service/daemon.cc +++ /dev/null @@ -1,207 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/daemon.h" - -#include <memory> - -#include <base/logging.h> -#include <base/run_loop.h> - -#include "abstract_message_loop.h" -#include "service/adapter.h" -#include "service/hal/bluetooth_av_interface.h" -#include "service/hal/bluetooth_avrcp_interface.h" -#include "service/hal/bluetooth_gatt_interface.h" -#include "service/hal/bluetooth_interface.h" -#include "service/ipc/ipc_manager.h" -#include "service/settings.h" -#include "service/switches.h" - -namespace bluetooth { - -namespace { - -// The global Daemon instance. -Daemon* g_daemon = nullptr; - -class DaemonImpl : public Daemon, public ipc::IPCManager::Delegate { - public: - DaemonImpl() : initialized_(false) {} - - DaemonImpl(const DaemonImpl&) = delete; - DaemonImpl& operator=(const DaemonImpl&) = delete; - - ~DaemonImpl() override { - if (!initialized_) return; - - CleanUpBluetoothStack(); - } - - void StartMainLoop() override { base::RunLoop().Run(); } - - Settings* GetSettings() const override { return settings_.get(); } - - btbase::AbstractMessageLoop* GetMessageLoop() const override { - return message_loop_.get(); - } - - private: - // ipc::IPCManager::Delegate implementation: - void OnIPCHandlerStarted(ipc::IPCManager::Type /* type */) override { - if (!settings_->EnableOnStart()) return; - adapter_->Enable(); - } - - void OnIPCHandlerStopped(ipc::IPCManager::Type /* type */) override { - // Do nothing. - } - - bool StartUpBluetoothInterfaces() { - if (!hal::BluetoothInterface::Initialize()) goto failed; - - if (!hal::BluetoothGattInterface::Initialize()) goto failed; - - if (!hal::BluetoothAvInterface::Initialize()) goto failed; - - if (!hal::BluetoothAvrcpInterface::Initialize()) goto failed; - - return true; - - failed: - ShutDownBluetoothInterfaces(); - return false; - } - - void ShutDownBluetoothInterfaces() { - if (hal::BluetoothGattInterface::IsInitialized()) - hal::BluetoothGattInterface::CleanUp(); - if (hal::BluetoothInterface::IsInitialized()) - hal::BluetoothInterface::CleanUp(); - if (hal::BluetoothAvInterface::IsInitialized()) - hal::BluetoothAvInterface::CleanUp(); - if (hal::BluetoothAvrcpInterface::IsInitialized()) - hal::BluetoothAvrcpInterface::CleanUp(); - } - - void CleanUpBluetoothStack() { - // The Adapter object needs to be cleaned up before the HAL interfaces. - ipc_manager_.reset(); - adapter_.reset(); - ShutDownBluetoothInterfaces(); - } - - bool SetUpIPC() { - // If an IPC socket path was given, initialize IPC with it. Otherwise - // initialize Binder IPC. - if (settings_->UseSocketIPC()) { - if (!ipc_manager_->Start(ipc::IPCManager::TYPE_LINUX, this)) { - LOG(ERROR) << "Failed to set up UNIX domain-socket IPCManager"; - return false; - } - return true; - } - -#if !defined(OS_GENERIC) - if (!ipc_manager_->Start(ipc::IPCManager::TYPE_BINDER, this)) { - LOG(ERROR) << "Failed to set up Binder IPCManager"; - return false; - } -#else - if (!ipc_manager_->Start(ipc::IPCManager::TYPE_DBUS, this)) { - LOG(ERROR) << "Failed to set up DBus IPCManager"; - return false; - } -#endif - - return true; - } - - bool Init() override { - CHECK(!initialized_); - message_loop_.reset(new btbase::AbstractMessageLoop()); - - settings_.reset(new Settings()); - if (!settings_->Init()) { - LOG(ERROR) << "Failed to set up Settings"; - return false; - } - - if (!StartUpBluetoothInterfaces()) { - LOG(ERROR) << "Failed to set up HAL Bluetooth interfaces"; - return false; - } - - adapter_ = Adapter::Create(); - ipc_manager_.reset(new ipc::IPCManager(adapter_.get())); - - if (!SetUpIPC()) { - CleanUpBluetoothStack(); - return false; - } - - initialized_ = true; - LOG(INFO) << "Daemon initialized"; - - return true; - } - - bool initialized_; - std::unique_ptr<btbase::AbstractMessageLoop> message_loop_; - std::unique_ptr<Settings> settings_; - std::unique_ptr<Adapter> adapter_; - std::unique_ptr<ipc::IPCManager> ipc_manager_; -}; - -} // namespace - -// static -bool Daemon::Initialize() { - CHECK(!g_daemon); - - g_daemon = new DaemonImpl(); - if (g_daemon->Init()) return true; - - LOG(ERROR) << "Failed to initialize the Daemon object"; - - delete g_daemon; - g_daemon = nullptr; - - return false; -} - -// static -void Daemon::ShutDown() { - CHECK(g_daemon); - delete g_daemon; - g_daemon = nullptr; -} - -// static -void Daemon::InitializeForTesting(Daemon* test_daemon) { - CHECK(test_daemon); - CHECK(!g_daemon); - - g_daemon = test_daemon; -} - -// static -Daemon* Daemon::Get() { - CHECK(g_daemon); - return g_daemon; -} - -} // namespace bluetooth diff --git a/system/service/daemon.h b/system/service/daemon.h deleted file mode 100644 index a1f26a07e2..0000000000 --- a/system/service/daemon.h +++ /dev/null @@ -1,74 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include "abstract_message_loop.h" - -namespace ipc { -class IPCManager; -} // namespace ipc - -namespace bluetooth { - -class CoreStack; -class Settings; - -// The Daemon class is a singleton that represents the root of the ownership -// hierarchy. The single instance sets up and owns the main event loop, the IPC -// handlers, global Settings, and the core Bluetooth stack. -class Daemon { - public: - // Initializes the daemon. This must be called to at the start of the - // application to set up the global daemon instance and everything it manages. - // Returns false in case of a failure. - static bool Initialize(); - - // Cleans up all the resources associated with the global Daemon object. - static void ShutDown(); - - // Assigns the global Daemon instance for testing. Should only be called from - // test code. - static void InitializeForTesting(Daemon* test_daemon); - - // Returns the singleton Daemon instance. All classes can interact with the - // Daemon, obtain its resources etc using this getter. - static Daemon* Get(); - - // The global Settings object. All classes have direct access to this through - // the Daemon object. - virtual Settings* GetSettings() const = 0; - - // The main event loop. This should be used for any events and delayed tasks - // that should be executed on the daemon's main thread. - virtual btbase::AbstractMessageLoop* GetMessageLoop() const = 0; - - // Starts the daemon's main loop. - virtual void StartMainLoop() = 0; - - protected: - Daemon() = default; - Daemon(const Daemon&) = delete; - Daemon& operator=(const Daemon&) = delete; - - virtual ~Daemon() = default; - - private: - // Internal instance helper called by Initialize(). - virtual bool Init() = 0; -}; - -} // namespace bluetooth diff --git a/system/service/doc/IBluetooth.txt b/system/service/doc/IBluetooth.txt deleted file mode 100644 index 6560daa6f5..0000000000 --- a/system/service/doc/IBluetooth.txt +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2015, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Binder IPC API for talking with the Bluetooth service and perform high-level - * operations on the adapter. - */ -interface IBluetooth { - /** - * Returns true if the Bluetooth adapter is powered and ready to use. This - * is equivalent to "getState() == ADAPTER_STATE_ON". - */ - boolean isEnabled(); - - /** - * Returns the current Bluetooth adapter state. The return value can be one of - * the following: - * - * - ADAPTER_STATE_OFF = 10 - * - ADAPTER_STATE_TURNING_ON = 11 - * - ADAPTER_STATE_ON = 12 - * - ADAPTER_STATE_TURNING_OFF = 13 - */ - int getState(); - - /** - * Turns on the Bluetooth radio. This function initiates the procedure to - * bring the adapter state from ADAPTER_STATE_OFF to ADAPTER_STATE_ON. Returns - * false, if the state is not ADAPTER_STATE_OFF or if there is an error while - * initiating the operation. On success, the adapter state will be - * asynchronously updated to ADAPTER_STATE_TURNING_ON and eventually to - * ADAPTER_STATE_ON. Callers can monitor the status of this call by observing - * the IBluetoothCallback.onBluetoothStateChange callback. - */ - boolean enable(); - - /** - * Turns off the Bluetooth radio. This function initiates the procedure to - * bring the adapter state from ADAPTER_STATE_ON to ADAPTER_STATE_OFF. Returns - * false, if the state is not ADAPTER_STATE_ON or if there is an error while - * initiating the operation. On success, the adapter state will be - * asynchronously updated to ADAPTER_STATE_TURNING_OFF and eventually to - * ADAPTER_STATE_OFF. Callers can monitor the status of this call by observing - * the IBluetoothCallback.onBluetoothStateChange callback. - */ - boolean disable(); - - /** - * Returns the identity Bluetooth Device Address (BD_ADDR) assigned to the - * underlying Bluetooth controller. Returns a string of the form - * "XX:XX:XX:XX:XX:XX", where each "X" is a hexadecimal digit. Returns - * "00:00:00:00:00:00" if the address is not known, which is usually the case - * before the adapter is enabled for the first time. - */ - String getAddress(); - - /** - * Sets the name assigned to the Bluetooth adapter. This is the name that will - * be seen by remote devices during discovery. Returns false if the operation - * fails. - */ - boolean setName(in String name); - - /** - * Returns the current name assigned to the Bluetooth adapter. This is the - * name that is seen by remote devices during discovery. If the controller has - * not been initialized yet (before the first time it gets enabled), this will - * return "not-initialized". - */ - String getName(); - - /** - * Registers a callback receiver which can be used to listen to state updates - * from the adapter. The Bluetooth daemon will automatically register this if - * the owning process dies. - */ - void registerCallback(in IBluetoothCallback callback); - - /** - * Unregisters a previously registered callback. - */ - void unregisterCallback(in IBluetoothCallback callback); - - /** - * Returns true, if the multi-advertisement feature is supported. Returns - * false, if this device can only advertise a single instance. - */ - boolean isMultiAdvertisementSupported(); - - /** - * Returns a binder that can be used to interact with Low-Energy features. - */ - IBluetoothLowEnergy getLowEnergyInterface(); - - /** - * Returns a binder that can be used to interact with GATT client-role - * features. - */ - IBluetoothGattClient getGattClientInterface(); - - /** - * Returns a binder that can be used to interact with GATT server-role - * features. - */ - IBluetoothGattServer getGattServerInterface(); -} diff --git a/system/service/doc/IBluetoothCallback.txt b/system/service/doc/IBluetoothCallback.txt deleted file mode 100644 index 93dcdef4d6..0000000000 --- a/system/service/doc/IBluetoothCallback.txt +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2015, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Binder IPC callback interface for receiving notifications about the - * high-level Bluetooth adapter state. - */ -interface IBluetoothCallback { - /** - * Called when the adapter state changes from |prev_state| to |new_state|. - */ - void onBluetoothStateChange(in int prev_state, in int new_state); -} diff --git a/system/service/doc/IBluetoothGattClient.txt b/system/service/doc/IBluetoothGattClient.txt deleted file mode 100644 index b0fc90553c..0000000000 --- a/system/service/doc/IBluetoothGattClient.txt +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright 2015, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Binder IPC interface for interacting with Bluetooth GATT client-role - * features. - * TODO(armansito): Not yet supported. - */ -interface IBluetoothGattClient { - /** - * Registers a client application with this interface. This creates a unique - * GATT client instance for the application. Returns true on success; false - * otherwise. If successful, the caller will be assigned a "client_id" which - * will be reported asynchronously via - * IBluetoothGattClientCallback.onRegistered. This ID is required to make - * calls to the functions defined below. - */ - boolean registerClient(in IBluetoothGattClientCallback callback); - - /** - * Unregisters a previously registered client with interface ID |client_id|. - */ - void unregisterClient(in int client_id); - - /** - * Unregisters all previously registered clients. - */ - void unregisterAll(); - - /** - * Refreshes the local client-side attribute cache that mirrors the attribute - * database of remote device with address |device_address|. Returns false in - * case of an error. |client_id| is the identifier obtained via - * registerClient. - */ - boolean refreshDevice(in int client_id, in String device_address); - - /** - * Returns the GATT services, characteristics, and descriptors on the remote - * device with address |device_address| asynchronously via the corresponding - * IBluetoothGattClientCallback callbacks. Based on the current connection and - * bonding state, either GATT service discovery will be initiated or the - * results will be returned from the attribute cache. Returns false in case of - * an error. |client_id| is the identifier obtained via registerClient. - */ - boolean discoverServices(in int client_id, in String device_address); - - /** - * Initiate a read request for the remote characteristic with identifier - * |characteristic_id|. The result will be asynchronously reported in - * IBluetoothGattClientCallback.onCharacteristicRead. Returns false if the - * request cannot be started, e.g. if a read is already pending on this remote - * device. If the read request fails due to characteristic permissions, - * this function will try to raise the connection security level based on the - * characteristic's permission requirements. If that operation fails, then the - * |status| parameter of the onCharacteristicRead callback will contain the - * appropriate ATT protocol error code. |client_id| is obtained via - * registerClient. - */ - boolean readCharacteristic(in int client_id, - in GattIdentifier characteristic_id); - - /** - * Initiate a write request for the remote characteristic with identifier - * |characteristic_id| with the value |value|. The |write_type| parameter - * indicates which of the following GATT write procedure should be used: - * - * - WRITE_TYPE_DEFAULT (0x02): Regular Write Procedure - * - WRITE_TYPE_NO_RESPONSE (0x01): Write Without Response procedure - * - WRITE_TYPE_SIGNED (0x04): Signed Write Without Response procedure. - * - * The result will be asynchronously reported in - * IBluetoothGattClientCallback.onCharacteristicWrite. Returns false if the - * request cannot be started. If the write request fails due to attribute - * permissions, this function will try to raise the connection security level - * based on the characteristic's permission requirements. If that operation - * fails, then the |status| parameter of the onCharacteristicWrite callback - * will contain the appropriate ATT protocol error code. |client_id| is - * obtained via registerClient. - */ - boolean writeCharacteristic(in int client_id, - in GattIdentifier characteristic_id, - in int write_type, - in byte[] value); - - /** - * Initiate a read request for the remote descriptor with identifier - * |descriptor_id|. The result will be asynchronously reported in - * IBluetoothGattClientCallback.onDescriptorRead. Returns false if the - * request cannot be started, e.g. if a read is already pending on this remote - * device. If the read request fails due to descriptor permissions, - * this function will try to raise the connection security level based on the - * descriptor's permission requirements. If that operation fails, then the - * |status| parameter of the onDescriptorRead callback will contain the - * appropriate ATT protocol error code. |client_id| is obtained via - * registerClient. - */ - boolean readDescriptor(in int client_id, - in GattIdentifier descriptor_id); - - /** - * Initiate a write request for the remote descriptor with identifier - * |descriptor_id| with the value |value|. The |write_type| parameter - * indicates which of the following GATT write procedure should be used: - * - * - WRITE_TYPE_DEFAULT (0x02): Regular write procedure - * - WRITE_TYPE_NO_RESPONSE (0x01): Write without response procedure - * - WRITE_TYPE_SIGNED (0x04): Authenticated-signed write procedure - * - * The result will be asynchronously reported in - * IBluetoothGattClientCallback.onDescriptorWrite. Returns false if the - * request cannot be started. If the write request fails due to attribute - * permissions, this function will try to raise the connection security level - * based on the descriptor's permission requirements. If that operation fails, - * then the |status| parameter of the onDescriptorWrite callback will contain - * the appropriate ATT protocol error code. |client_id| is obtained via - * registerClient. - */ - boolean writeDescriptor(in int client_id, - in GattIdentifier descriptor_id, - in int write_type, - in byte[] value); - - /** - * Enables handle-value notifications from the remote characteristic with ID - * |characteristic_id|. If successful, notifications will be signaled via - * IBluetoothGattClientCallback.onNotify. Returns false if the request cannot - * be initiated. |client_id| is obtained via registerClient. - */ - boolean registerForNotifications(in int client_id, - in GattIdentifier characteristic_id); - - /** - * Disables handle-value notifications from the remote characteristic with ID - * |characteristic_id|. Returns false if the request cannot be initiated, e.g. - * if notifications from this characteristic have not been enabled. - * |client_id| is obtained via registerClient. - */ - boolean unregisterForNotifications(in int client_id, - in GattIdentifier characteristic_id); - - /** - * Initiates a reliable write procedure for the remote device with address - * |device_address|. Once a reliable write transaction has been initiated, all - * calls to writeCharacteristic are sent to the remote device for verification - * and queued up for atomic execution. The application can verify each write - * payload using the IBluetoothGattClientCallback.onCharacteristicWrite - * callback and abort reliable write in case of a mismatch. The queued writes - * will be processed atomically by the remote device after calling - * endReliableWrite. Returns false if the procedure cannot be started, e.g. if - * it has already been started earlier. |client_id| is obtained via - * registerClient. - */ - boolean beginReliableWrite(in int client_id, in String device_address); - - /** - * Ends a previously started reliable write procedure for the remote device - * with address |device_address|. If |execute| is true, then a request will be - * sent to execute the queued writes, else a request will be sent to abort the - * queued writes. Returns false in case of a failure, e.g. if a reliable write - * procedure was not started. IBluetoothGattClientCallback.onExecuteWrite will - * be used to asynchronously report the result of the execute write request. - * |client_id| is obtained via registerClient. - */ - boolean endReliableWrite(in int client_id, in String device_address, - in boolean execute); -} diff --git a/system/service/doc/IBluetoothGattClientCallback.txt b/system/service/doc/IBluetoothGattClientCallback.txt deleted file mode 100644 index 455fcacc88..0000000000 --- a/system/service/doc/IBluetoothGattClientCallback.txt +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2015, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Binder IPC interface for receiving callbacks related to Bluetooth GATT - * client-role operations. - * TODO(armansito): Not yet supported. - */ -oneway interface IBluetoothGattClientCallback { - /** - * Called as a result of IBluetoothGattClient.registerClient. - * |status| will contain BLE_STATUS_SUCCESS (0) if the client was successfully - * registered. |client_id| is the owning application's unique GATT client - * handle and can be used to perform further operations on the - * IBluetoothGattClient interface. - */ - void onClientRegistered(in int status, in int client_id); - - /** - * Called for each GATT service that was discovered on the remote device. The - * device that this service belongs to can be obtained from the |service_id| - * structure. |is_primary| is true if this refers to a primary service, - * otherwise this refers to a secondary service. - */ - void onGetService(in boolean is_primary, in GattIdentifier service_id); - - /** - * Called for each include definition that was discovered on the remote - * device. - */ - void onGetIncludedService(in GattIdentifier included_service_id); - - /** - * Called for each characteristic that was discovered on the remote device. - * The service that this characteristic belongs to can be obtained from the - * |characteristic_id| structure. |properties| contains the bitmask of GATT - * characteristic properties as defined in the Bluetooth Core Specification. - */ - void onGetCharacteristic(in GattIdentifier characteristic_id, - in int properties); - - /** - * Called for each descriptor that was discovered on the remote device. The - * service and characteristic that this descriptor belongs to can be obtained - * from the |descriptor_id| structure. - */ - void onGetDescriptor(in GattIdentifier descriptor_id); - - /** - * Called to mark the end of GATT service discovery on the remote device with - * address |device_address|. |status| will contain BLE_STATUS_SUCCESS (0) if - * the operation was successful. - */ - void onSearchComplete(in String device_address, in int status); - - /** - * Called as a result of IBluetoothGattClient.readCharacteristic. |status| - * will contain BLE_STATUS_SUCCESS (0) on success and an ATT protocol error - * code in case of an error. |characteristic_id| refers to the characteristic - * this operation was performed on. On success, |value| will contain the - * characteristic value that was read from the remote device. This argument - * can be ignored in case of failure. - */ - void onCharacteristicRead(in int status, in GattIdentifier characteristic_id, - in byte[] value); - - /** - * Called as a result of IBluetoothGattClient.writeCharacteristic. |status| - * will contain BLE_STATUS_SUCCESS (0) on success and an ATT protocol error - * code in case of an error. |characteristic_id| refers to the characteristic - * this operation was performed on. - */ - void onCharacteristicWrite(in int status, - in GattIdentifier characteristic_id); - - /** - * Called as a result of IBluetoothGattClient.endReliableWrite. - * |device_address| refers to the remote device that the endReliableWrite - * method was called on. |status| will contain BLE_STATUS_SUCCESS (0) on - * success and an ATT error code in case of an error. - */ - void onExecuteWrite(in String device_address, in int status); - - /** - * Called as a result of IBluetoothGattClient.readDescriptor. |status| - * will contain BLE_STATUS_SUCCESS (0) on success and an ATT protocol error - * code in case of an error. |descriptor_id| refers to the descriptor this - * operation was performed on. On success, |value| will contain the - * descriptor value that was read from the remote device. This argument - * can be ignored in case of failure. - */ - void onDescriptorRead(in int status, in GattIdentifier descriptor_id, - in byte[] value); - - /** - * Called as a result of IBluetoothGattClient.writeDescriptor. |status| - * will contain BLE_STATUS_SUCCESS (0) on success and an ATT protocol error - * code in case of an error. |descriptor_id| refers to the descriptor this - * operation was performed on. - */ - void onDescriptorWrite(in int status, in GattIdentifier descriptor_id); - - /** - * Called when there is an incoming ATT Handle-Value notification or - * indication for the characteristic with identifier |characteristic_id|. - */ - void onNotify(in GattIdentifier characteristic_id, in byte[] value); -} diff --git a/system/service/doc/IBluetoothGattServer.txt b/system/service/doc/IBluetoothGattServer.txt deleted file mode 100644 index 848109aa98..0000000000 --- a/system/service/doc/IBluetoothGattServer.txt +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2015, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Binder IPC interface for interacting with Bluetooth GATT server-role - * features. - */ -interface IBluetoothGattServer { - /** - * Registers a client application with this interface. This creates a unique - * GATT server instance for the application that will contain the GATT - * services belonging to the calling application. A special interface ID will - * be returned in a callback to the application that can be used to perform - * GATT server operations. Returns false in case of an error. - */ - boolean registerServer(in IBluetoothGattServerCallback callback); - - /** - * Unregisters a previously registered server with interface ID |server_if|. - */ - void unregisterServer(in int server_if); - - /** - * Unregisters all previously registered servers. - */ - void unregisterAll(); - - /** - * Adds new GATT service. This will execute synchronously, and result in - * IBluetoothGattServerCallback.onServiceAdded. - * - * Returns true on success, false otherwise. - */ - boolean AddService(int server_id, in BluetoothGattService service); - - /** - * Sends a response to a currently pending read or write request. The request - * will be propagated to the application via IBluetoothGattServerCallback with - * a unique |request_id| which must be passed to this method along with the - * |device_address| of the device that the request originated from. - * - * The |status| field should contain the result of the operation. In the case - * of success, the application should pass in "0". Otherwise this should - * contain an ATT protocol error code. - */ - boolean sendResponse(in int server_if, in String device_address, - in int request_id, in int status, - in int offset, in byte[] value); - - /** - * Sends a handle-value notification or indication to the device with the - * given address for the characteristic with the given handle. |confirm| - * should be set to true, if a handle-value indication should be sent, which - * will remain pending until the remote device sends a handle-value - * confirmation. Returns false if a call to this method is pending. Otherwise - * reports the result asynchronously in - * IBluetoothGattServerCallback.onNotificationSent. - */ - boolean sendNotification(in int server_if, in String device_address, - in int handle, - in boolean confirm, in byte[] value); -} diff --git a/system/service/doc/IBluetoothGattServerCallback.txt b/system/service/doc/IBluetoothGattServerCallback.txt deleted file mode 100644 index e3eefbac5a..0000000000 --- a/system/service/doc/IBluetoothGattServerCallback.txt +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright 2015, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Binder IPC interface for receiving callbacks related to Bluetooth GATT - * server-role operations. - */ -oneway interface IBluetoothGattServerCallback { - /** - * Called to report the result of a call to - * IBluetoothGattServer.registerServer. |status| will be 0 (or - * BLE_STATUS_SUCCESS) if the server was successfully registered. |server_if| - * is the owning application's unique GATT server handle and can be used to - * perform further operations on the IBluetoothGattServer interface. - */ - void onServerRegistered(in int status, in int server_if); - - /** - * Called to report the result of a call to IBluetoothGattServer.AddService. - * A |status| of 0 denotes success, which means that the GATT service has - * been published and is discoverable. In this case handles of added service, - * it's characteristics and descriptors are filled. - */ - void onServiceAdded(in int status, in BluetoothGattServer service_id); - - /** - * Called when there is an incoming read request from the remote device with - * address |device_address| for the characteristic with handle |handle|. - * |offset| is the index of the characteristic value that - * the remote device wants to read from. If |is_long| is true, then this - * request is part of a Long Read procedure. An implementation should handle - * this request by calling IBluetoothGattServer.sendResponse with the given - * |request_id| and the appropriate characteristic value. - * - * If |offset| is invalid then sendResponse should be called with - * GATT_ERROR_INVALID_OFFSET. If |is_long| is true but this characteristic is - * not a long attribute (i.e. its value would fit within the current ATT MTU), - * then GATT_ERROR_ATTRIBUTE_NOT_LONG should be returned. - */ - void onCharacteristicReadRequest(in String device_address, in int request_id, - in int offset, in boolean is_long, - in int handle); - - /** - * Called when there is an incoming read request from the remote device with - * address |device_address| for the descriptor with handle |handle|. - * |offset| is the index of the descriptor value that - * the remote device wants to read from. If |is_long| is true, then this - * request is part of a Long Read procedure. An implementation should handle - * this request by calling IBluetoothGattServer.sendResponse with the given - * |request_id| and the appropriate descriptor value. - * - * If |offset| is invalid then sendResponse should be called with - * GATT_ERROR_INVALID_OFFSET. If |is_long| is true but this descriptor is - * not a long attribute (i.e. its value would fit within the current ATT MTU), - * then GATT_ERROR_ATTRIBUTE_NOT_LONG should be returned. - */ - void onDescriptorReadRequest(in String device_address, in int request_id, - in int offset, in boolean is_long, - in int handle); - - /** - * Called when there is an incoming write request from the remote device with - * address |device_address| for the characteristic with handle |handle| - * with the value |value|. An implementation should handle - * this request by calling IBluetoothGattServer.sendResponse with the given - * |request_id|. |offset| is the index of the characteristic value that the - * remote device wants to write to, so the value should be written starting at - * |offset|. If |need_response| is false, then this is a "Write Without - * Response" procedure and sendResponse should not be called. If - * |is_prepare_write| is true, then the implementation should not commit this - * write until a call to onExecuteWriteRequest is received. - * - * If |offset| is invalid, then sendResponse should be called with - * GATT_ERROR_INVALID_OFFSET. - */ - void onCharacteristicWriteRequest(in String device_address, in int request_id, - in int offset, in boolean is_prepare_write, - in boolean need_response, in byte[] value, - in int handle); - - /** - * Called when there is an incoming write request from the remote device with - * address |device_address| for the descriptor with handle |handle| - * with the value |value|. An implementation should handle - * this request by calling IBluetoothGattServer.sendResponse with the given - * |request_id|. |offset| is the index of the descriptor value that the - * remote device wants to write to, so the value should be written starting at - * |offset|. If |need_response| is false, then this is a "Write Without - * Response" procedure and sendResponse should not be called. If - * |is_prepare_write| is true, then the implementation should not commit this - * write until a call to onExecuteWriteRequest is received. - * - * If |offset| is invalid, then sendResponse should be called with - * GATT_ERROR_INVALID_OFFSET. - */ - void onDescriptorWriteRequest(in String device_address, in int request_id, - in int offset, in boolean is_prepare_write, - in boolean need_response, in byte[] value, - in int handle); - - /** - * Called when there is an incoming execute-write request to commit or abort - * previously prepared writes. If |is_execute| is true, then the - * implementation should commit all previously prepared writes. Otherwise all - * prepared writes should dropped (aborted). The application should report the - * result of the execute write by calling IBluetoothGattServer.sendResponse - * with the given |request_id|. - */ - void onExecuteWriteRequest(in String device_address, in int request_id, - in boolean is_execute); - - /** - * Reports the result of a previous call to - * IBluetoothGattServer.sendNotification. If an indication was sent, this will - * be called when the remote device sends a confirmation packet. Otherwise - * this will be called as soon as the notification packet is successfully sent - * out over the radio. - */ - void onNotificationSent(in String device_address, in int status); -} diff --git a/system/service/doc/IBluetoothLowEnergy.txt b/system/service/doc/IBluetoothLowEnergy.txt deleted file mode 100644 index ac7a6cbefd..0000000000 --- a/system/service/doc/IBluetoothLowEnergy.txt +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2015, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Binder IPC API for interacting with Bluetooth Low-Energy features. - */ -interface IBluetoothLowEnergy { - /** - * Registers a client application that can manage its own Low Energy - * instance. A special client interface ID will be returned in a callback to - * the application that can be used to perform Low Energy operations. Returns - * false in case of an error. - */ - boolean registerClient(in IBluetoothLowEnergyCallback callback); - - /** - * Unregisters a previously registered client with "client interface ID" - * |client_if|. - */ - void unregisterClient(in int client_if); - - /** - * Unregisters all previously registered clients. - */ - void unregisterAll(); - - /* Initiates a BLE connection do device with address |address|. If - * |is_direct| is set, use direct connect procedure. Return true on success, - * false otherwise. - */ - boolean Connect(in int client_id, in const char* address, - in boolean is_direct); - - /* Disconnect from previously connected BLE device with address |address|. - * Returns true on success, false otherwise. - */ - boolean Disconnect(in int client_id, in const char* address); - - /** - * Sends request to set MTU to |mtu| for the device with address |address|. - * OnMtuChanged callback will be triggered as a result of this call. Returns - * true when the command was sent, false otherwise. - */ - boolean setMtu(in int client_id, in char* address, int mtu); - - /** - * Initiates a BLE device scan for the scan client with ID |client_id|, using - * the parameters defined in |settings|. Scan results that are reported to the - * application with the associated IBluetoothLowEnergyCallback event will be - * filtered using a combination of hardware and software filtering based on - * |filters|. Return true on success, false otherwise. - */ - boolean startScan(in int client_id, in ScanSettings settings, - in ScanFilter[] filters); - - /** - * Stops a previously initiated scan session for the client with ID - * |client_id|. Return true on success, false otherwise. - */ - boolean stopScan(in int client_id); - - /** - * Starts a multi-advertising instance using |advertising_data| and - * |scan_response_data|, both of which can be empty. Each of these parameters - * must contain the raw advertising packet. Returns false if there were any - * synchronous failures, e.g. if the advertising or scan response data are - * incorrectly formatted. Otherwise, the result of the operation will be - * asynchronously reported in - * IBluetoothLowEnergyCallback.onMultiAdvertiseCallback. See the headers in - * common/bluetooth/binder for documentation on the AdvertiseData and - * AdvertiseSettings data types. - */ - boolean startMultiAdvertising(in int client_if, - in AdvertiseData advertise_data, - in AdvertiseData scan_response_data, - in AdvertiseSettings settings); - - /** - * Stops the previously started multi-advertising instance for the given - * client. Returns false in case of an error, e.g. this client has not started - * an instance. - */ - boolean stopMultiAdvertising(in int client_if); -} diff --git a/system/service/doc/IBluetoothLowEnergyCallback.txt b/system/service/doc/IBluetoothLowEnergyCallback.txt deleted file mode 100644 index 7867379ca3..0000000000 --- a/system/service/doc/IBluetoothLowEnergyCallback.txt +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2015, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Binder IPC interface for receiving callbacks related to Bluetooth Low Energy - * operations. - */ -oneway interface IBluetoothLowEnergyCallback { - /** - * Called to report the result of a call to - * IBluetoothLowEnergy.registerClient. |status| will be BLE_STATUS_SUCCESS (0) - * if the client was successfully registered. |client_if| is the owning - * application's unique Low Energy client handle and can be used - * to perform further operations on the IBluetoothLowEnergy interface. - */ - void onClientRegistered(in int status, in int client_if); - - /* Called asynchronously to notify the delegate of connection state change. - */ - void OnConnectionState(in int status, in int client_id, in const char* address, - in bool connected); - - /* Called to report current MTU value. Can be a result of calling - * IBluetoothLowEnergy.setMtu or remote device trying to change MTU. - */ - void OnMtuChanged(in int status, in const char* address, in int mtu); - - /** - * Called to report BLE device scan results once a scan session is started for - * this client using IBluetoothLowEnergy.startScan. |scan_result| contains all - * the data related to the discovered BLE device. - */ - void onScanResult(in ScanResult scan_result); - - /** - * Called to report the result of a call to - * IBluetoothLowEnergy.startMultiAdvertising or stopMultiAdvertising. - */ - void onMultiAdvertiseCallback(in int status, in boolean is_start, - in AdvertiseSettings settings); -} diff --git a/system/service/example/heart_rate/constants.h b/system/service/example/heart_rate/constants.h deleted file mode 100644 index 884d5edc41..0000000000 --- a/system/service/example/heart_rate/constants.h +++ /dev/null @@ -1,46 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <bluetooth/uuid.h> - -// This header defines constants specific to the GATT Heart Rate Service. - -namespace heart_rate { - -// HR Measurement characteristic value flags -const uint8_t kHRValueFormat8Bit = (0 << 0); -const uint8_t kHRValueFormat16Bit = (1 << 0); -const uint16_t kHRSensorContactDetected = (3 << 1); -const uint8_t kHREnergyExpendedPresent = (1 << 3); - -const bluetooth::Uuid kCCCDescriptorUuid = bluetooth::Uuid::FromString("2902"); -const bluetooth::Uuid kHRServiceUuid = bluetooth::Uuid::FromString("180D"); -const bluetooth::Uuid kHRMeasurementUuid = bluetooth::Uuid::FromString("2A37"); -const bluetooth::Uuid kBodySensorLocationUuid = - bluetooth::Uuid::FromString("2A38"); -const bluetooth::Uuid kHRControlPointUuid = bluetooth::Uuid::FromString("2A39"); - -const uint8_t kHRBodyLocationOther = 0; -const uint8_t kHRBodyLocationChest = 1; -const uint8_t kHRBodyLocationWrist = 2; -const uint8_t kHRBodyLocationFinger = 3; -const uint8_t kHRBodyLocationHand = 4; -const uint8_t kHRBodyLocationEarLobe = 5; -const uint8_t kHRBodyLocationFoot = 6; - -} // namespace heart_rate diff --git a/system/service/example/heart_rate/heart_rate_server.cc b/system/service/example/heart_rate/heart_rate_server.cc deleted file mode 100644 index 2a53ba4d63..0000000000 --- a/system/service/example/heart_rate/heart_rate_server.cc +++ /dev/null @@ -1,501 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include <base/functional/bind.h> -#include <base/location.h> -#include <base/logging.h> -#include <base/rand_util.h> - -#include <android/bluetooth/BnBluetoothLeAdvertiserCallback.h> -#include <android/bluetooth/IBluetoothLeAdvertiser.h> -#include <bluetooth/low_energy_constants.h> - -#include "constants.h" -#include "heart_rate_server.h" - -using android::binder::Status; -using android::String8; -using android::String16; - -using android::bluetooth::IBluetoothLeAdvertiser; -using android::bluetooth::BluetoothGattService; - -namespace heart_rate { - -class CLIBluetoothLeAdvertiserCallback - : public android::bluetooth::BnBluetoothLeAdvertiserCallback { - public: - explicit CLIBluetoothLeAdvertiserCallback( - android::sp<android::bluetooth::IBluetooth> bt) - : bt_(bt) {} - - CLIBluetoothLeAdvertiserCallback(const CLIBluetoothLeAdvertiserCallback&) = - delete; - CLIBluetoothLeAdvertiserCallback& operator=( - const CLIBluetoothLeAdvertiserCallback&) = delete; - - // IBluetoothLeAdvertiserCallback overrides: - Status OnAdvertiserRegistered(int status, int advertiser_id) { - if (status != bluetooth::BLE_STATUS_SUCCESS) { - LOG(ERROR) - << "Failed to register BLE advertiser, will not start advertising"; - return Status::ok(); - } - - LOG(INFO) << "Registered BLE advertiser with ID: " << advertiser_id; - - String16 name_param; - bt_->GetName(&name_param); - std::string name(String8(name_param).string()); - - /* Advertising data: 16-bit Service Uuid: Heart Rate Service, Tx power*/ - std::vector<uint8_t> data{0x03, bluetooth::kEIRTypeComplete16BitUuids, - 0x0D, 0x18, - 0x02, bluetooth::kEIRTypeTxPower, - 0x00}; - data.push_back(name.length() + 1); - data.push_back(bluetooth::kEIRTypeCompleteLocalName); - data.insert(data.end(), name.c_str(), name.c_str() + name.length()); - - base::TimeDelta timeout; - - bluetooth::AdvertiseSettings settings( - bluetooth::AdvertiseSettings::MODE_LOW_POWER, timeout, - bluetooth::AdvertiseSettings::TX_POWER_LEVEL_MEDIUM, true); - - bluetooth::AdvertiseData adv_data(data); - bluetooth::AdvertiseData scan_rsp; - - android::sp<IBluetoothLeAdvertiser> ble; - bt_->GetLeAdvertiserInterface(&ble); - bool start_status; - ble->StartMultiAdvertising(advertiser_id, adv_data, scan_rsp, settings, - &start_status); - return Status::ok(); - } - - Status OnMultiAdvertiseCallback( - int status, bool is_start, - const android::bluetooth::AdvertiseSettings& /* settings */) { - LOG(INFO) << "Advertising" << (is_start ? " started" : " stopped"); - return Status::ok(); - }; - - private: - android::sp<android::bluetooth::IBluetooth> bt_; -}; - -HeartRateServer::HeartRateServer( - android::sp<android::bluetooth::IBluetooth> bluetooth, - scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, - bool advertise) - : simulation_started_(false), - bluetooth_(bluetooth), - server_if_(-1), - hr_notification_count_(0), - energy_expended_(0), - advertise_(advertise), - main_task_runner_(main_task_runner), - weak_ptr_factory_(this) { - CHECK(bluetooth_.get()); -} - -HeartRateServer::~HeartRateServer() { - std::lock_guard<std::mutex> lock(mutex_); - if (!gatt_.get() || server_if_ == -1) return; - - if (!android::IInterface::asBinder(gatt_.get())->isBinderAlive()) return; - - // Manually unregister ourselves from the daemon. It's good practice to do - // this, even though the daemon will automatically unregister us if this - // process exits. - gatt_->UnregisterServer(server_if_); -} - -bool HeartRateServer::Run(const RunCallback& callback) { - std::lock_guard<std::mutex> lock(mutex_); - - if (pending_run_cb_) { - LOG(ERROR) << "Already started"; - return false; - } - - // Grab the IBluetoothGattServer binder from the Bluetooth daemon. - bluetooth_->GetGattServerInterface(&gatt_); - if (!gatt_.get()) { - LOG(ERROR) << "Failed to obtain handle to IBluetoothGattServer interface"; - return false; - } - - // Register this instance as a GATT server. If this call succeeds, we will - // asynchronously receive a server ID via the OnServerRegistered callback. - bool status; - gatt_->RegisterServer(this, &status); - if (!status) { - LOG(ERROR) << "Failed to register with the server interface"; - return false; - } - - pending_run_cb_ = callback; - - return true; -} - -void HeartRateServer::ScheduleNextMeasurement() { - main_task_runner_->PostDelayedTask( - FROM_HERE, base::Bind(&HeartRateServer::SendHeartRateMeasurement, - weak_ptr_factory_.GetWeakPtr()), -#if BASE_VER < 931007 - base::TimeDelta::FromSeconds(1)); -#else - base::Seconds(1)); -#endif -} - -void HeartRateServer::SendHeartRateMeasurement() { - std::lock_guard<std::mutex> lock(mutex_); - - // Send a notification or indication to all enabled devices. - bool found = false; - for (const auto& iter : device_ccc_map_) { - uint8_t ccc_val = iter.second; - - if (!ccc_val) continue; - - found = true; - - // Don't send a notification if one is already pending for this device. - if (pending_notification_map_[iter.first]) continue; - - std::vector<uint8_t> value; - BuildHeartRateMeasurementValue(&value); - - bool status; - gatt_->SendNotification(server_if_, String16(String8(iter.first.c_str())), - hr_measurement_handle_, false, value, &status); - if (status) pending_notification_map_[iter.first] = true; - } - - // Still enabled! - if (found) { - ScheduleNextMeasurement(); - return; - } - - // All clients disabled notifications. - simulation_started_ = false; - - // TODO(armansito): We should keep track of closed connections here so that we - // don't send notifications to uninterested clients. -} - -void HeartRateServer::BuildHeartRateMeasurementValue( - std::vector<uint8_t>* out_value) { - CHECK(out_value); // Assert that |out_value| is not nullptr. - - // Default flags field. Here is what we put in there: - // Bit 0: 0 - 8-bit Heart Rate value - // Bits 1 & 2: 11 - Sensor contact feature supported and contact detected. - uint8_t flags = kHRValueFormat8Bit | kHRSensorContactDetected; - - // Our demo's heart rate. Pick a value between 90 and 130. - uint8_t heart_rate = base::RandInt(90, 130); - - // On every tenth beat we include the Energy Expended value. - bool include_ee = false; - if (!(hr_notification_count_ % 10)) { - include_ee = true; - flags |= kHREnergyExpendedPresent; - } - - hr_notification_count_++; - energy_expended_ = std::min(UINT16_MAX, (int)energy_expended_ + 1); - - // Add all the value bytes. - out_value->push_back(flags); - out_value->push_back(heart_rate); - if (include_ee) { - out_value->push_back(energy_expended_); - out_value->push_back(energy_expended_ >> 8); - } -} - -Status HeartRateServer::OnServerRegistered(int status, int server_if) { - std::lock_guard<std::mutex> lock(mutex_); - - if (status != bluetooth::BLE_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to register GATT server"; - pending_run_cb_(false); - return Status::ok(); - } - - // Registration succeeded. Store our ID, as we need it for GATT server - // operations. - server_if_ = server_if; - - LOG(INFO) << "Heart Rate server registered - server_if: " << server_if_; - - bluetooth::Service hrService(0, true, kHRServiceUuid, - {{0, - kHRMeasurementUuid, - bluetooth::kCharacteristicPropertyNotify, - 0, - {{0, kCCCDescriptorUuid, - (bluetooth::kAttributePermissionRead | - bluetooth::kAttributePermissionWrite)}}}, - {0, - kBodySensorLocationUuid, - bluetooth::kCharacteristicPropertyRead, - bluetooth::kAttributePermissionRead, - {}}, - {0, - kHRControlPointUuid, - bluetooth::kCharacteristicPropertyWrite, - bluetooth::kAttributePermissionWrite, - {}}}, - {}); - - bool op_status = true; - - Status stat = gatt_->AddService(server_if_, (BluetoothGattService)hrService, - &op_status); - if (!stat.isOk()) { - LOG(ERROR) << "Failed to add service, status is: " /*<< stat*/; - pending_run_cb_(false); - return Status::ok(); - } - - if (!op_status) { - LOG(ERROR) << "Failed to add service"; - pending_run_cb_(false); - return Status::ok(); - } - - LOG(INFO) << "Initiated AddService request"; - return Status::ok(); -} - -Status HeartRateServer::OnServiceAdded( - int status, const android::bluetooth::BluetoothGattService& service) { - std::lock_guard<std::mutex> lock(mutex_); - - if (status != bluetooth::BLE_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to add Heart Rate service"; - pending_run_cb_(false); - return Status::ok(); - } - - hr_service_handle_ = service.handle(); - hr_measurement_handle_ = service.characteristics()[0].handle(); - hr_measurement_cccd_handle_ = - service.characteristics()[0].descriptors()[0].handle(); - body_sensor_loc_handle_ = service.characteristics()[1].handle(); - hr_control_point_handle_ = service.characteristics()[2].handle(); - - LOG(INFO) << "Heart Rate service added"; - pending_run_cb_(true); - - if (advertise_) { - android::sp<IBluetoothLeAdvertiser> ble; - bluetooth_->GetLeAdvertiserInterface(&ble); - bool status; - ble->RegisterAdvertiser(new CLIBluetoothLeAdvertiserCallback(bluetooth_), - &status); - } - - return Status::ok(); -} - -Status HeartRateServer::OnCharacteristicReadRequest( - const String16& device_address, int request_id, int offset, - bool /* is_long */, int handle) { - std::lock_guard<std::mutex> lock(mutex_); - - // This is where we handle an incoming characteristic read. Only the body - // sensor location characteristic is readable. - CHECK(handle == body_sensor_loc_handle_); - - std::vector<uint8_t> value; - bluetooth::GATTError error = bluetooth::GATT_ERROR_NONE; - if (offset > 1) - error = bluetooth::GATT_ERROR_INVALID_OFFSET; - else if (offset == 0) - value.push_back(kHRBodyLocationFoot); - - bool status; - gatt_->SendResponse(server_if_, device_address, request_id, error, offset, - value, &status); - return Status::ok(); -} - -Status HeartRateServer::OnDescriptorReadRequest(const String16& device_address, - int request_id, int offset, - bool /* is_long */, - int handle) { - std::lock_guard<std::mutex> lock(mutex_); - - // This is where we handle an incoming characteristic descriptor read. There - // is only one descriptor. - if (handle != hr_measurement_cccd_handle_) { - std::vector<uint8_t> value; - bool status; - gatt_->SendResponse(server_if_, device_address, request_id, - bluetooth::GATT_ERROR_ATTRIBUTE_NOT_FOUND, offset, - value, &status); - return Status::ok(); - } - - // 16-bit value encoded as little-endian. - const uint8_t value_bytes[] = { - device_ccc_map_[std::string(String8(device_address).string())], 0x00}; - - std::vector<uint8_t> value; - bluetooth::GATTError error = bluetooth::GATT_ERROR_NONE; - if (offset > 2) - error = bluetooth::GATT_ERROR_INVALID_OFFSET; - else - value.insert(value.begin(), value_bytes + offset, value_bytes + 2 - offset); - - bool status; - gatt_->SendResponse(server_if_, device_address, request_id, error, offset, - value, &status); - return Status::ok(); -} - -Status HeartRateServer::OnCharacteristicWriteRequest( - const String16& device_address, int request_id, int offset, - bool is_prepare_write, bool need_response, - const std::vector<uint8_t>& value, int handle) { - std::lock_guard<std::mutex> lock(mutex_); - - std::vector<uint8_t> dummy; - - // This is where we handle an incoming characteristic write. The Heart Rate - // service doesn't really support prepared writes, so we just reject them to - // keep things simple. - if (is_prepare_write) { - bool status; - gatt_->SendResponse(server_if_, device_address, request_id, - bluetooth::GATT_ERROR_REQUEST_NOT_SUPPORTED, offset, - dummy, &status); - return Status::ok(); - } - - // Heart Rate Control point is the only writable characteristic. - CHECK(handle == hr_control_point_handle_); - - // Writes to the Heart Rate Control Point characteristic must contain a single - // byte with the value 0x01. - if (value.size() != 1 || value[0] != 0x01) { - bool status; - gatt_->SendResponse(server_if_, device_address, request_id, - bluetooth::GATT_ERROR_OUT_OF_RANGE, offset, dummy, - &status); - return Status::ok(); - } - - LOG(INFO) << "Heart Rate Control Point written; Enery Expended reset!"; - energy_expended_ = 0; - - if (!need_response) return Status::ok(); - - bool status; - gatt_->SendResponse(server_if_, device_address, request_id, - bluetooth::GATT_ERROR_NONE, offset, dummy, &status); - return Status::ok(); -} - -Status HeartRateServer::OnDescriptorWriteRequest( - const String16& device_address, int request_id, int offset, - bool is_prepare_write, bool need_response, - const std::vector<uint8_t>& value, int handle) { - std::lock_guard<std::mutex> lock(mutex_); - - std::vector<uint8_t> dummy; - - // This is where we handle an incoming characteristic write. The Heart Rate - // service doesn't really support prepared writes, so we just reject them to - // keep things simple. - if (is_prepare_write) { - bool status; - gatt_->SendResponse(server_if_, device_address, request_id, - bluetooth::GATT_ERROR_REQUEST_NOT_SUPPORTED, offset, - dummy, &status); - return Status::ok(); - } - - // CCC is the only descriptor we have. - CHECK(handle == hr_measurement_cccd_handle_); - - // CCC must contain 2 bytes for a 16-bit value in little-endian. The only - // allowed values here are 0x0000 and 0x0001. - if (value.size() != 2 || value[1] != 0x00 || value[0] > 0x01) { - bool status; - gatt_->SendResponse(server_if_, device_address, request_id, - bluetooth::GATT_ERROR_CCCD_IMPROPERLY_CONFIGURED, - offset, dummy, &status); - return Status::ok(); - } - - device_ccc_map_[std::string(String8(device_address).string())] = value[0]; - - LOG(INFO) << "Heart Rate Measurement CCC written - device: " << device_address - << " value: " << (int)value[0]; - - // Start the simulation. - if (!simulation_started_ && value[0]) { - simulation_started_ = true; - ScheduleNextMeasurement(); - } - - if (!need_response) return Status::ok(); - - bool status; - gatt_->SendResponse(server_if_, device_address, request_id, - bluetooth::GATT_ERROR_NONE, offset, dummy, &status); - return Status::ok(); -} - -Status HeartRateServer::OnExecuteWriteRequest(const String16& device_address, - int request_id, - bool /* is_execute */) { - // We don't support Prepared Writes so, simply return Not Supported error. - std::vector<uint8_t> dummy; - bool status; - gatt_->SendResponse(server_if_, device_address, request_id, - bluetooth::GATT_ERROR_REQUEST_NOT_SUPPORTED, 0, dummy, - &status); - - return Status::ok(); -} - -Status HeartRateServer::OnNotificationSent(const String16& device_address, - int status) { - LOG(INFO) << "Notification was sent - device: " << device_address - << " status: " << status; - std::lock_guard<std::mutex> lock(mutex_); - pending_notification_map_[std::string(String8(device_address).string())] = - false; - - return Status::ok(); -} - -Status HeartRateServer::OnConnectionStateChanged(const String16& device_address, - bool connected) { - LOG(INFO) << "Connection state changed - device: " << device_address - << " connected: " << (connected ? "true" : "false"); - return Status::ok(); -} -} // namespace heart_rate diff --git a/system/service/example/heart_rate/heart_rate_server.h b/system/service/example/heart_rate/heart_rate_server.h deleted file mode 100644 index 1b716fd193..0000000000 --- a/system/service/example/heart_rate/heart_rate_server.h +++ /dev/null @@ -1,148 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <mutex> -#include <unordered_map> - -#include <base/memory/ref_counted.h> -#include <base/memory/weak_ptr.h> -#if BASE_VER < 930627 -#include <base/single_thread_task_runner.h> -#else -#include <base/task/single_thread_task_runner.h> -#endif - -#include <android/bluetooth/BnBluetoothGattServerCallback.h> -#include <android/bluetooth/IBluetooth.h> - -using android::binder::Status; -using android::String16; - -namespace heart_rate { - -// Implements an example GATT Heart Rate service. This class emulates the -// behavior of a heart rate service by sending fake heart-rate pulses. -class HeartRateServer - : public android::bluetooth::BnBluetoothGattServerCallback { - public: - HeartRateServer(android::sp<android::bluetooth::IBluetooth> bluetooth, - scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, - bool advertise); - HeartRateServer(const HeartRateServer&) = delete; - HeartRateServer& operator=(const HeartRateServer&) = delete; - - ~HeartRateServer() override; - - // Set up the server and register the GATT services with the stack. This - // initiates a set of asynchronous procedures. Invokes |callback| - // asynchronously with the result of the operation. - using RunCallback = std::function<void(bool success)>; - bool Run(const RunCallback& callback); - - private: - // Helpers for posting heart rate measurement notifications. - void ScheduleNextMeasurement(); - void SendHeartRateMeasurement(); - void BuildHeartRateMeasurementValue(std::vector<uint8_t>* out_value); - - // ipc::binder::IBluetoothGattServerCallback override: - Status OnServerRegistered(int status, int server_id) override; - Status OnServiceAdded( - int status, - const android::bluetooth::BluetoothGattService& service) override; - Status OnCharacteristicReadRequest(const String16& device_address, - int request_id, int offset, bool is_long, - int handle) override; - Status OnDescriptorReadRequest(const String16& device_address, int request_id, - int offset, bool is_long, int handle) override; - Status OnCharacteristicWriteRequest(const String16& device_address, - int request_id, int offset, - bool is_prepare_write, bool need_response, - const std::vector<uint8_t>& value, - int handle) override; - Status OnDescriptorWriteRequest(const String16& device_address, - int request_id, int offset, - bool is_prepare_write, bool need_response, - const std::vector<uint8_t>& value, - int handle) override; - Status OnExecuteWriteRequest(const String16& device_address, int request_id, - bool is_execute) override; - Status OnNotificationSent(const String16& device_address, - int status) override; - Status OnConnectionStateChanged(const String16& device_address, - bool connected) override; - - // Single mutex to protect all variables below. - std::mutex mutex_; - - // This stores whether or not at least one remote device has written to the - // CCC descriptor. - bool simulation_started_; - - // The IBluetooth and IBluetoothGattServer binders that we use to communicate - // with the Bluetooth daemon's GATT server features. - android::sp<android::bluetooth::IBluetooth> bluetooth_; - android::sp<android::bluetooth::IBluetoothGattServer> gatt_; - - // ID assigned to us by the daemon to operate on our dedicated GATT server - // instance. - int server_if_; - - // Callback passed to Run(). We use this to tell main that all attributes have - // been registered with the daemon. - RunCallback pending_run_cb_; - - // Stores whether or not an outgoing notification is still pending. We use - // this to throttle notifications so that we don't accidentally congest the - // connection. - std::unordered_map<std::string, bool> pending_notification_map_; - - // The current HR notification count. - int hr_notification_count_; - - // The Energy Expended value we use in our notifications. - uint16_t energy_expended_; - - // Handles that refer to Heart Rate Service GATT objects. - // These returned to us from the Bluetooth daemon as we populate the database. - uint16_t hr_service_handle_; - uint16_t hr_measurement_handle_; - uint16_t hr_measurement_cccd_handle_; - uint16_t body_sensor_loc_handle_; - uint16_t hr_control_point_handle_; - - // The daemon itself doesn't maintain a Client Characteristic Configuration - // mapping, so we do it ourselves here. - std::unordered_map<std::string, uint8_t> device_ccc_map_; - - // Wether we should also start advertising - bool advertise_; - - // libchrome task runner that we use to post heart rate measurement - // notifications on the main thread. - scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_; - - // We use this to pass weak_ptr's to base::Bind, which won't execute if the - // HeartRateServer object gets deleted. This is a convenience utility from - // libchrome and we use it here since base::TaskRunner uses base::Callback. - // Note: This should remain the last member so that it'll be destroyed and - // invalidate its weak pointers before any other members are destroyed. - base::WeakPtrFactory<HeartRateServer> weak_ptr_factory_; -}; - -} // namespace heart_rate diff --git a/system/service/example/heart_rate/server_main.cc b/system/service/example/heart_rate/server_main.cc deleted file mode 100644 index f7a434e666..0000000000 --- a/system/service/example/heart_rate/server_main.cc +++ /dev/null @@ -1,157 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include <base/at_exit.h> -#include <base/command_line.h> -#include <base/functional/bind.h> -#include <base/location.h> -#include <base/logging.h> -#include <base/run_loop.h> - -#include <binder/IPCThreadState.h> -#include <binder/IServiceManager.h> -#include <binder/ProcessState.h> - -#include <android/bluetooth/IBluetooth.h> - -#include "abstract_message_loop.h" -#include "heart_rate_server.h" - -using android::sp; -using android::OK; -using android::bluetooth::IBluetooth; - -using android::getService; - -namespace { - -std::string kServiceName = "bluetooth-service"; - -void QuitMessageLoop() { - base::RunLoop().Quit(); -} - -// Handles the case where the Bluetooth process dies. -class BluetoothDeathRecipient : public android::IBinder::DeathRecipient { - public: - explicit BluetoothDeathRecipient( - scoped_refptr<base::SingleThreadTaskRunner> main_task_runner) - : main_task_runner_(main_task_runner) {} - - ~BluetoothDeathRecipient() override = default; - - // android::IBinder::DeathRecipient override: - void binderDied(const android::wp<android::IBinder>& /* who */) override { - LOG(ERROR) << "The Bluetooth daemon has died. Aborting."; - - // binderDied executes on a dedicated thread. We need to stop the main loop - // on the main thread so we post a message to it here. The main loop only - // runs on the main thread. - main_task_runner_->PostTask(FROM_HERE, base::Bind(&QuitMessageLoop)); - - android::IPCThreadState::self()->stopProcess(); - } - - private: - scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_; -}; - -} // namespace - -int main(int argc, char* argv[]) { - base::AtExitManager exit_manager; - base::CommandLine::Init(argc, argv); - logging::LoggingSettings log_settings; - - // Initialize global logging based on command-line parameters (this is a - // libchrome pattern). - if (!logging::InitLogging(log_settings)) { - LOG(ERROR) << "Failed to set up logging"; - return EXIT_FAILURE; - } - - // Set up a message loop so that we can schedule timed Heart Rate - // notifications. - btbase::AbstractMessageLoop main_loop; - - LOG(INFO) << "Starting GATT Heart Rate Service sample"; - - sp<IBluetooth> bluetooth; - status_t status = getService(String16(kServiceName.c_str()), &bluetooth); - if (status != OK) { - LOG(ERROR) << "Failed to get service binder: '" << kServiceName - << "' status=" << status; - return EXIT_FAILURE; - } - - // Bluetooth needs to be enabled for our demo to work. - bool enabled; - bluetooth->IsEnabled(&enabled); - if (!enabled) { - LOG(ERROR) << "Bluetooth is not enabled."; - return EXIT_FAILURE; - } - - // Register for death notifications on the IBluetooth binder. This let's us - // handle the case where the Bluetooth daemon process (bluetoothtbd) dies - // outside of our control. - sp<BluetoothDeathRecipient> dr( - new BluetoothDeathRecipient(main_loop.task_runner())); - if (android::IInterface::asBinder(bluetooth.get())->linkToDeath(dr) != - android::NO_ERROR) { - LOG(ERROR) << "Failed to register DeathRecipient for IBluetooth"; - return EXIT_FAILURE; - } - - // Initialize the Binder process thread pool. We have to set this up, - // otherwise, incoming callbacks from the Bluetooth daemon would block the - // main thread (in other words, we have to do this as we are a "Binder - // server"). - android::ProcessState::self()->startThreadPool(); - - // heart_rate::HeartRateServer notifies success or failure asynchronously - // using a closure, so we set up a lambda for that here. - auto callback = [&](bool success) { - if (success) { - LOG(INFO) << "Heart Rate service started successfully"; - return; - } - - LOG(ERROR) << "Starting Heart Rate server failed asynchronously"; - base::RunLoop().QuitWhenIdle(); - }; - - bool advertise = - base::CommandLine::ForCurrentProcess()->HasSwitch("advertise"); - - // Create the Heart Rate server. - std::unique_ptr<heart_rate::HeartRateServer> hr( - new heart_rate::HeartRateServer(bluetooth, main_loop.task_runner(), - advertise)); - if (!hr->Run(callback)) { - LOG(ERROR) << "Failed to start Heart Rate server"; - return EXIT_FAILURE; - } - - // Run the main loop on the main process thread. Binder callbacks will be - // received in dedicated threads set up by the ProcessState::startThreadPool - // call above but we use this main loop for sending out heart rate - // notifications. - base::RunLoop().Run(); - - LOG(INFO) << "Exiting"; - return EXIT_SUCCESS; -} diff --git a/system/service/gatt_client.cc b/system/service/gatt_client.cc deleted file mode 100644 index e091948a58..0000000000 --- a/system/service/gatt_client.cc +++ /dev/null @@ -1,100 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/gatt_client.h" - -#include <base/logging.h> - -using std::lock_guard; -using std::mutex; - -namespace bluetooth { - -// GattClient implementation - -GattClient::GattClient(const Uuid& uuid, int client_id) - : app_identifier_(uuid), client_id_(client_id) {} - -GattClient::~GattClient() { - // Automatically unregister the client. - VLOG(1) << "GattClient unregistering client: " << client_id_; - - hal::BluetoothGattInterface::Get() - ->GetClientHALInterface() - ->unregister_client(client_id_); -} - -const Uuid& GattClient::GetAppIdentifier() const { return app_identifier_; } - -int GattClient::GetInstanceId() const { return client_id_; } - -// GattClientFactory implementation - -GattClientFactory::GattClientFactory() { - hal::BluetoothGattInterface::Get()->AddClientObserver(this); -} - -GattClientFactory::~GattClientFactory() { - hal::BluetoothGattInterface::Get()->RemoveClientObserver(this); -} - -bool GattClientFactory::RegisterInstance(const Uuid& uuid, - const RegisterCallback& callback) { - VLOG(1) << __func__ << " - Uuid: " << uuid.ToString(); - lock_guard<mutex> lock(pending_calls_lock_); - - if (pending_calls_.find(uuid) != pending_calls_.end()) { - LOG(ERROR) << "GATT client with given Uuid already registered - " - << "Uuid: " << uuid.ToString(); - return false; - } - - const btgatt_client_interface_t* hal_iface = - hal::BluetoothGattInterface::Get()->GetClientHALInterface(); - - if (hal_iface->register_client(uuid, false) != BT_STATUS_SUCCESS) - return false; - - pending_calls_[uuid] = callback; - - return true; -} - -void GattClientFactory::RegisterClientCallback( - hal::BluetoothGattInterface* /* gatt_iface */, int status, int client_id, - const Uuid& app_uuid) { - Uuid uuid(app_uuid); - - auto iter = pending_calls_.find(uuid); - if (iter == pending_calls_.end()) { - VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString(); - return; - } - - bool success = (status == BT_STATUS_SUCCESS); - BLEStatus result = success ? BLE_STATUS_SUCCESS : BLE_STATUS_FAILURE; - - // No need to construct a client if the call wasn't successful. - std::unique_ptr<GattClient> client; - if (success) client.reset(new GattClient(uuid, client_id)); - - // Notify the result via the result callback. - iter->second(result, uuid, std::move(client)); - - pending_calls_.erase(iter); -} - -} // namespace bluetooth diff --git a/system/service/gatt_client.h b/system/service/gatt_client.h deleted file mode 100644 index 4ed1143e4e..0000000000 --- a/system/service/gatt_client.h +++ /dev/null @@ -1,84 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <mutex> -#include <unordered_map> - -#include <bluetooth/uuid.h> - -#include "service/bluetooth_instance.h" -#include "service/hal/bluetooth_gatt_interface.h" - -namespace bluetooth { - -// A GattClient instance represents an application's handle to perform GATT -// client-role operations. Instances cannot be created directly and should be -// obtained through the factory. -class GattClient : public BluetoothInstance { - public: - GattClient(const GattClient&) = delete; - GattClient& operator=(const GattClient&) = delete; - - ~GattClient() override; - - // BluetoothClientInstace overrides: - const Uuid& GetAppIdentifier() const override; - int GetInstanceId() const override; - - private: - friend class GattClientFactory; - - // Constructor shouldn't be called directly as instances are meant to be - // obtained from the factory. - GattClient(const Uuid& uuid, int client_id); - - // See getters above for documentation. - Uuid app_identifier_; - int client_id_; -}; - -// GattClientFactory is used to register and obtain a per-application GattClient -// instance. Users should call RegisterClient to obtain their own unique -// GattClient instance that has been registered with the Bluetooth stack. -class GattClientFactory : public BluetoothInstanceFactory, - private hal::BluetoothGattInterface::ClientObserver { - public: - // Don't construct/destruct directly except in tests. Instead, obtain a handle - // from an Adapter instance. - GattClientFactory(); - GattClientFactory(const GattClientFactory&) = delete; - GattClientFactory& operator=(const GattClientFactory&) = delete; - - ~GattClientFactory() override; - - // BluetoothInstanceFactory override: - bool RegisterInstance(const Uuid& uuid, - const RegisterCallback& callback) override; - - private: - // hal::BluetoothGattInterface::ClientObserver override: - void RegisterClientCallback(hal::BluetoothGattInterface* gatt_iface, - int status, int client_id, - const Uuid& app_uuid) override; - - // Map of pending calls to register. - std::mutex pending_calls_lock_; - std::unordered_map<Uuid, RegisterCallback> pending_calls_; -}; - -} // namespace bluetooth diff --git a/system/service/gatt_server.cc b/system/service/gatt_server.cc deleted file mode 100644 index 5167fc17cf..0000000000 --- a/system/service/gatt_server.cc +++ /dev/null @@ -1,632 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/gatt_server.h" - -#include <base/logging.h> - -#include "service/logging_helpers.h" -#include "stack/include/bt_types.h" -#include "types/raw_address.h" - -using std::lock_guard; -using std::mutex; - -namespace bluetooth { - -// GattServer implementation - -GattServer::GattServer(const Uuid& uuid, int server_id) - : app_identifier_(uuid), server_id_(server_id), delegate_(nullptr) {} - -GattServer::~GattServer() { - // Automatically unregister the server. - VLOG(1) << "GattServer unregistering: " << server_id_; - - // Unregister as observer so we no longer receive any callbacks. - hal::BluetoothGattInterface::Get()->RemoveServerObserver(this); - - // Unregister this server, stop all services, and ignore the result. - // TODO(armansito): stop and remove all services here? unregister_server - // should really take care of that. - hal::BluetoothGattInterface::Get() - ->GetServerHALInterface() - ->unregister_server(server_id_); -} - -void GattServer::SetDelegate(Delegate* delegate) { - lock_guard<mutex> lock(mutex_); - delegate_ = delegate; -} - -const Uuid& GattServer::GetAppIdentifier() const { return app_identifier_; } - -int GattServer::GetInstanceId() const { return server_id_; } - -bool GattServer::AddService(const bluetooth::Service& service, - const ResultCallback& callback) { - VLOG(1) << __func__ << " server_id: " << server_id_; - lock_guard<mutex> lock(mutex_); - - if (!callback) { - LOG(ERROR) << "|callback| cannot be NULL"; - return false; - } - - std::vector<btgatt_db_element_t> svc; - - svc.push_back({ - .uuid = service.uuid(), - .type = (service.primary() ? BTGATT_DB_PRIMARY_SERVICE - : BTGATT_DB_SECONDARY_SERVICE), - }); - - for (const auto& characteristic : service.characteristics()) { - svc.push_back({.uuid = characteristic.uuid(), - .type = BTGATT_DB_CHARACTERISTIC, - .properties = characteristic.properties(), - .permissions = characteristic.permissions()}); - for (const auto& descriptor : characteristic.descriptors()) - svc.push_back({.uuid = descriptor.uuid(), - .type = BTGATT_DB_DESCRIPTOR, - .permissions = descriptor.permissions()}); - } - - for (const auto& incl_svc : service.included_services()) - svc.push_back({.type = BTGATT_DB_INCLUDED_SERVICE, - .attribute_handle = incl_svc.handle()}); - - pending_end_decl_cb_ = callback; - - bt_status_t status = - hal::BluetoothGattInterface::Get()->GetServerHALInterface()->add_service( - server_id_, svc.data(), svc.size()); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to initiate call to populate GATT service"; - CleanUpPendingData(); - return false; - } - - return true; -} - -bool GattServer::SendResponse(const std::string& device_address, int request_id, - GATTError error, int offset, - const std::vector<uint8_t>& value) { - VLOG(1) << __func__ << " - server_id: " << server_id_ - << " device_address: " << device_address - << " request_id: " << request_id << " error: " << error - << " offset: " << offset; - lock_guard<mutex> lock(mutex_); - - RawAddress addr; - if (!RawAddress::FromString(device_address, addr)) { - LOG(ERROR) << "Invalid device address given: " << device_address; - return false; - } - - if (offset < 0) { - LOG(ERROR) << "Offset is less than 0 offset: " << offset; - return false; - } - - if (value.size() + offset > BTGATT_MAX_ATTR_LEN) { - LOG(ERROR) << "Value is too large"; - return false; - } - - // Find the correct connection ID for |device_address| and |request_id|. - auto iter = conn_addr_map_.find(device_address); - if (iter == conn_addr_map_.end()) { - LOG(ERROR) << "No known connections for device address: " << device_address; - return false; - } - - std::shared_ptr<Connection> connection; - for (const auto& tmp : iter->second) { - if (tmp->request_id_to_handle.find(request_id) == - tmp->request_id_to_handle.end()) - continue; - - connection = tmp; - } - - if (!connection) { - LOG(ERROR) << "Pending request with ID " << request_id - << " not found for device with BD_ADDR: " << device_address; - return false; - } - - btgatt_response_t response; - memset(&response, 0, sizeof(response)); - - // We keep -1 as the handle for "Execute Write Request". In that case, - // there is no need to populate the response data. Just send zeros back. - int handle = connection->request_id_to_handle[request_id]; - response.handle = handle; - response.attr_value.handle = handle; - if (handle != -1) { - memcpy(response.attr_value.value, value.data(), value.size()); - response.attr_value.offset = offset; - response.attr_value.len = value.size(); - } - - bt_status_t result = - hal::BluetoothGattInterface::Get() - ->GetServerHALInterface() - ->send_response(connection->conn_id, request_id, error, response); - if (result != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to initiate call to send GATT response"; - return false; - } - - connection->request_id_to_handle.erase(request_id); - - return true; -} - -bool GattServer::SendNotification(const std::string& device_address, - const uint16_t handle, bool confirm, - const std::vector<uint8_t>& value, - const GattCallback& callback) { - VLOG(1) << " - server_id: " << server_id_ - << " device_address: " << device_address << " confirm: " << confirm; - lock_guard<mutex> lock(mutex_); - - RawAddress addr; - if (!RawAddress::FromString(device_address, addr)) { - LOG(ERROR) << "Invalid device address given: " << device_address; - return false; - } - - // Get the connection IDs for which we will send this notification. - auto conn_iter = conn_addr_map_.find(device_address); - if (conn_iter == conn_addr_map_.end()) { - LOG(ERROR) << "No known connections for device with address: " - << device_address; - return false; - } - - std::shared_ptr<PendingIndication> pending_ind( - new PendingIndication(callback)); - - // Send the notification/indication on all matching connections. - int send_count = 0; - for (const auto& conn : conn_iter->second) { - // Make sure that one isn't already pending for this connection. - if (pending_indications_.find(conn->conn_id) != - pending_indications_.end()) { - VLOG(1) << "A" << (confirm ? "n indication" : " notification") - << " is already pending for connection: " << conn->conn_id; - continue; - } - - // The HAL API takes char* rather const char* for |value|, so we have to - // cast away the const. - // TODO(armansito): Make HAL accept const char*. - bt_status_t status = - hal::BluetoothGattInterface::Get() - ->GetServerHALInterface() - ->send_indication(server_id_, handle, conn->conn_id, confirm, - value.data(), value.size()); - - // Increment the send count if this was successful. We don't immediately - // fail if the HAL returned an error. It's better to report success as long - // as we sent out at least one notification to this device as - // multi-transport GATT connections from the same BD_ADDR will be rare - // enough already. - if (status != BT_STATUS_SUCCESS) continue; - - send_count++; - pending_indications_[conn->conn_id] = pending_ind; - } - - if (send_count == 0) { - LOG(ERROR) << "Failed to send notifications/indications to device: " - << device_address; - return false; - } - - return true; -} - -void GattServer::ConnectionCallback( - hal::BluetoothGattInterface* /* gatt_iface */, int conn_id, int server_id, - int connected, const RawAddress& bda) { - lock_guard<mutex> lock(mutex_); - - if (server_id != server_id_) return; - - std::string device_address = BtAddrString(&bda); - - VLOG(1) << __func__ << " conn_id: " << conn_id << " connected: " << connected - << " BD_ADDR: " << device_address; - - if (!connected) { - // Erase the entry if we were connected to it. - VLOG(1) << "No longer connected: " << device_address; - conn_id_map_.erase(conn_id); - auto iter = conn_addr_map_.find(device_address); - if (iter == conn_addr_map_.end()) return; - - // Remove the appropriate connection objects in the address. - for (auto conn_iter = iter->second.begin(); conn_iter != iter->second.end(); - ++conn_iter) { - if ((*conn_iter)->conn_id != conn_id) continue; - - iter->second.erase(conn_iter); - break; - } - - if (delegate_) - delegate_->OnConnectionStateChanged(this, device_address, false); - - return; - } - - if (conn_id_map_.find(conn_id) != conn_id_map_.end()) { - LOG(WARNING) << "Connection entry already exists; " - << "ignoring ConnectionCallback"; - return; - } - - LOG(INFO) << "Added connection entry for conn_id: " << conn_id - << " device address: " << device_address; - std::shared_ptr<Connection> connection(new Connection(conn_id, bda)); - conn_id_map_[conn_id] = connection; - conn_addr_map_[device_address].push_back(connection); - - if (delegate_) - delegate_->OnConnectionStateChanged(this, device_address, true); -} - -void GattServer::ServiceAddedCallback(hal::BluetoothGattInterface* gatt_iface, - int status, int server_id, - std::vector<btgatt_db_element_t> svc) { - lock_guard<mutex> lock(mutex_); - - if (server_id != server_id_) return; - - VLOG(1) << __func__ << " - status: " << status << " server_id: " << server_id - << " first handle: " << svc[0].attribute_handle - << " service Uuid: " << Uuid(svc[0].uuid).ToString() - << " count: " << svc.size(); - - Service service(svc[0].attribute_handle, true, Uuid(svc[0].uuid), {}, {}); - - for (size_t i = 1; i < svc.size(); i++) { - const btgatt_db_element_t& curr = svc[i]; - VLOG(1) << " - processing item no: " << i - << " handle: " << curr.attribute_handle; - if (curr.type == BTGATT_DB_CHARACTERISTIC) { - service.characteristics().push_back({curr.attribute_handle, - Uuid(curr.uuid), - curr.properties, - curr.permissions, - {}}); - } else if (curr.type == BTGATT_DB_DESCRIPTOR) { - service.characteristics().back().descriptors().push_back( - {curr.attribute_handle, Uuid(curr.uuid), curr.permissions}); - } else if (svc[i].type == BTGATT_DB_INCLUDED_SERVICE) { - } - } - - pending_end_decl_cb_((bluetooth::BLEStatus)status, service); - - CleanUpPendingData(); -} - -void GattServer::ServiceStoppedCallback( - hal::BluetoothGattInterface* /* gatt_iface */, int /* status */, - int /* server_id */, int /* service_handle */) { - // TODO(armansito): Support stopping a service. -} - -void GattServer::RequestReadCharacteristicCallback( - hal::BluetoothGattInterface* /* gatt_iface */, int conn_id, int trans_id, - const RawAddress& bda, int attribute_handle, int offset, bool is_long) { - lock_guard<mutex> lock(mutex_); - - // Check to see if we know about this connection. Otherwise ignore the - // request. - auto conn = GetConnection(conn_id, bda, trans_id); - if (!conn) return; - - std::string device_address = BtAddrString(&bda); - - VLOG(1) << __func__ << " - conn_id: " << conn_id << " trans_id: " << trans_id - << " BD_ADDR: " << device_address - << " attribute_handle: " << attribute_handle << " offset: " << offset - << " is_long: " << is_long; - - conn->request_id_to_handle[trans_id] = attribute_handle; - - // If there is no delegate then there is nobody to handle request. The request - // will eventually timeout and we should get a connection update that - // terminates the connection. - if (!delegate_) { - // TODO(armansito): Require a delegate at server registration so that this - // is never possible. - LOG(WARNING) << "No delegate was assigned to GattServer. Incoming request " - << "will time out."; - return; - } - - delegate_->OnCharacteristicReadRequest(this, device_address, trans_id, offset, - is_long, attribute_handle); -} -void GattServer::RequestReadDescriptorCallback( - hal::BluetoothGattInterface* /* gatt_iface */, int conn_id, int trans_id, - const RawAddress& bda, int attribute_handle, int offset, bool is_long) { - lock_guard<mutex> lock(mutex_); - - // Check to see if we know about this connection. Otherwise ignore the - // request. - auto conn = GetConnection(conn_id, bda, trans_id); - if (!conn) return; - - std::string device_address = BtAddrString(&bda); - - VLOG(1) << __func__ << " - conn_id: " << conn_id << " trans_id: " << trans_id - << " BD_ADDR: " << device_address - << " attribute_handle: " << attribute_handle << " offset: " << offset - << " is_long: " << is_long; - - conn->request_id_to_handle[trans_id] = attribute_handle; - - // If there is no delegate then there is nobody to handle request. The request - // will eventually timeout and we should get a connection update that - // terminates the connection. - if (!delegate_) { - // TODO(armansito): Require a delegate at server registration so that this - // is never possible. - LOG(WARNING) << "No delegate was assigned to GattServer. Incoming request " - << "will time out."; - return; - } - - delegate_->OnDescriptorReadRequest(this, device_address, trans_id, offset, - is_long, attribute_handle); -} - -void GattServer::RequestWriteCharacteristicCallback( - hal::BluetoothGattInterface* /* gatt_iface */, int conn_id, int trans_id, - const RawAddress& bda, int attr_handle, int offset, bool need_rsp, - bool is_prep, std::vector<uint8_t> value) { - lock_guard<mutex> lock(mutex_); - - // Check to see if we know about this connection. Otherwise ignore the - // request. - auto conn = GetConnection(conn_id, bda, trans_id); - if (!conn) return; - - std::string device_address = BtAddrString(&bda); - - VLOG(1) << __func__ << " - conn_id: " << conn_id << " trans_id: " << trans_id - << " BD_ADDR: " << device_address << " attr_handle: " << attr_handle - << " offset: " << offset << " length: " << value.size() - << " need_rsp: " << need_rsp << " is_prep: " << is_prep; - - // Store the request ID only if this is not a write-without-response. If - // another request occurs after this with the same request ID, then we'll - // simply process it normally, though that shouldn't ever happen. - if (need_rsp) conn->request_id_to_handle[trans_id] = attr_handle; - - // If there is no delegate then there is nobody to handle request. The request - // will eventually timeout and we should get a connection update that - // terminates the connection. - if (!delegate_) { - // TODO(armansito): Require a delegate at server registration so that this - // is never possible. - LOG(WARNING) << "No delegate was assigned to GattServer. Incoming request " - << "will time out."; - return; - } - - delegate_->OnCharacteristicWriteRequest(this, device_address, trans_id, - offset, is_prep, need_rsp, - std::move(value), attr_handle); -} - -void GattServer::RequestWriteDescriptorCallback( - hal::BluetoothGattInterface* /* gatt_iface */, int conn_id, int trans_id, - const RawAddress& bda, int attr_handle, int offset, bool need_rsp, - bool is_prep, std::vector<uint8_t> value) { - lock_guard<mutex> lock(mutex_); - - // Check to see if we know about this connection. Otherwise ignore the - // request. - auto conn = GetConnection(conn_id, bda, trans_id); - if (!conn) return; - - std::string device_address = BtAddrString(&bda); - - VLOG(1) << __func__ << " - conn_id: " << conn_id << " trans_id: " << trans_id - << " BD_ADDR: " << device_address << " attr_handle: " << attr_handle - << " offset: " << offset << " length: " << value.size() - << " need_rsp: " << need_rsp << " is_prep: " << is_prep; - - // Store the request ID only if this is not a write-without-response. If - // another request occurs after this with the same request ID, then we'll - // simply process it normally, though that shouldn't ever happen. - if (need_rsp) conn->request_id_to_handle[trans_id] = attr_handle; - - // If there is no delegate then there is nobody to handle request. The request - // will eventually timeout and we should get a connection update that - // terminates the connection. - if (!delegate_) { - // TODO(armansito): Require a delegate at server registration so that this - // is never possible. - LOG(WARNING) << "No delegate was assigned to GattServer. Incoming request " - << "will time out."; - return; - } - - delegate_->OnDescriptorWriteRequest(this, device_address, trans_id, offset, - is_prep, need_rsp, std::move(value), - attr_handle); -} - -void GattServer::RequestExecWriteCallback( - hal::BluetoothGattInterface* /* gatt_iface */, int conn_id, int trans_id, - const RawAddress& bda, int exec_write) { - lock_guard<mutex> lock(mutex_); - - // Check to see if we know about this connection. Otherwise ignore the - // request. - auto conn = GetConnection(conn_id, bda, trans_id); - if (!conn) return; - - std::string device_address = BtAddrString(&bda); - - VLOG(1) << __func__ << " - conn_id: " << conn_id << " trans_id: " << trans_id - << " BD_ADDR: " << device_address << " exec_write: " << exec_write; - - // Just store a dummy invalid handle as this request doesn't apply to a - // specific handle. - conn->request_id_to_handle[trans_id] = -1; - - // If there is no delegate then there is nobody to handle request. The request - // will eventually timeout and we should get a connection update that - // terminates the connection. - if (!delegate_) { - // TODO(armansito): Require a delegate at server registration so that this - // is never possible. - LOG(WARNING) << "No delegate was assigned to GattServer. Incoming request " - << "will time out."; - return; - } - - delegate_->OnExecuteWriteRequest(this, device_address, trans_id, exec_write); -} - -void GattServer::IndicationSentCallback( - hal::BluetoothGattInterface* /* gatt_iface */, int conn_id, int status) { - VLOG(1) << __func__ << " conn_id: " << conn_id << " status: " << status; - lock_guard<mutex> lock(mutex_); - - const auto& pending_ind_iter = pending_indications_.find(conn_id); - if (pending_ind_iter == pending_indications_.end()) { - VLOG(1) << "Unknown connection: " << conn_id; - return; - } - - std::shared_ptr<PendingIndication> pending_ind = pending_ind_iter->second; - pending_indications_.erase(pending_ind_iter); - - if (status == BT_STATUS_SUCCESS) pending_ind->has_success = true; - - // Invoke it if this was the last reference to the confirmation callback. - if (pending_ind.unique() && pending_ind->callback) { - pending_ind->callback(pending_ind->has_success - ? GATT_ERROR_NONE - : static_cast<GATTError>(status)); - } -} - -void GattServer::CleanUpPendingData() { - pending_end_decl_cb_ = ResultCallback(); -} - -std::shared_ptr<GattServer::Connection> GattServer::GetConnection( - int conn_id, const RawAddress& bda, int request_id) { - auto iter = conn_id_map_.find(conn_id); - if (iter == conn_id_map_.end()) { - VLOG(1) << "Connection doesn't belong to this server"; - return nullptr; - } - - auto conn = iter->second; - if (conn->bdaddr != bda) { - LOG(WARNING) << "BD_ADDR: " << BtAddrString(&bda) << " doesn't match " - << "connection ID: " << conn_id; - return nullptr; - } - - if (conn->request_id_to_handle.find(request_id) != - conn->request_id_to_handle.end()) { - VLOG(1) << "Request with ID: " << request_id << " already exists for " - << " connection: " << conn_id; - return nullptr; - } - - return conn; -} - -// GattServerFactory implementation - -GattServerFactory::GattServerFactory() { - hal::BluetoothGattInterface::Get()->AddServerObserver(this); -} - -GattServerFactory::~GattServerFactory() { - hal::BluetoothGattInterface::Get()->RemoveServerObserver(this); -} - -bool GattServerFactory::RegisterInstance(const Uuid& uuid, - const RegisterCallback& callback) { - VLOG(1) << __func__ << " - Uuid: " << uuid.ToString(); - lock_guard<mutex> lock(pending_calls_lock_); - - if (pending_calls_.find(uuid) != pending_calls_.end()) { - LOG(ERROR) << "GATT-server client with given Uuid already being registered " - << " - Uuid: " << uuid.ToString(); - return false; - } - - const btgatt_server_interface_t* hal_iface = - hal::BluetoothGattInterface::Get()->GetServerHALInterface(); - - if (hal_iface->register_server(uuid, false) != BT_STATUS_SUCCESS) - return false; - - pending_calls_[uuid] = callback; - - return true; -} - -void GattServerFactory::RegisterServerCallback( - hal::BluetoothGattInterface* gatt_iface, int status, int server_id, - const Uuid& app_uuid) { - Uuid uuid(app_uuid); - - VLOG(1) << __func__ << " - Uuid: " << uuid.ToString(); - lock_guard<mutex> lock(pending_calls_lock_); - - auto iter = pending_calls_.find(uuid); - if (iter == pending_calls_.end()) { - VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString(); - return; - } - - // No need to construct a server if the call wasn't successful. - std::unique_ptr<GattServer> server; - BLEStatus result = BLE_STATUS_FAILURE; - if (status == BT_STATUS_SUCCESS) { - server.reset(new GattServer(uuid, server_id)); - - gatt_iface->AddServerObserver(server.get()); - - result = BLE_STATUS_SUCCESS; - } - - // Notify the result via the result callback. - iter->second(result, uuid, std::move(server)); - - pending_calls_.erase(iter); -} - -} // namespace bluetooth diff --git a/system/service/gatt_server.h b/system/service/gatt_server.h deleted file mode 100644 index 7d670aed91..0000000000 --- a/system/service/gatt_server.h +++ /dev/null @@ -1,298 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <bluetooth/uuid.h> - -#include <deque> -#include <functional> -#include <mutex> -#include <string> -#include <unordered_map> -#include <unordered_set> -#include <vector> - -#include "service/bluetooth_instance.h" -#include "service/common/bluetooth/service.h" -#include "service/hal/bluetooth_gatt_interface.h" -#include "types/raw_address.h" - -namespace bluetooth { - -// A GattServer instance represents an application's handle to perform GATT -// server-role operations. Instances cannot be created directly and should be -// obtained through the factory. -class GattServer : public BluetoothInstance, - private hal::BluetoothGattInterface::ServerObserver { - public: - // Delegate interface is used to handle incoming requests and confirmations - // for a GATT service. - class Delegate { - public: - Delegate() = default; - Delegate(const Delegate&) = delete; - Delegate& operator=(const Delegate&) = delete; - - virtual ~Delegate() = default; - - // Called when there is an incoming read request for the characteristic with - // ID |characteristic_id| from a remote device with address - // |device_address|. |request_id| can be used to respond to this request by - // calling SendResponse below. - virtual void OnCharacteristicReadRequest(GattServer* gatt_server, - const std::string& device_address, - int request_id, int offset, - bool is_long, uint16_t handle) = 0; - - // Called when there is an incoming read request for the descriptor with - // ID |descriptor_id| from a remote device with address |device_address|. - // |request_id| can be used to respond to this request by - // calling SendResponse below. - virtual void OnDescriptorReadRequest(GattServer* gatt_server, - const std::string& device_address, - int request_id, int offset, - bool is_long, uint16_t handle) = 0; - - // Called when there is an incoming write request for the characteristic - // with ID |characteristic_id| from a remote device with address - // |device_address|. |request_id| can be used to respond to this request by - // calling SendResponse, if the |need_response| parameter is true. Otherwise - // this is a "Write Without Reponse" procedure and SendResponse will fail. - // If |is_prepare_write| is true, then the write should not be committed - // immediately as this is a "Prepared Write Request". Instead, the Delegate - // should hold on to the value and either discard it or complete the write - // when it receives the OnExecuteWriteRequest event. - virtual void OnCharacteristicWriteRequest( - GattServer* gatt_server, const std::string& device_address, - int request_id, int offset, bool is_prepare_write, bool need_response, - const std::vector<uint8_t>& value, uint16_t handle) = 0; - - // Called when there is an incoming write request for the descriptor - // with ID |descriptor_id| from a remote device with address - // |device_address|. |request_id| can be used to respond to this request by - // calling SendResponse, if the |need_response| parameter is true. Otherwise - // this is a "Write Without Response" procedure and SendResponse will fail. - // If |is_prepare_write| is true, then the write should not be committed - // immediately as this is a "Prepared Write Request". Instead, the Delegate - // should hold on to the value and either discard it or complete the write - // when it receives the OnExecuteWriteRequest event. - virtual void OnDescriptorWriteRequest( - GattServer* gatt_server, const std::string& device_address, - int request_id, int offset, bool is_prepare_write, bool need_response, - const std::vector<uint8_t>& value, uint16_t handle) = 0; - - // Called when there is an incoming "Execute Write Request". If |is_execute| - // is true, then the Delegate should commit all previously prepared writes. - // Otherwise, all prepared writes should be aborted. The Delegate should - // call "SendResponse" to complete the procedure. - virtual void OnExecuteWriteRequest(GattServer* gatt_server, - const std::string& device_address, - int request_id, bool is_execute) = 0; - - virtual void OnConnectionStateChanged(GattServer* gatt_server, - const std::string& device_addres, - bool connected) = 0; - }; - - // The desctructor automatically unregisters this instance from the stack. - GattServer(const GattServer&) = delete; - GattServer& operator=(const GattServer&) = delete; - - ~GattServer() override; - - // Assigns a delegate to this instance. |delegate| must out-live this - // GattServer instance. - void SetDelegate(Delegate* delegate); - - // BluetoothClientInstace overrides: - const Uuid& GetAppIdentifier() const override; - int GetInstanceId() const override; - - // Callback type used to report the status of an asynchronous GATT server - // operation. - using ResultCallback = - std::function<void(BLEStatus status, const Service& id)>; - using GattCallback = std::function<void(GATTError error)>; - - // Add service declaration. This method immediately - // returns false if a service hasn't been started. Otherwise, |callback| will - // be called asynchronously with the result of the operation. - // - // TODO(armansito): It is unclear to me what it means for this function to - // fail. What is the state that we're in? Is the service declaration over so - // we can add other services to this server instance? Do we need to clean up - // all the entries or does the upper-layer need to remove the service? Or are - // we in a stuck-state where the service declaration hasn't ended? - bool AddService(const Service&, const ResultCallback& callback); - - // Sends a response for a pending notification. |request_id| and - // |device_address| should match those that were received through one of the - // Delegate callbacks. |value| and |offset| are used for read requests and - // prepare write requests and should match the value of the attribute. Returns - // false if the pending request could not be resolved using the given - // parameters or if the call to the underlying stack fails. - bool SendResponse(const std::string& device_address, int request_id, - GATTError error, int offset, - const std::vector<uint8_t>& value); - - // Sends an ATT Handle-Value Notification to the device with BD_ADDR - // |device_address| for the characteristic with handle |handle| and - // value |value|. If |confirm| is true, then an ATT Handle-Value Indication - // will be sent instead, which requires the remote to confirm receipt. Returns - // false if there was an immediate error in initiating the notification - // procedure. Otherwise, returns true and reports the asynchronous result of - // the operation in |callback|. - // - // If |confirm| is true, then |callback| will be run when the remote device - // sends a ATT Handle-Value Confirmation packet. Otherwise, it will be run as - // soon as the notification has been sent out. - bool SendNotification(const std::string& device_address, - const uint16_t handle, bool confirm, - const std::vector<uint8_t>& value, - const GattCallback& callback); - - private: - friend class GattServerFactory; - - // Used for the internal remote connection tracking. Keeps track of the - // request ID and the device address for the connection. If |request_id| is -1 - // then no ATT read/write request is currently pending. - struct Connection { - Connection(int conn_id, const RawAddress& bdaddr) - : conn_id(conn_id), bdaddr(bdaddr) {} - Connection() : conn_id(-1) { memset(&bdaddr, 0, sizeof(bdaddr)); } - - int conn_id; - std::unordered_map<int, int> request_id_to_handle; - RawAddress bdaddr; - }; - - // Used to keep track of a pending Handle-Value indication. - struct PendingIndication { - explicit PendingIndication(const GattCallback& callback) - : has_success(false), callback(callback) {} - - bool has_success; - GattCallback callback; - }; - - // Constructor shouldn't be called directly as instances are meant to be - // obtained from the factory. - GattServer(const Uuid& uuid, int server_id); - - // hal::BluetoothGattInterface::ServerObserver overrides: - void ConnectionCallback(hal::BluetoothGattInterface* gatt_iface, int conn_id, - int server_id, int connected, - const RawAddress& bda) override; - void ServiceAddedCallback(hal::BluetoothGattInterface* gatt_iface, int status, - int server_if, - std::vector<btgatt_db_element_t>) override; - void ServiceStoppedCallback(hal::BluetoothGattInterface* gatt_iface, - int status, int server_id, - int service_handle) override; - void RequestReadCharacteristicCallback( - hal::BluetoothGattInterface* gatt_iface, int conn_id, int trans_id, - const RawAddress& bda, int attribute_handle, int offset, - bool is_long) override; - void RequestReadDescriptorCallback(hal::BluetoothGattInterface* gatt_iface, - int conn_id, int trans_id, - const RawAddress& bda, - int attribute_handle, int offset, - bool is_long) override; - void RequestWriteCharacteristicCallback( - hal::BluetoothGattInterface* gatt_iface, int conn_id, int trans_id, - const RawAddress& bda, int attr_handle, int offset, bool need_rsp, - bool is_prep, std::vector<uint8_t> value) override; - void RequestWriteDescriptorCallback(hal::BluetoothGattInterface* gatt_iface, - int conn_id, int trans_id, - const RawAddress& bda, int attr_handle, - int offset, bool need_rsp, bool is_prep, - std::vector<uint8_t> value) override; - void RequestExecWriteCallback(hal::BluetoothGattInterface* gatt_iface, - int conn_id, int trans_id, - const RawAddress& bda, int exec_write) override; - void IndicationSentCallback(hal::BluetoothGattInterface* gatt_iface, - int conn_id, int status) override; - - // Helper function that notifies and clears the pending callback. - void CleanUpPendingData(); - - // Handles the next attribute entry in the pending service declaration. - void HandleNextEntry(hal::BluetoothGattInterface* gatt_iface); - - // Helper method that returns a pointer to an internal Connection instance - // that matches the given parameters. - std::shared_ptr<Connection> GetConnection(int conn_id, const RawAddress& bda, - int request_id); - - // See getters for documentation. - Uuid app_identifier_; - int server_id_; - - // Mutex that synchronizes access to the entries below. - std::mutex mutex_; - ResultCallback pending_end_decl_cb_; - - // GATT connection mappings from stack-provided "conn_id" IDs and remote - // device addresses to Connection structures. The conn_id map is one-to-one - // while the conn_addr map is one to many, as a remote device may support - // multiple transports (BR/EDR & LE) and use the same device address for both. - std::unordered_map<int, std::shared_ptr<Connection>> conn_id_map_; - std::unordered_map<std::string, std::vector<std::shared_ptr<Connection>>> - conn_addr_map_; - - // Connections for which a Handle-Value indication is pending. Since there can - // be multiple indications to the same device (in the case of a dual-mode - // device with simulatenous BR/EDR & LE GATT connections), we also keep track - // of whether there has been at least one successful confirmation. - std::unordered_map<int, std::shared_ptr<PendingIndication>> - pending_indications_; - - // Raw handle to the Delegate, which must outlive this GattServer instance. - Delegate* delegate_; -}; - -// GattServerFactory is used to register and obtain a per-application GattServer -// instance. Users should call RegisterClient to obtain their own unique -// GattServer instance that has been registered with the Bluetooth stack. -class GattServerFactory : public BluetoothInstanceFactory, - private hal::BluetoothGattInterface::ServerObserver { - public: - // Don't construct/destruct directly except in tests. Instead, obtain a handle - // from an Adapter instance. - GattServerFactory(); - GattServerFactory(const GattServerFactory&) = delete; - GattServerFactory& operator=(const GattServerFactory&) = delete; - - ~GattServerFactory() override; - - // BluetoothInstanceFactory override: - bool RegisterInstance(const Uuid& uuid, - const RegisterCallback& callback) override; - - private: - // hal::BluetoothGattInterface::ServerObserver override: - void RegisterServerCallback(hal::BluetoothGattInterface* gatt_iface, - int status, int server_id, - const Uuid& app_uuid) override; - - // Map of pending calls to register. - std::mutex pending_calls_lock_; - std::unordered_map<Uuid, RegisterCallback> pending_calls_; -}; - -} // namespace bluetooth diff --git a/system/service/gatt_server_old.cc b/system/service/gatt_server_old.cc deleted file mode 100644 index ac438d2ef7..0000000000 --- a/system/service/gatt_server_old.cc +++ /dev/null @@ -1,735 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#define LOG_TAG "bt_gatts" - -#include "gatt_server_old.h" - -#include <base/functional/bind.h> -#include <base/functional/callback.h> -#include <hardware/bluetooth.h> -#include <hardware/bt_gatt.h> -#include <stdio.h> -#include <stdlib.h> -#include <unistd.h> - -#include <algorithm> -#include <array> -#include <condition_variable> -#include <map> -#include <memory> -#include <mutex> -#include <set> -#include <string> -#include <unordered_map> -#include <unordered_set> -#include <vector> - -#include "bind_helpers.h" -#include "osi/include/log.h" -#include "osi/include/osi.h" -#include "service/hal/bluetooth_interface.h" -#include "service/logging_helpers.h" -#include "types/raw_address.h" - -namespace { - -const size_t kMaxGattAttributeSize = 512; -std::vector<btgatt_db_element_t> pending_svc_decl; -std::unordered_set<int> blob_index; - -// TODO(icoolidge): Support multiple instances -// TODO(armansito): Remove this variable. No point of having this if -// each bluetooth::gatt::Server instance already keeps a pointer to the -// ServerInternals that is associated with it (which is much cleaner). It looks -// like this variable exists because the btif callbacks don't allow the -// upper-layer to pass user data to them. We could: -// -// 1. Fix the btif callbacks so that some sort of continuation can be -// attached to a callback. This might be a long shot since the callback -// interface doesn't allow more than one caller to register its own callbacks -// (which might be what we want though, since this would make the API more -// flexible). -// -// 2. Allow creation of Server objects using a factory method that returns -// the result asynchronously in a base::Callback. The RegisterServerCallback -// provides an |app_uuid|, which can be used to store callback structures in -// a map and lazily instantiate the Server and invoke the correct callback. -// This is a general pattern that we should use throughout the daemon, since -// all operations can timeout or fail and this is best reported in an -// asynchronous base::Callback. -// -static bluetooth::gatt::ServerInternals* g_internal = nullptr; - -enum { kPipeReadEnd = 0, kPipeWriteEnd = 1, kPipeNumEnds = 2 }; - -} // namespace - -namespace bluetooth { -namespace gatt { - -struct Characteristic { - Uuid uuid; - int blob_section; - std::vector<uint8_t> blob; - - // Support synchronized blob updates by latching under mutex. - std::vector<uint8_t> next_blob; - bool next_blob_pending; - bool notify; -}; - -struct ServerInternals { - ServerInternals(); - ~ServerInternals(); - int Initialize(); - bt_status_t AddCharacteristic(const Uuid& uuid, uint8_t properties, - uint16_t permissions); - - // This maps API attribute Uuids to BlueDroid handles. - std::map<Uuid, int> uuid_to_attribute; - - // The attribute cache, indexed by BlueDroid handles. - std::unordered_map<int, Characteristic> characteristics; - - // Associate a control attribute with its value attribute. - std::unordered_map<int, int> controlled_blobs; - - ScanResults scan_results; - - Uuid last_write; - const btgatt_interface_t* gatt; - int server_if; - int client_if; - int service_handle; - std::set<int> connections; - - std::mutex lock; - std::condition_variable api_synchronize; - int pipefd[kPipeNumEnds]; -}; - -} // namespace gatt -} // namespace bluetooth - -namespace { - -/** Callback invoked in response to register_server */ -void RegisterServerCallback(int status, int server_if, - const bluetooth::Uuid& app_uuid) { - LOG_INFO("%s: status:%d server_if:%d app_uuid:%p", __func__, status, - server_if, &app_uuid); - - g_internal->server_if = server_if; - - pending_svc_decl.push_back({ - .uuid = app_uuid, - .type = BTGATT_DB_PRIMARY_SERVICE, - }); -} - -void ServiceAddedCallback(int status, int server_if, - const btgatt_db_element_t* service, - size_t service_count) { - LOG_INFO("%s: status:%d server_if:%d count:%zu svc_handle:%d", __func__, - status, server_if, service_count, service[0].attribute_handle); - - std::lock_guard<std::mutex> lock(g_internal->lock); - g_internal->server_if = server_if; - - g_internal->service_handle = service[0].attribute_handle; - - uint16_t prev_char_handle = 0; - uint16_t prev_char_properties = 0; - for (size_t i = 1; i < service_count; i++) { - const btgatt_db_element_t& el = service[i]; - if (el.type == BTGATT_DB_DESCRIPTOR) { - LOG_INFO("%s: descr_handle:%d", __func__, el.attribute_handle); - } else if (el.type == BTGATT_DB_CHARACTERISTIC) { - bluetooth::Uuid id(el.uuid); - uint16_t char_handle = el.attribute_handle; - - LOG_INFO("%s: char_handle:%d", __func__, char_handle); - - g_internal->uuid_to_attribute[id] = char_handle; - g_internal->characteristics[char_handle].uuid = id; - g_internal->characteristics[char_handle].blob_section = 0; - - // If the added characteristic is blob - if (blob_index.find(i) != blob_index.end()) { - // Finally, associate the control attribute with the value attribute. - // Also, initialize the control attribute to a readable zero. - const uint16_t control_attribute = char_handle; - const uint16_t blob_attribute = prev_char_handle; - g_internal->controlled_blobs[control_attribute] = blob_attribute; - g_internal->characteristics[blob_attribute].notify = - prev_char_properties & bluetooth::gatt::kPropertyNotify; - - bluetooth::gatt::Characteristic& ctrl = - g_internal->characteristics[control_attribute]; - ctrl.next_blob.clear(); - ctrl.next_blob.push_back(0); - ctrl.next_blob_pending = true; - ctrl.blob_section = 0; - ctrl.notify = false; - } - prev_char_handle = char_handle; - prev_char_properties = el.properties; - } - } - - pending_svc_decl.clear(); - blob_index.clear(); - - // The Uuid provided here is unimportant, and is only used to satisfy - // BlueDroid. - // It must be different than any other registered Uuid. - bluetooth::Uuid client_id = bluetooth::Uuid::GetRandom(); - - bt_status_t btstat = - g_internal->gatt->client->register_client(client_id, false); - if (btstat != BT_STATUS_SUCCESS) { - LOG_ERROR("%s: Failed to register client", __func__); - } -} - -void RequestReadCallback(int conn_id, int trans_id, const RawAddress& bda, - int attr_handle, int attribute_offset_octets, - bool is_long) { - std::lock_guard<std::mutex> lock(g_internal->lock); - - bluetooth::gatt::Characteristic& ch = - g_internal->characteristics[attr_handle]; - - // Latch next_blob to blob on a 'fresh' read. - if (ch.next_blob_pending && attribute_offset_octets == 0 && - ch.blob_section == 0) { - std::swap(ch.blob, ch.next_blob); - ch.next_blob_pending = false; - } - - const size_t blob_offset_octets = - std::min(ch.blob.size(), ch.blob_section * kMaxGattAttributeSize); - const size_t blob_remaining = ch.blob.size() - blob_offset_octets; - const size_t attribute_size = std::min(kMaxGattAttributeSize, blob_remaining); - - std::string addr(BtAddrString(&bda)); - LOG_INFO( - "%s: connection:%d (%s) reading attr:%d attribute_offset_octets:%d " - "blob_section:%u (is_long:%u)", - __func__, conn_id, addr.c_str(), attr_handle, attribute_offset_octets, - ch.blob_section, is_long); - - btgatt_response_t response; - response.attr_value.len = 0; - - if (attribute_offset_octets < static_cast<int>(attribute_size)) { - std::copy(ch.blob.begin() + blob_offset_octets + attribute_offset_octets, - ch.blob.begin() + blob_offset_octets + attribute_size, - response.attr_value.value); - response.attr_value.len = attribute_size - attribute_offset_octets; - } - - response.attr_value.handle = attr_handle; - response.attr_value.offset = attribute_offset_octets; - response.attr_value.auth_req = 0; - g_internal->gatt->server->send_response(conn_id, trans_id, 0, response); -} - -void RequestWriteCallback(int conn_id, int trans_id, const RawAddress& bda, - int attr_handle, int attribute_offset, bool need_rsp, - bool is_prep, const uint8_t* value, size_t length) { - std::string addr(BtAddrString(&bda)); - LOG_INFO( - "%s: connection:%d (%s:trans:%d) write attr:%d attribute_offset:%d " - "length:%zu " - "need_resp:%u is_prep:%u", - __func__, conn_id, addr.c_str(), trans_id, attr_handle, attribute_offset, - length, need_rsp, is_prep); - - std::lock_guard<std::mutex> lock(g_internal->lock); - - bluetooth::gatt::Characteristic& ch = - g_internal->characteristics[attr_handle]; - - ch.blob.resize(attribute_offset + length); - - std::copy(value, value + length, ch.blob.begin() + attribute_offset); - - auto target_blob = g_internal->controlled_blobs.find(attr_handle); - // If this is a control attribute, adjust offset of the target blob. - if (target_blob != g_internal->controlled_blobs.end() && - ch.blob.size() == 1u) { - g_internal->characteristics[target_blob->second].blob_section = ch.blob[0]; - LOG_INFO("%s: updating attribute %d blob_section to %u", __func__, - target_blob->second, ch.blob[0]); - } else if (!is_prep) { - // This is a single frame characteristic write. - // Notify upwards because we're done now. - const bluetooth::Uuid::UUID128Bit& attr_uuid = ch.uuid.To128BitBE(); - ssize_t status; - OSI_NO_INTR(status = write(g_internal->pipefd[kPipeWriteEnd], - attr_uuid.data(), attr_uuid.size())); - if (-1 == status) - LOG_ERROR("%s: write failed: %s", __func__, strerror(errno)); - } else { - // This is a multi-frame characteristic write. - // Wait for an 'RequestExecWriteCallback' to notify completion. - g_internal->last_write = ch.uuid; - } - - // Respond only if needed. - if (!need_rsp) return; - - btgatt_response_t response; - response.attr_value.handle = attr_handle; - response.attr_value.offset = attribute_offset; - response.attr_value.len = length; - response.attr_value.auth_req = 0; - // Provide written data back to sender for the response. - // Remote stacks use this to validate the success of the write. - std::copy(value, value + length, response.attr_value.value); - g_internal->gatt->server->send_response(conn_id, trans_id, 0, response); -} - -void RequestExecWriteCallback(int conn_id, int trans_id, const RawAddress& bda, - int exec_write) { - std::string addr(BtAddrString(&bda)); - LOG_INFO("%s: connection:%d (%s:trans:%d) exec_write:%d", __func__, conn_id, - addr.c_str(), trans_id, exec_write); - - // This 'response' data is unused for ExecWriteResponses. - // It is only used to pass BlueDroid argument validation. - btgatt_response_t response = {}; - g_internal->gatt->server->send_response(conn_id, trans_id, 0, response); - - if (!exec_write) return; - - std::lock_guard<std::mutex> lock(g_internal->lock); - // Communicate the attribute Uuid as notification of a write update. - const bluetooth::Uuid::UUID128Bit uuid = g_internal->last_write.To128BitBE(); - ssize_t status; - OSI_NO_INTR(status = write(g_internal->pipefd[kPipeWriteEnd], uuid.data(), - uuid.size())); - if (-1 == status) - LOG_ERROR("%s: write failed: %s", __func__, strerror(errno)); -} - -void ConnectionCallback(int conn_id, int server_if, int connected, - const RawAddress& bda) { - std::string addr(BtAddrString(&bda)); - LOG_INFO("%s: connection:%d server_if:%d connected:%d addr:%s", __func__, - conn_id, server_if, connected, addr.c_str()); - if (connected == 1) { - g_internal->connections.insert(conn_id); - } else if (connected == 0) { - g_internal->connections.erase(conn_id); - } -} - -void EnableAdvertisingCallback(uint8_t status) { - LOG_INFO("%s: status:%d", __func__, status); - // This terminates a Start call. - std::lock_guard<std::mutex> lock(g_internal->lock); - g_internal->api_synchronize.notify_one(); -} - -void RegisterClientCallback(int status, int client_if, - const bluetooth::Uuid& app_uuid) { - LOG_INFO("%s: status:%d client_if:%d uuid[0]:%s", __func__, status, client_if, - app_uuid.ToString().c_str()); - g_internal->client_if = client_if; - - // Setup our advertisement. This has no callback. - g_internal->gatt->advertiser->SetData(0 /* std_inst */, false, - {/*TODO: put inverval 2,2 here*/}, - base::DoNothing()); - - g_internal->gatt->advertiser->Enable( - 0 /* std_inst */, true, base::Bind(&EnableAdvertisingCallback), - 0 /* no duration */, 0 /* no maxExtAdvEvent*/, base::DoNothing()); -} - -void ServiceStoppedCallback(int status, int server_if, int srvc_handle) { - LOG_INFO("%s: status:%d server_if:%d srvc_handle:%d", __func__, status, - server_if, srvc_handle); - // This terminates a Stop call. - // TODO(icoolidge): make this symmetric with start - std::lock_guard<std::mutex> lock(g_internal->lock); - g_internal->api_synchronize.notify_one(); -} - -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<uint8_t> adv_data, - RawAddress* original_bda) { - std::string addr(BtAddrString(bda)); - std::lock_guard<std::mutex> lock(g_internal->lock); - g_internal->scan_results[addr] = rssi; -} - -void ClientConnectCallback(int conn_id, int status, int client_if, - const RawAddress& bda) { - std::string addr(BtAddrString(&bda)); - LOG_INFO("%s: conn_id:%d status:%d client_if:%d %s", __func__, conn_id, - status, client_if, addr.c_str()); -} - -void ClientDisconnectCallback(int conn_id, int status, int client_if, - const RawAddress& bda) { - std::string addr(BtAddrString(&bda)); - LOG_INFO("%s: conn_id:%d status:%d client_if:%d %s", __func__, conn_id, - status, client_if, addr.c_str()); -} - -void IndicationSentCallback(UNUSED_ATTR int conn_id, UNUSED_ATTR int status) { - // TODO(icoolidge): what to do -} - -void ResponseConfirmationCallback(UNUSED_ATTR int status, - UNUSED_ATTR int handle) { - // TODO(icoolidge): what to do -} - -const btgatt_server_callbacks_t gatt_server_callbacks = { - RegisterServerCallback, - ConnectionCallback, - ServiceAddedCallback, - ServiceStoppedCallback, - nullptr, /* service_deleted_cb */ - RequestReadCallback, - RequestReadCallback, - RequestWriteCallback, - RequestWriteCallback, - RequestExecWriteCallback, - ResponseConfirmationCallback, - IndicationSentCallback, - nullptr, /* congestion_cb*/ - nullptr, /* mtu_changed_cb */ - nullptr, /* phy_update_cb */ - nullptr, /* conn_update_cb */ - nullptr, /* subrate_chg_cb */ -}; - -// TODO(eisenbach): Refactor GATT interface to not require servers -// to refer to the client interface. -const btgatt_client_callbacks_t gatt_client_callbacks = { - RegisterClientCallback, - ClientConnectCallback, - ClientDisconnectCallback, - nullptr, /* search_complete_cb; */ - nullptr, /* register_for_notification_cb; */ - nullptr, /* notify_cb; */ - nullptr, /* read_characteristic_cb; */ - nullptr, /* write_characteristic_cb; */ - nullptr, /* read_descriptor_cb; */ - nullptr, /* write_descriptor_cb; */ - nullptr, /* execute_write_cb; */ - nullptr, /* read_remote_rssi_cb; */ - nullptr, /* configure_mtu_cb; */ - nullptr, /* congestion_cb; */ - nullptr, /* get_gatt_db_cb; */ - nullptr, /* services_removed_cb */ - nullptr, /* services_added_cb */ - nullptr, /* phy_update_cb */ - nullptr, /* conn_update_cb */ - nullptr, /* service_changed_cb*/ - nullptr, /* subrate_chg_cb */ -}; - -const btgatt_scanner_callbacks_t gatt_scanner_callbacks = { - ScanResultCallback, - nullptr, /* batchscan_reports_cb; */ - nullptr, /* batchscan_threshold_cb; */ - nullptr, /* track_adv_event_cb; */ -}; - -const btgatt_callbacks_t gatt_callbacks = { - /** Set to sizeof(btgatt_callbacks_t) */ - sizeof(btgatt_callbacks_t), - - /** GATT Client callbacks */ - &gatt_client_callbacks, - - /** GATT Server callbacks */ - &gatt_server_callbacks, - - /** GATT Server callbacks */ - &gatt_scanner_callbacks, -}; - -} // namespace - -namespace bluetooth { -namespace gatt { - -int ServerInternals::Initialize() { - // Get the interface to the GATT profile. - const bt_interface_t* bt_iface = - hal::BluetoothInterface::Get()->GetHALInterface(); - gatt = reinterpret_cast<const btgatt_interface_t*>( - bt_iface->get_profile_interface(BT_PROFILE_GATT_ID)); - if (!gatt) { - LOG_ERROR("Error getting GATT interface"); - return -1; - } - - bt_status_t btstat = gatt->init(&gatt_callbacks); - if (btstat != BT_STATUS_SUCCESS) { - LOG_ERROR("Failed to initialize gatt interface"); - return -1; - } - - int status = pipe(pipefd); - if (status == -1) { - LOG_ERROR("pipe creation failed: %s", strerror(errno)); - return -1; - } - - return 0; -} - -bt_status_t ServerInternals::AddCharacteristic(const Uuid& uuid, - uint8_t properties, - uint16_t permissions) { - pending_svc_decl.push_back({.uuid = uuid, - .type = BTGATT_DB_CHARACTERISTIC, - .properties = properties, - .permissions = permissions}); - return BT_STATUS_SUCCESS; -} - -ServerInternals::ServerInternals() - : gatt(nullptr), - server_if(0), - client_if(0), - service_handle(0), - pipefd{INVALID_FD, INVALID_FD} {} - -ServerInternals::~ServerInternals() { - if (pipefd[0] != INVALID_FD) close(pipefd[0]); - if (pipefd[1] != INVALID_FD) close(pipefd[1]); - - gatt->server->delete_service(server_if, service_handle); - gatt->server->unregister_server(server_if); - gatt->client->unregister_client(client_if); -} - -Server::Server() : internal_(nullptr) {} - -Server::~Server() {} - -bool Server::Initialize(const Uuid& service_id, int* gatt_pipe) { - internal_.reset(new ServerInternals); - if (!internal_) { - LOG_ERROR("Error creating internals"); - return false; - } - g_internal = internal_.get(); - - std::unique_lock<std::mutex> lock(internal_->lock); - int status = internal_->Initialize(); - if (status) { - LOG_ERROR("Error initializing internals"); - return false; - } - - bt_status_t btstat = - internal_->gatt->server->register_server(service_id, false); - if (btstat != BT_STATUS_SUCCESS) { - LOG_ERROR("Failed to register server"); - return false; - } - - internal_->api_synchronize.wait(lock); - // TODO(icoolidge): Better error handling. - if (internal_->server_if == 0) { - LOG_ERROR("Initialization of server failed"); - return false; - } - - *gatt_pipe = internal_->pipefd[kPipeReadEnd]; - LOG_INFO("Server Initialize succeeded"); - return true; -} - -bool Server::SetAdvertisement(const std::vector<Uuid>& ids, - const std::vector<uint8_t>& service_data, - const std::vector<uint8_t>& manufacturer_data, - bool transmit_name) { - // std::vector<uint8_t> id_data; - // const auto& mutable_manufacturer_data = manufacturer_data; - // const auto& mutable_service_data = service_data; - - // for (const Uuid &id : ids) { - // const auto le_id = id.To128BitLE(); - // id_data.insert(id_data.end(), le_id.begin(), le_id.end()); - // } - - std::lock_guard<std::mutex> lock(internal_->lock); - - // Setup our advertisement. This has no callback. - internal_->gatt->advertiser->SetData(0, false, /* beacon, not scan response */ - {}, base::DoNothing()); - // transmit_name, /* name */ - // 2, 2, interval - // mutable_manufacturer_data, - // mutable_service_data, - // id_data); - return true; -} - -bool Server::SetScanResponse(const std::vector<Uuid>& ids, - const std::vector<uint8_t>& service_data, - const std::vector<uint8_t>& manufacturer_data, - bool transmit_name) { - // std::vector<uint8_t> id_data; - // const auto& mutable_manufacturer_data = manufacturer_data; - // const auto& mutable_service_data = service_data; - - // for (const Uuid &id : ids) { - // const auto le_id = id.To128BitLE(); - // id_data.insert(id_data.end(), le_id.begin(), le_id.end()); - // } - - std::lock_guard<std::mutex> lock(internal_->lock); - - // Setup our advertisement. This has no callback. - internal_->gatt->advertiser->SetData(0, true, /* scan response */ - {}, base::DoNothing()); - // transmit_name, /* name */ - // false, /* no txpower */ - // 2, 2, interval - // 0, /* appearance */ - // mutable_manufacturer_data, - // mutable_service_data, - // id_data); - return true; -} - -bool Server::AddCharacteristic(const Uuid& id, int properties, - int permissions) { - std::unique_lock<std::mutex> lock(internal_->lock); - bt_status_t btstat = - internal_->AddCharacteristic(id, properties, permissions); - if (btstat != BT_STATUS_SUCCESS) { - LOG_ERROR("Failed to add characteristic to service: 0x%04x", - internal_->service_handle); - return false; - } - internal_->api_synchronize.wait(lock); - const int handle = internal_->uuid_to_attribute[id]; - internal_->characteristics[handle].notify = properties & kPropertyNotify; - return true; -} - -bool Server::AddBlob(const Uuid& id, const Uuid& control_id, int properties, - int permissions) { - std::unique_lock<std::mutex> lock(internal_->lock); - - // First, add the primary attribute (characteristic value) - bt_status_t btstat = - internal_->AddCharacteristic(id, properties, permissions); - if (btstat != BT_STATUS_SUCCESS) { - LOG_ERROR("Failed to set scan response data"); - return false; - } - - // Next, add the secondary attribute (blob control). - // Control attributes have fixed permissions/properties. - // Remember position at which blob was added. - blob_index.insert(pending_svc_decl.size()); - btstat = - internal_->AddCharacteristic(control_id, kPropertyRead | kPropertyWrite, - kPermissionRead | kPermissionWrite); - - return true; -} - -bool Server::Start() { - std::unique_lock<std::mutex> lock(internal_->lock); - bt_status_t btstat = internal_->gatt->server->add_service( - internal_->server_if, pending_svc_decl.data(), pending_svc_decl.size()); - if (btstat != BT_STATUS_SUCCESS) { - LOG_ERROR("Failed to start service with handle: 0x%04x", - internal_->service_handle); - return false; - } - internal_->api_synchronize.wait(lock); - return true; -} - -bool Server::Stop() { - std::unique_lock<std::mutex> lock(internal_->lock); - bt_status_t btstat = internal_->gatt->server->stop_service( - internal_->server_if, internal_->service_handle); - if (btstat != BT_STATUS_SUCCESS) { - LOG_ERROR("Failed to stop service with handle: 0x%04x", - internal_->service_handle); - return false; - } - internal_->api_synchronize.wait(lock); - return true; -} - -bool Server::ScanEnable() { - internal_->gatt->scanner->Scan(true); - return true; -} - -bool Server::ScanDisable() { - internal_->gatt->scanner->Scan(false); - return true; -} - -bool Server::GetScanResults(ScanResults* results) { - std::lock_guard<std::mutex> lock(internal_->lock); - *results = internal_->scan_results; - return true; -} - -bool Server::SetCharacteristicValue(const Uuid& id, - const std::vector<uint8_t>& value) { - std::lock_guard<std::mutex> lock(internal_->lock); - const int attribute_id = internal_->uuid_to_attribute[id]; - Characteristic& ch = internal_->characteristics[attribute_id]; - ch.next_blob = value; - ch.next_blob_pending = true; - - if (!ch.notify) return true; - - std::vector<uint8_t> ind_value = {0}; - for (auto connection : internal_->connections) { - internal_->gatt->server->send_indication(internal_->server_if, attribute_id, - connection, true, ind_value.data(), - ind_value.size()); - } - return true; -} - -bool Server::GetCharacteristicValue(const Uuid& id, - std::vector<uint8_t>* value) { - std::lock_guard<std::mutex> lock(internal_->lock); - const int attribute_id = internal_->uuid_to_attribute[id]; - *value = internal_->characteristics[attribute_id].blob; - return true; -} - -} // namespace gatt -} // namespace bluetooth diff --git a/system/service/gatt_server_old.h b/system/service/gatt_server_old.h deleted file mode 100644 index 546f164f3a..0000000000 --- a/system/service/gatt_server_old.h +++ /dev/null @@ -1,126 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#pragma once - -#include <bluetooth/uuid.h> -#include <array> -#include <memory> -#include <unordered_map> -#include <vector> - -#include "hardware/bluetooth.h" -#include "hardware/bt_gatt.h" - -namespace bluetooth { -namespace gatt { - -// Attribute permission values -const int kPermissionRead = 0x1; -const int kPermissionReadEncrypted = 0x2; -const int kPermissionReadEncryptedMitm = 0x4; -const int kPermissionWrite = 0x10; -const int kPermissionWriteEnecrypted = 0x20; -const int KPermissionWriteEncryptedMitm = 0x40; -const int kPermissionWriteSigned = 0x80; -const int kPermissionWriteSignedMitm = 0x100; - -// GATT characteristic properties bit-field values -const int kPropertyBroadcast = 0x1; -const int kPropertyRead = 0x2; -const int kPropertyWriteNoResponse = 0x4; -const int kPropertyWrite = 0x8; -const int kPropertyNotify = 0x10; -const int kPropertyIndicate = 0x20; -const int kPropertySignedWrite = 0x40; -const int kPropertyExtendedProps = 0x80; - -// A mapping from string bluetooth addresses to RSSI measurements. -typedef std::unordered_map<std::string, int> ScanResults; - -// TODO(armansito): This should be a private internal class though I don't see -// why we even need this class. Instead it should probably be merged into -// Server. -struct ServerInternals; - -// Server is threadsafe and internally locked. -// Asynchronous IO is identified via a gatt_pipe FD, -// and synchronously read with 'GetCharacteristicValue' -// -// ****DEPRECATED**** -// -// TODO(armansito): This class has been deprecated and is being replaced by -// bluetooth::GattServer. We will remove this entirely once the new code is -// ready. -class Server { - public: - Server(); - ~Server(); - - // Register GATT interface, initialize internal state, - // and open a pipe for characteristic write notification. - bool Initialize(const Uuid& service_id, int* gatt_pipe); - - // Control the content of service advertisement. - bool SetAdvertisement(const std::vector<Uuid>& ids, - const std::vector<uint8_t>& service_data, - const std::vector<uint8_t>& manufacturer_data, - bool transmit_name); - - // Control the content of service scan response. - bool SetScanResponse(const std::vector<Uuid>& ids, - const std::vector<uint8_t>& service_data, - const std::vector<uint8_t>& manufacturer_data, - bool transmit_name); - - // Add an ordinary characteristic for reading and/or writing. - bool AddCharacteristic(const Uuid& id, int properties, int permissions); - - // Add a special 'blob' characteristic with a corresponding control - // attribute to manipulate which part of the blob the attribute represents. - bool AddBlob(const Uuid& id, const Uuid& control_id, int properties, - int permissions); - - // Put a new value into a characeteristic. - // It will be read from a client starting at the next 0-offset read. - bool SetCharacteristicValue(const Uuid& id, - const std::vector<uint8_t>& value); - - // Get the current value of a characteristic. - bool GetCharacteristicValue(const Uuid& id, std::vector<uint8_t>* value); - - // Start this service. Activate advertisements, allow connections. - // Characteristics should all be created before this. - bool Start(); - - // Cease advertisements and disallow connections. - bool Stop(); - - // Enable LE scan. Scan results will be cached internally. - bool ScanEnable(); - - // Disable LE scan. - bool ScanDisable(); - - // Copy out the cached scan results. - bool GetScanResults(ScanResults* results); - - private: - // Internal data. - std::unique_ptr<ServerInternals> internal_; -}; - -} // namespace gatt -} // namespace bluetooth diff --git a/system/service/hal/bluetooth_av_interface.cc b/system/service/hal/bluetooth_av_interface.cc deleted file mode 100644 index c86a992535..0000000000 --- a/system/service/hal/bluetooth_av_interface.cc +++ /dev/null @@ -1,394 +0,0 @@ -// -// Copyright 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/hal/bluetooth_av_interface.h" - -#include <base/logging.h> -#include <base/memory/ptr_util.h> -#include <base/observer_list.h> - -#include <shared_mutex> - -#include "abstract_observer_list.h" -#include "service/hal/bluetooth_interface.h" -#include "types/raw_address.h" - -namespace bluetooth { -namespace hal { - -namespace { - -BluetoothAvInterface* g_interface = nullptr; - -#if defined(OS_GENERIC) && defined(_LIBCPP_VERSION) && (_LIBCPP_VERSION < 3500) -using shared_mutex_impl = std::shared_mutex; -#else -using shared_mutex_impl = std::shared_timed_mutex; -#endif - -// Mutex used by callbacks to access |g_interface|. If we initialize or clean it -// use unique_lock. If only accessing |g_interface| use shared lock. -shared_mutex_impl g_instance_lock; - -btbase::AbstractObserverList<BluetoothAvInterface::A2dpSourceObserver>* -GetA2dpSourceObservers(); -btbase::AbstractObserverList<BluetoothAvInterface::A2dpSinkObserver>* -GetA2dpSinkObservers(); - -#define VERIFY_INTERFACE_OR_RETURN(...) \ - do { \ - if (!g_interface) { \ - LOG(WARNING) << "Callback received while |g_interface| is NULL"; \ - return __VA_ARGS__; \ - } \ - } while (0) - -} // namespace - -void SourceConnectionStateCallback(const RawAddress& bd_addr, - btav_connection_state_t state, - const btav_error_t& error) { - std::shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - - for (auto& observer : *GetA2dpSourceObservers()) { - observer.ConnectionStateCallback(g_interface, bd_addr, state); - } -} - -void SourceAudioStateCallback(const RawAddress& bd_addr, - btav_audio_state_t state) { - std::shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetA2dpSourceObservers()) { - observer.AudioStateCallback(g_interface, bd_addr, state); - } -} - -void SourceAudioConfigCallback( - const RawAddress& bd_addr, btav_a2dp_codec_config_t codec_config, - std::vector<btav_a2dp_codec_config_t> codecs_local_capabilities, - std::vector<btav_a2dp_codec_config_t> codecs_selectable_capabilities) { - std::shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetA2dpSourceObservers()) { - observer.AudioConfigCallback(g_interface, bd_addr, codec_config, - codecs_local_capabilities, - codecs_selectable_capabilities); - } -} - -bool SourceMandatoryCodecPreferredCallback(const RawAddress& bd_addr) { - VERIFY_INTERFACE_OR_RETURN(false); - // The mandatory codec is preferred only when all observers disable their - // optional codecs. - for (auto& observer : *GetA2dpSourceObservers()) { - if (!observer.MandatoryCodecPreferredCallback(g_interface, bd_addr)) - return false; - } - return true; -} - -void SinkConnectionStateCallback(const RawAddress& bd_addr, - btav_connection_state_t state, - const btav_error_t& error) { - std::shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetA2dpSinkObservers()) { - observer.ConnectionStateCallback(g_interface, bd_addr, state); - } -} - -void SinkAudioStateCallback(const RawAddress& bd_addr, - btav_audio_state_t state) { - std::shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetA2dpSinkObservers()) { - observer.AudioStateCallback(g_interface, bd_addr, state); - } -} - -void SinkAudioConfigCallback(const RawAddress& bd_addr, uint32_t sample_rate, - uint8_t channel_count) { - std::shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetA2dpSinkObservers()) { - observer.AudioConfigCallback(g_interface, bd_addr, sample_rate, - channel_count); - } -} - -btav_source_callbacks_t av_source_callbacks = { - .size = sizeof(btav_source_callbacks_t), - .connection_state_cb = SourceConnectionStateCallback, - .audio_state_cb = SourceAudioStateCallback, - .audio_config_cb = SourceAudioConfigCallback, - .mandatory_codec_preferred_cb = SourceMandatoryCodecPreferredCallback, -}; - -btav_sink_callbacks_t av_sink_callbacks = { - .size = sizeof(btav_sink_callbacks_t), - .connection_state_cb = SinkConnectionStateCallback, - .audio_state_cb = SinkAudioStateCallback, - .audio_config_cb = SinkAudioConfigCallback, -}; - -class BluetoothAvInterfaceImpl : public BluetoothAvInterface { - public: - BluetoothAvInterfaceImpl() = default; - BluetoothAvInterfaceImpl(const BluetoothAvInterfaceImpl&) = delete; - BluetoothAvInterfaceImpl& operator=(const BluetoothAvInterfaceImpl&) = delete; - - ~BluetoothAvInterfaceImpl() override { - A2dpSinkDisable(); - A2dpSourceDisable(); - } - - bool A2dpSourceEnable( - std::vector<btav_a2dp_codec_config_t> codec_priorities) override { - if (source_enabled_) { - return true; - } - - // Right now we only support one connected audio device. - int max_connected_audio_devices = 1; - std::vector<btav_a2dp_codec_config_t> offloading_preference(0); - if (hal_source_iface_->init( - &av_source_callbacks, max_connected_audio_devices, - std::move(codec_priorities), - std::move(offloading_preference)) != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to initialize HAL A2DP source interface"; - return false; - } - source_enabled_ = true; - return true; - } - - void A2dpSourceDisable() override { - if (!source_enabled_) { - return; - } - - hal_source_iface_->cleanup(); - source_enabled_ = false; - } - - bool A2dpSinkEnable() override { - if (sink_enabled_) { - return true; - } - - // Right now we only support one connected audio device. - int max_connected_audio_devices = 1; - if (hal_sink_iface_->init(&av_sink_callbacks, - max_connected_audio_devices) != - BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to initialize HAL A2DP sink interface"; - return false; - } - sink_enabled_ = true; - return true; - } - - void A2dpSinkDisable() override { - if (!sink_enabled_) { - return; - } - hal_sink_iface_->cleanup(); - sink_enabled_ = false; - } - - void AddA2dpSourceObserver(A2dpSourceObserver* observer) override { - a2dp_source_observers_.AddObserver(observer); - } - - void RemoveA2dpSourceObserver(A2dpSourceObserver* observer) override { - a2dp_source_observers_.RemoveObserver(observer); - } - - void AddA2dpSinkObserver(A2dpSinkObserver* observer) override { - a2dp_sink_observers_.AddObserver(observer); - } - - void RemoveA2dpSinkObserver(A2dpSinkObserver* observer) override { - a2dp_sink_observers_.RemoveObserver(observer); - } - - const btav_source_interface_t* GetA2dpSourceHALInterface() override { - return hal_source_iface_; - } - - const btav_sink_interface_t* GetA2dpSinkHALInterface() override { - return hal_sink_iface_; - } - - bool Initialize() { - const bt_interface_t* bt_iface = - BluetoothInterface::Get()->GetHALInterface(); - CHECK(bt_iface); - - const auto* hal_source_iface = - reinterpret_cast<const btav_source_interface_t*>( - bt_iface->get_profile_interface(BT_PROFILE_ADVANCED_AUDIO_ID)); - if (!hal_source_iface) { - LOG(ERROR) << "Failed to obtain A2DP source interface handle"; - return false; - } - - const auto* hal_sink_iface = reinterpret_cast<const btav_sink_interface_t*>( - bt_iface->get_profile_interface(BT_PROFILE_ADVANCED_AUDIO_SINK_ID)); - if (!hal_sink_iface) { - LOG(ERROR) << "Failed to obtain A2DP sink interface handle"; - return false; - } - - hal_sink_iface_ = hal_sink_iface; - hal_source_iface_ = hal_source_iface; - - // Only initialize the sink interface. - return A2dpSinkEnable(); - } - - btbase::AbstractObserverList<A2dpSourceObserver>* source_observers() { - return &a2dp_source_observers_; - } - - btbase::AbstractObserverList<A2dpSinkObserver>* sink_observers() { - return &a2dp_sink_observers_; - } - - private: - btbase::AbstractObserverList<A2dpSourceObserver> a2dp_source_observers_; - btbase::AbstractObserverList<A2dpSinkObserver> a2dp_sink_observers_; - - const btav_source_interface_t* hal_source_iface_ = nullptr; - const btav_sink_interface_t* hal_sink_iface_ = nullptr; - - bool source_enabled_ = false; - bool sink_enabled_ = false; -}; - -namespace { - -btbase::AbstractObserverList<BluetoothAvInterface::A2dpSourceObserver>* -GetA2dpSourceObservers() { - CHECK(g_interface); - return static_cast<BluetoothAvInterfaceImpl*>(g_interface) - ->source_observers(); -} - -btbase::AbstractObserverList<BluetoothAvInterface::A2dpSinkObserver>* -GetA2dpSinkObservers() { - CHECK(g_interface); - return static_cast<BluetoothAvInterfaceImpl*>(g_interface)->sink_observers(); -} - -} // namespace - -void BluetoothAvInterface::A2dpSourceObserver::ConnectionStateCallback( - BluetoothAvInterface* iface, const RawAddress& bd_addr, - btav_connection_state_t state) { - // Do nothing. -} - -void BluetoothAvInterface::A2dpSourceObserver::AudioStateCallback( - BluetoothAvInterface* iface, const RawAddress& bd_addr, - btav_audio_state_t state) { - // Do nothing. -} - -void BluetoothAvInterface::A2dpSourceObserver::AudioConfigCallback( - BluetoothAvInterface* iface, const RawAddress& bd_addr, - const btav_a2dp_codec_config_t& codec_config, - const std::vector<btav_a2dp_codec_config_t> codecs_local_capabilities, - const std::vector<btav_a2dp_codec_config_t> - codecs_selectable_capabilities) { - // Do nothing. -} - -bool BluetoothAvInterface::A2dpSourceObserver::MandatoryCodecPreferredCallback( - BluetoothAvInterface* iface, const RawAddress& bd_addr) { - // Do nothing. - return false; -} - -void BluetoothAvInterface::A2dpSinkObserver::ConnectionStateCallback( - BluetoothAvInterface* iface, const RawAddress& bd_addr, - btav_connection_state_t state) { - // Do nothing. -} - -void BluetoothAvInterface::A2dpSinkObserver::AudioStateCallback( - BluetoothAvInterface* iface, const RawAddress& bd_addr, - btav_audio_state_t state) { - // Do nothing. -} - -void BluetoothAvInterface::A2dpSinkObserver::AudioConfigCallback( - BluetoothAvInterface* iface, const RawAddress& bd_addr, - uint32_t sample_rate, uint8_t channel_count) { - // Do nothing. -} - -// static -bool BluetoothAvInterface::Initialize() { - std::unique_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(!g_interface); - - auto impl = std::make_unique<BluetoothAvInterfaceImpl>(); - if (!impl->Initialize()) { - LOG(ERROR) << "Failed to initialize BluetoothAvInterface"; - return false; - } - - g_interface = impl.release(); - return true; -} - -// static -void BluetoothAvInterface::CleanUp() { - std::unique_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(g_interface); - - delete g_interface; - g_interface = nullptr; -} - -// static -bool BluetoothAvInterface::IsInitialized() { - std::shared_lock<shared_mutex_impl> lock(g_instance_lock); - return g_interface != nullptr; -} - -// static -void BluetoothAvInterface::InitializeForTesting( - BluetoothAvInterface* test_instance) { - std::unique_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(test_instance); - CHECK(!g_interface); - - g_interface = test_instance; -} - -// static -BluetoothAvInterface* BluetoothAvInterface::Get() { - std::shared_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(g_interface); - return g_interface; -} - -} // namespace hal -} // namespace bluetooth diff --git a/system/service/hal/bluetooth_av_interface.h b/system/service/hal/bluetooth_av_interface.h deleted file mode 100644 index 4f0b4773e8..0000000000 --- a/system/service/hal/bluetooth_av_interface.h +++ /dev/null @@ -1,99 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <hardware/bluetooth.h> -#include <hardware/bt_av.h> - -#include <vector> - -#include "types/raw_address.h" - -namespace bluetooth { -namespace hal { - -class BluetoothAvInterface { - public: - class A2dpSourceObserver { - public: - virtual void ConnectionStateCallback(BluetoothAvInterface* iface, - const RawAddress& bd_addr, - btav_connection_state_t state); - virtual void AudioStateCallback(BluetoothAvInterface* iface, - const RawAddress& bd_addr, - btav_audio_state_t state); - virtual void AudioConfigCallback( - BluetoothAvInterface* iface, const RawAddress& bd_addr, - const btav_a2dp_codec_config_t& codec_config, - const std::vector<btav_a2dp_codec_config_t> codecs_local_capabilities, - const std::vector<btav_a2dp_codec_config_t> - codecs_selectable_capabilities); - virtual bool MandatoryCodecPreferredCallback(BluetoothAvInterface* iface, - const RawAddress& bd_addr); - - protected: - virtual ~A2dpSourceObserver() = default; - }; - - class A2dpSinkObserver { - public: - virtual void ConnectionStateCallback(BluetoothAvInterface* iface, - const RawAddress& bd_addr, - btav_connection_state_t state); - virtual void AudioStateCallback(BluetoothAvInterface* iface, - const RawAddress& bd_addr, - btav_audio_state_t state); - virtual void AudioConfigCallback(BluetoothAvInterface* iface, - const RawAddress& bd_addr, - uint32_t sample_rate, - uint8_t channel_count); - - protected: - virtual ~A2dpSinkObserver() = default; - }; - - static bool Initialize(); - static void CleanUp(); - static bool IsInitialized(); - static void InitializeForTesting(BluetoothAvInterface* test_instance); - - static BluetoothAvInterface* Get(); - - virtual bool A2dpSourceEnable( - std::vector<btav_a2dp_codec_config_t> codec_priorities) = 0; - virtual void A2dpSourceDisable() = 0; - virtual bool A2dpSinkEnable() = 0; - virtual void A2dpSinkDisable() = 0; - - virtual void AddA2dpSourceObserver(A2dpSourceObserver* observer) = 0; - virtual void RemoveA2dpSourceObserver(A2dpSourceObserver* observer) = 0; - virtual void AddA2dpSinkObserver(A2dpSinkObserver* observer) = 0; - virtual void RemoveA2dpSinkObserver(A2dpSinkObserver* observer) = 0; - - virtual const btav_source_interface_t* GetA2dpSourceHALInterface() = 0; - virtual const btav_sink_interface_t* GetA2dpSinkHALInterface() = 0; - - protected: - BluetoothAvInterface() = default; - BluetoothAvInterface(const BluetoothAvInterface&) = delete; - BluetoothAvInterface& operator=(const BluetoothAvInterface&) = delete; - - virtual ~BluetoothAvInterface() = default; -}; - -} // namespace hal -} // namespace bluetooth diff --git a/system/service/hal/bluetooth_avrcp_interface.cc b/system/service/hal/bluetooth_avrcp_interface.cc deleted file mode 100644 index cbb0317041..0000000000 --- a/system/service/hal/bluetooth_avrcp_interface.cc +++ /dev/null @@ -1,895 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/hal/bluetooth_avrcp_interface.h" - -#include <base/logging.h> -#include <base/observer_list.h> - -#include <mutex> -#include <shared_mutex> - -#include "abstract_observer_list.h" -#include "service/hal/bluetooth_interface.h" -#include "service/logging_helpers.h" -#include "types/raw_address.h" - -using std::lock_guard; -using std::mutex; -using std::shared_lock; -using std::unique_lock; -#if defined(OS_GENERIC) && defined(_LIBCPP_VERSION) && (_LIBCPP_VERSION < 3500) -using shared_mutex_impl = std::shared_mutex; -#else -using shared_mutex_impl = std::shared_timed_mutex; -#endif - -namespace bluetooth { -namespace hal { - -namespace { - -// The global BluetoothAvrcpInterface instance. -BluetoothAvrcpInterface* g_interface = nullptr; - -// Mutex used by callbacks to access |g_interface|. If we initialize or clean it -// use unique_lock. If only accessing |g_interface| use shared lock. -// TODO(jpawlowski): this should be just shared_mutex, as we currently don't use -// timed methods. Change to shared_mutex when we upgrade to C++14 -shared_mutex_impl g_instance_lock; - -// Helper for obtaining the observer lists. This is forward declared here -// and defined below since it depends on BluetoothInterfaceImpl. -btbase::AbstractObserverList<BluetoothAvrcpInterface::TargetObserver>* -GetTargetObservers(); - -btbase::AbstractObserverList<BluetoothAvrcpInterface::ControlObserver>* -GetControlObservers(); - -#define VERIFY_INTERFACE_OR_RETURN() \ - do { \ - if (!g_interface) { \ - LOG(WARNING) << "Callback received while |g_interface| is NULL"; \ - return; \ - } \ - } while (0) - -void RemoteFeaturesCallback(const RawAddress& bd_addr, - btrc_remote_features_t features) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.RemoteFeaturesCallback(bd_addr, features); - } -} - -void GetPlayStatusCallback(const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.GetPlayStatusCallback(bd_addr); - } -} - -void ListPlayerAppAttrCallback(const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.ListPlayerAppAttrCallback(bd_addr); - } -} - -void ListPlayerAppValuesCallback(btrc_player_attr_t attr_id, - const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.ListPlayerAppValuesCallback(attr_id, bd_addr); - } -} - -void GetPlayerAppValueCallback(uint8_t num_attr, btrc_player_attr_t* p_attrs, - const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.GetPlayerAppValueCallback(num_attr, p_attrs, bd_addr); - } -} - -void GetPlayerAppAttrsTextCallback(uint8_t num_attr, - btrc_player_attr_t* p_attrs, - const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.GetPlayerAppAttrsTextCallback(num_attr, p_attrs, bd_addr); - } -} - -void GetPlayerAppValuesTextCallback(uint8_t attr_id, uint8_t num_val, - uint8_t* p_vals, - const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.GetPlayerAppValuesTextCallback(attr_id, num_val, p_vals, bd_addr); - } -} - -void SetPlayerAppValueCallback(btrc_player_settings_t* p_vals, - const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.SetPlayerAppValueCallback(p_vals, bd_addr); - } -} - -void GetElementAttrCallback(uint8_t num_attr, btrc_media_attr_t* p_attrs, - const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.GetElementAttrCallback(num_attr, p_attrs, bd_addr); - } -} - -void RegisterNotificationCallback(btrc_event_id_t event_id, uint32_t param, - const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.RegisterNotificationCallback(event_id, param, bd_addr); - } -} - -void VolumeChangeCallback(uint8_t volume, uint8_t ctype, - const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.VolumeChangeCallback(volume, ctype, bd_addr); - } -} - -void PassthroughCmdCallback(int id, int key_state, const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.PassthroughCmdCallback(id, key_state, bd_addr); - } -} - -void SetAddressedPlayerCallback(uint16_t player_id, const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.SetAddressedPlayerCallback(player_id, bd_addr); - } -} - -void SetBrowsedPlayerCallback(uint16_t player_id, const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.SetBrowsedPlayerCallback(player_id, bd_addr); - } -} - -void GetFolderItemsCallback(uint8_t scope, uint32_t start_item, - uint32_t end_item, uint8_t num_attr, - uint32_t* p_attr_ids, const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.GetFolderItemsCallback(scope, start_item, end_item, num_attr, - p_attr_ids, bd_addr); - } -} - -void ChangePathCallback(uint8_t direction, uint8_t* folder_uid, - const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.ChangePathCallback(direction, folder_uid, bd_addr); - } -} - -void GetItemAttrCallback(uint8_t scope, uint8_t* uid, uint16_t uid_counter, - uint8_t num_attr, btrc_media_attr_t* p_attrs, - const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.GetItemAttrCallback(scope, uid, uid_counter, num_attr, p_attrs, - bd_addr); - } -} - -void PlayItemCallback(uint8_t scope, uint16_t uid_counter, uint8_t* uid, - const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.PlayItemCallback(scope, uid_counter, uid, bd_addr); - } -} - -void GetTotalNumOfItemsCallback(uint8_t scope, const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.GetTotalNumOfItemsCallback(scope, bd_addr); - } -} - -void SearchCallback(uint16_t charset_id, uint16_t str_len, uint8_t* p_str, - const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.SearchCallback(str_len, p_str, bd_addr); - } -} - -void AddToNowPlayingCallback(uint8_t scope, uint8_t* uid, uint16_t uid_counter, - const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetTargetObservers()) { - observer.AddToNowPlayingCallback(scope, uid, uid_counter, bd_addr); - } -} - -void PassthroughRspCallback(const RawAddress& bd_addr, int id, int key_state) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.PassthroughRspCallback(bd_addr, id, key_state); - } -} - -void GroupnavigationRspCallback(int id, int key_state) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.GroupnavigationRspCallback(id, key_state); - } -} - -void ConnectionStateCallback(bool rc_connect, bool bt_connect, - const RawAddress& bd_addr) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.ConnectionStateCallback(rc_connect, bt_connect, bd_addr); - } -} - -void CtrlGetrcfeaturesCallback(const RawAddress& bd_addr, int features) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.CtrlGetrcfeaturesCallback(bd_addr, features); - } -} - -void CtrlSetplayerapplicationsettingRspCallback(const RawAddress& bd_addr, - uint8_t accepted) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - - for (auto& observer : *GetControlObservers()) { - observer.CtrlSetplayerapplicationsettingRspCallback(bd_addr, accepted); - } -} - -void CtrlPlayerapplicationsettingCallback( - 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) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.CtrlPlayerapplicationsettingCallback(bd_addr, num_attr, app_attrs, - num_ext_attr, ext_attrs); - } -} - -void CtrlPlayerapplicationsettingChangedCallback( - const RawAddress& bd_addr, const btrc_player_settings_t& vals) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.CtrlPlayerapplicationsettingChangedCallback(bd_addr, vals); - } -} - -void CtrlSetabsvolCmdCallback(const RawAddress& bd_addr, uint8_t abs_vol, - uint8_t label) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.CtrlSetabsvolCmdCallback(bd_addr, abs_vol, label); - } -} - -void CtrlRegisternotificationAbsVolCallback(const RawAddress& bd_addr, - uint8_t label) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.CtrlRegisternotificationAbsVolCallback(bd_addr, label); - } -} - -void CtrlTrackChangedCallback(const RawAddress& bd_addr, uint8_t num_attr, - btrc_element_attr_val_t* p_attrs) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.CtrlTrackChangedCallback(bd_addr, num_attr, p_attrs); - } -} - -void CtrlPlayPositionChangedCallback(const RawAddress& bd_addr, - uint32_t song_len, uint32_t song_pos) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.CtrlPlayPositionChangedCallback(bd_addr, song_len, song_pos); - } -} - -void CtrlPlayStatusChangedCallback(const RawAddress& bd_addr, - btrc_play_status_t play_status) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.CtrlPlayStatusChangedCallback(bd_addr, play_status); - } -} - -void CtrlGetFolderItemsCallback(const RawAddress& bd_addr, btrc_status_t status, - const btrc_folder_items_t* folder_items, - uint8_t count) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.CtrlGetFolderItemsCallback(bd_addr, status, folder_items, count); - } -} - -void CtrlChangePathCallback(const RawAddress& bd_addr, uint32_t count) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.CtrlChangePathCallback(bd_addr, count); - } -} - -void CtrlSetBrowsedPlayerCallback(const RawAddress& bd_addr, uint8_t num_items, - uint8_t depth) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.CtrlSetBrowsedPlayerCallback(bd_addr, num_items, depth); - } -} - -void CtrlSetAddressedPlayerCallback(const RawAddress& bd_addr, uint8_t status) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__; - VERIFY_INTERFACE_OR_RETURN(); - for (auto& observer : *GetControlObservers()) { - observer.CtrlSetAddressedPlayerCallback(bd_addr, status); - } -} - -btrc_callbacks_t target_callbacks = { - .size = sizeof(btrc_callbacks_t), - .remote_features_cb = RemoteFeaturesCallback, - .get_play_status_cb = GetPlayStatusCallback, - .list_player_app_attr_cb = ListPlayerAppAttrCallback, - .list_player_app_values_cb = ListPlayerAppValuesCallback, - .get_player_app_value_cb = GetPlayerAppValueCallback, - .get_player_app_attrs_text_cb = GetPlayerAppAttrsTextCallback, - .get_player_app_values_text_cb = GetPlayerAppValuesTextCallback, - .set_player_app_value_cb = SetPlayerAppValueCallback, - .get_element_attr_cb = GetElementAttrCallback, - .register_notification_cb = RegisterNotificationCallback, - .volume_change_cb = VolumeChangeCallback, - .passthrough_cmd_cb = PassthroughCmdCallback, - .set_addressed_player_cb = SetAddressedPlayerCallback, - .set_browsed_player_cb = SetBrowsedPlayerCallback, - .get_folder_items_cb = GetFolderItemsCallback, - .change_path_cb = ChangePathCallback, - .get_item_attr_cb = GetItemAttrCallback, - .play_item_cb = PlayItemCallback, - .get_total_num_of_items_cb = GetTotalNumOfItemsCallback, - .search_cb = SearchCallback, - .add_to_now_playing_cb = AddToNowPlayingCallback, -}; - -btrc_ctrl_callbacks_t control_callbacks = { - .size = sizeof(btrc_ctrl_callbacks_t), - .passthrough_rsp_cb = PassthroughRspCallback, - .groupnavigation_rsp_cb = GroupnavigationRspCallback, - .connection_state_cb = ConnectionStateCallback, - .getrcfeatures_cb = CtrlGetrcfeaturesCallback, - .setplayerappsetting_rsp_cb = CtrlSetplayerapplicationsettingRspCallback, - .playerapplicationsetting_cb = CtrlPlayerapplicationsettingCallback, - .playerapplicationsetting_changed_cb = - CtrlPlayerapplicationsettingChangedCallback, - .setabsvol_cmd_cb = CtrlSetabsvolCmdCallback, - .registernotification_absvol_cb = CtrlRegisternotificationAbsVolCallback, - .track_changed_cb = CtrlTrackChangedCallback, - .play_position_changed_cb = CtrlPlayPositionChangedCallback, - .play_status_changed_cb = CtrlPlayStatusChangedCallback, - .get_folder_items_cb = CtrlGetFolderItemsCallback, - .change_folder_path_cb = CtrlChangePathCallback, - .set_browsed_player_cb = CtrlSetBrowsedPlayerCallback, - .set_addressed_player_cb = CtrlSetAddressedPlayerCallback, -}; - -} // namespace - -// BluetoothAvrcpInterface implementation for production. -class BluetoothAvrcpInterfaceImpl : public BluetoothAvrcpInterface { - public: - BluetoothAvrcpInterfaceImpl() : control_iface_(nullptr) {} - - BluetoothAvrcpInterfaceImpl(const BluetoothAvrcpInterfaceImpl&) = delete; - BluetoothAvrcpInterfaceImpl& operator=(const BluetoothAvrcpInterfaceImpl&) = - delete; - - ~BluetoothAvrcpInterfaceImpl() override { - if (control_iface_) control_iface_->cleanup(); - } - - bool AvrcpControlEnable() override { - if (control_enabled_) { - return true; - } - - if (control_iface_->init(&control_callbacks) != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to initialize HAL AVRCP control interface"; - return false; - } - - control_enabled_ = true; - return true; - } - - void AvrcpControlDisable() override { - if (!control_enabled_) { - return; - } - - control_iface_->cleanup(); - control_enabled_ = false; - } - - bool AvrcpTargetEnable() override { - if (target_enabled_) { - return true; - } - - if (target_iface_->init(&target_callbacks) != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to initialize HAL AVRCP target interface"; - return false; - } - - target_enabled_ = true; - return true; - } - - void AvrcpTargetDisable() override { - if (!target_enabled_) { - return; - } - - target_iface_->cleanup(); - target_enabled_ = false; - } - - void AddTargetObserver(TargetObserver* observer) override { - target_observers_.AddObserver(observer); - } - - void RemoveTargetObserver(TargetObserver* observer) override { - target_observers_.RemoveObserver(observer); - } - - void AddControlObserver(ControlObserver* observer) override { - control_observers_.AddObserver(observer); - } - - void RemoveControlObserver(ControlObserver* observer) override { - control_observers_.RemoveObserver(observer); - } - - const btrc_interface_t* GetTargetHALInterface() const override { - return target_iface_; - } - - const btrc_ctrl_interface_t* GetControlHALInterface() const override { - return control_iface_; - } - - // Initialize the interface. - bool Initialize() { - const bt_interface_t* bt_iface = - BluetoothInterface::Get()->GetHALInterface(); - CHECK(bt_iface); - - auto* target_iface = reinterpret_cast<const btrc_interface_t*>( - bt_iface->get_profile_interface(BT_PROFILE_AV_RC_ID)); - if (!target_iface) { - LOG(ERROR) << "Failed to obtain HAL AVRCP target interface handle"; - return false; - } - - auto* control_iface = reinterpret_cast<const btrc_ctrl_interface_t*>( - bt_iface->get_profile_interface(BT_PROFILE_AV_RC_CTRL_ID)); - if (!control_iface) { - LOG(ERROR) << "Failed to obtain HAL AVRCP control interface handle"; - return false; - } - - control_iface_ = control_iface; - target_iface_ = target_iface; - - // Only initialize the control interface. - return AvrcpControlEnable(); - } - - btbase::AbstractObserverList<TargetObserver>* target_observers() { - return &target_observers_; - } - - btbase::AbstractObserverList<ControlObserver>* control_observers() { - return &control_observers_; - } - - private: - // List of observers that are interested in notifications from us. - // We're not using a base::ObserverListThreadSafe, which it posts observer - // events automatically on the origin threads, as we want to avoid that - // overhead and simply forward the events to the upper layer. - btbase::AbstractObserverList<TargetObserver> target_observers_; - btbase::AbstractObserverList<ControlObserver> control_observers_; - - // The HAL handle obtained from the shared library. We hold a weak reference - // to this since the actual data resides in the shared Bluetooth library. - const btrc_interface_t* target_iface_ = nullptr; - const btrc_ctrl_interface_t* control_iface_ = nullptr; - - bool control_enabled_ = false; - bool target_enabled_ = false; -}; - -namespace { - -btbase::AbstractObserverList<BluetoothAvrcpInterface::TargetObserver>* -GetTargetObservers() { - CHECK(g_interface); - return static_cast<BluetoothAvrcpInterfaceImpl*>(g_interface) - ->target_observers(); -} - -btbase::AbstractObserverList<BluetoothAvrcpInterface::ControlObserver>* -GetControlObservers() { - CHECK(g_interface); - return static_cast<BluetoothAvrcpInterfaceImpl*>(g_interface) - ->control_observers(); -} - -} // namespace - -void BluetoothAvrcpInterface::TargetObserver::RemoteFeaturesCallback( - const RawAddress& bd_addr, btrc_remote_features_t features) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::GetPlayStatusCallback( - const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::ListPlayerAppAttrCallback( - const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::ListPlayerAppValuesCallback( - btrc_player_attr_t attr_id, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::GetPlayerAppValueCallback( - uint8_t num_attr, btrc_player_attr_t* p_attrs, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::GetPlayerAppAttrsTextCallback( - uint8_t num_attr, btrc_player_attr_t* p_attrs, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::GetPlayerAppValuesTextCallback( - uint8_t attr_id, uint8_t num_val, uint8_t* p_vals, - const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::SetPlayerAppValueCallback( - btrc_player_settings_t* p_vals, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::GetElementAttrCallback( - uint8_t num_attr, btrc_media_attr_t* p_attrs, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::RegisterNotificationCallback( - btrc_event_id_t event_id, uint32_t param, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::VolumeChangeCallback( - uint8_t volume, uint8_t ctype, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::PassthroughCmdCallback( - int id, int key_state, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::SetAddressedPlayerCallback( - uint16_t player_id, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::SetBrowsedPlayerCallback( - uint16_t player_id, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::GetFolderItemsCallback( - uint8_t scope, uint32_t start_item, uint32_t end_item, uint8_t num_attr, - uint32_t* p_attr_ids, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::ChangePathCallback( - uint8_t direction, uint8_t* folder_uid, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::GetItemAttrCallback( - uint8_t scope, uint8_t* uid, uint16_t uid_counter, uint8_t num_attr, - btrc_media_attr_t* p_attrs, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::PlayItemCallback( - uint8_t scope, uint16_t uid_counter, uint8_t* uid, - const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::GetTotalNumOfItemsCallback( - uint8_t scope, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::SearchCallback( - uint16_t str_len, uint8_t* p_str, const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::TargetObserver::AddToNowPlayingCallback( - uint8_t scope, uint8_t* uid, uint16_t uid_counter, - const RawAddress& bd_addr) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver::PassthroughRspCallback( - const RawAddress& /* bd_addr */, int /* id */, int /* key_state */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver::GroupnavigationRspCallback( - int /* id */, int /* key_state */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver::ConnectionStateCallback( - bool /* rc_connect */, bool /* bt_connect */, - const RawAddress& /* bd_addr */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver::CtrlGetrcfeaturesCallback( - const RawAddress& /* bd_addr */, int /* features */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver:: - CtrlSetplayerapplicationsettingRspCallback(const RawAddress& /* bd_addr */, - uint8_t /* accepted */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver:: - CtrlPlayerapplicationsettingCallback( - 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 */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver:: - CtrlPlayerapplicationsettingChangedCallback( - const RawAddress& /* bd_addr*/, - const btrc_player_settings_t& /* vals */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver::CtrlSetabsvolCmdCallback( - const RawAddress& /* bd_addr */, uint8_t /* abs_vol */, - uint8_t /* label */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver:: - CtrlRegisternotificationAbsVolCallback(const RawAddress& /* bd_addr */, - uint8_t /* label */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver::CtrlTrackChangedCallback( - const RawAddress& /*bd_addr */, uint8_t /* num_attr */, - btrc_element_attr_val_t* /* p_attrs */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver::CtrlPlayPositionChangedCallback( - const RawAddress& /* bd_addr */, uint32_t /* song_len */, - uint32_t /* song_pos */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver::CtrlPlayStatusChangedCallback( - const RawAddress& /* bd_addr */, btrc_play_status_t /* play_status */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver::CtrlGetFolderItemsCallback( - const RawAddress& /* bd_addr */, btrc_status_t /* status */, - const btrc_folder_items_t* /*folder_items */, uint8_t /* count */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver::CtrlChangePathCallback( - const RawAddress& /* bd_addr */, uint32_t /* count */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver::CtrlSetBrowsedPlayerCallback( - const RawAddress& /* bd_addr */, uint8_t /* num_items */, - uint8_t /* depth */) { - // Do nothing. -} - -void BluetoothAvrcpInterface::ControlObserver::CtrlSetAddressedPlayerCallback( - const RawAddress& /* bd_addr */, uint8_t /* status */) { - // Do nothing. -} - -// static -bool BluetoothAvrcpInterface::Initialize() { - unique_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(!g_interface); - - std::unique_ptr<BluetoothAvrcpInterfaceImpl> impl( - new BluetoothAvrcpInterfaceImpl()); - if (!impl->Initialize()) { - LOG(ERROR) << "Failed to initialize BluetoothAvrcpInterface"; - return false; - } - - g_interface = impl.release(); - - return true; -} - -// static -void BluetoothAvrcpInterface::CleanUp() { - unique_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(g_interface); - - delete g_interface; - g_interface = nullptr; -} - -// static -bool BluetoothAvrcpInterface::IsInitialized() { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - - return g_interface != nullptr; -} - -// static -BluetoothAvrcpInterface* BluetoothAvrcpInterface::Get() { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(g_interface); - return g_interface; -} - -// static -void BluetoothAvrcpInterface::InitializeForTesting( - BluetoothAvrcpInterface* test_instance) { - unique_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(test_instance); - CHECK(!g_interface); - - g_interface = test_instance; -} - -} // namespace hal -} // namespace bluetooth diff --git a/system/service/hal/bluetooth_avrcp_interface.h b/system/service/hal/bluetooth_avrcp_interface.h deleted file mode 100644 index 4646880169..0000000000 --- a/system/service/hal/bluetooth_avrcp_interface.h +++ /dev/null @@ -1,180 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <hardware/bluetooth.h> -#include <hardware/bt_rc.h> - -#include "types/raw_address.h" - -namespace bluetooth { -namespace hal { - -class BluetoothAvrcpInterface { - public: - // The HAL interface doesn't allow registering "user data" that carries - // context beyond the callback parameters, forcing implementations to deal - // with global variables. The *Observer interface is to redirect these events - // to interested parties in an object-oriented manner. - class TargetObserver { - public: - virtual ~TargetObserver() = default; - - virtual void RemoteFeaturesCallback(const RawAddress& bd_addr, - btrc_remote_features_t features); - virtual void GetPlayStatusCallback(const RawAddress& bd_addr); - virtual void ListPlayerAppAttrCallback(const RawAddress& bd_addr); - virtual void ListPlayerAppValuesCallback(btrc_player_attr_t attr_id, - const RawAddress& bd_addr); - virtual void GetPlayerAppValueCallback(uint8_t num_attr, - btrc_player_attr_t* p_attrs, - const RawAddress& bd_addr); - virtual void GetPlayerAppAttrsTextCallback(uint8_t num_attr, - btrc_player_attr_t* p_attrs, - const RawAddress& bd_addr); - virtual void GetPlayerAppValuesTextCallback(uint8_t attr_id, - uint8_t num_val, - uint8_t* p_vals, - const RawAddress& bd_addr); - virtual void SetPlayerAppValueCallback(btrc_player_settings_t* p_vals, - const RawAddress& bd_addr); - virtual void GetElementAttrCallback(uint8_t num_attr, - btrc_media_attr_t* p_attrs, - const RawAddress& bd_addr); - virtual void RegisterNotificationCallback(btrc_event_id_t event_id, - uint32_t param, - const RawAddress& bd_addr); - virtual void VolumeChangeCallback(uint8_t volume, uint8_t ctype, - const RawAddress& bd_addr); - virtual void PassthroughCmdCallback(int id, int key_state, - const RawAddress& bd_addr); - virtual void SetAddressedPlayerCallback(uint16_t player_id, - const RawAddress& bd_addr); - virtual void SetBrowsedPlayerCallback(uint16_t player_id, - const RawAddress& bd_addr); - virtual void GetFolderItemsCallback(uint8_t scope, uint32_t start_item, - uint32_t end_item, uint8_t num_attr, - uint32_t* p_attr_ids, - const RawAddress& bd_addr); - virtual void ChangePathCallback(uint8_t direction, uint8_t* folder_uid, - const RawAddress& bd_addr); - virtual void GetItemAttrCallback(uint8_t scope, uint8_t* uid, - uint16_t uid_counter, uint8_t num_attr, - btrc_media_attr_t* p_attrs, - const RawAddress& bd_addr); - virtual void PlayItemCallback(uint8_t scope, uint16_t uid_counter, - uint8_t* uid, const RawAddress& bd_addr); - virtual void GetTotalNumOfItemsCallback(uint8_t scope, - const RawAddress& bd_addr); - virtual void SearchCallback(uint16_t str_len, uint8_t* p_str, - const RawAddress& bd_addr); - virtual void AddToNowPlayingCallback(uint8_t scope, uint8_t* uid, - uint16_t uid_counter, - const RawAddress& bd_addr); - }; - - class ControlObserver { - public: - virtual ~ControlObserver() = default; - - virtual void PassthroughRspCallback(const RawAddress& bd_addr, int id, - int key_state); - virtual void GroupnavigationRspCallback(int id, int key_state); - virtual void ConnectionStateCallback(bool rc_connect, bool bt_connect, - const RawAddress& bd_addr); - virtual void CtrlGetrcfeaturesCallback(const RawAddress& bd_addr, - int features); - virtual void CtrlSetplayerapplicationsettingRspCallback( - const RawAddress& bd_addr, uint8_t accepted); - virtual void CtrlPlayerapplicationsettingCallback( - 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); - virtual void CtrlPlayerapplicationsettingChangedCallback( - const RawAddress& bd_addr, const btrc_player_settings_t& p_vals); - virtual void CtrlSetabsvolCmdCallback(const RawAddress& bd_addr, - uint8_t abs_vol, uint8_t label); - virtual void CtrlRegisternotificationAbsVolCallback( - const RawAddress& bd_addr, uint8_t label); - virtual void CtrlTrackChangedCallback(const RawAddress& bd_addr, - uint8_t num_attr, - btrc_element_attr_val_t* p_attrs); - virtual void CtrlPlayPositionChangedCallback(const RawAddress& bd_addr, - uint32_t song_len, - uint32_t song_pos); - virtual void CtrlPlayStatusChangedCallback(const RawAddress& bd_addr, - btrc_play_status_t play_status); - virtual void CtrlGetFolderItemsCallback( - const RawAddress& bd_addr, btrc_status_t status, - const btrc_folder_items_t* folder_items, uint8_t count); - virtual void CtrlChangePathCallback(const RawAddress& bd_addr, - uint32_t count); - virtual void CtrlSetBrowsedPlayerCallback(const RawAddress& bd_addr, - uint8_t num_items, uint8_t depth); - virtual void CtrlSetAddressedPlayerCallback(const RawAddress& bd_addr, - uint8_t status); - }; - - BluetoothAvrcpInterface(const BluetoothAvrcpInterface&) = delete; - BluetoothAvrcpInterface& operator=(const BluetoothAvrcpInterface&) = delete; - - // Initialize and clean up the BluetoothInterface singleton. Returns false if - // the underlying HAL interface failed to initialize, and true on success. - static bool Initialize(); - - // Shuts down and cleans up the interface. CleanUp must be called on the same - // thread that called Initialize. - static void CleanUp(); - - // Returns true if the interface was initialized and a global singleton has - // been created. - static bool IsInitialized(); - - // Initialize for testing. Use this to inject a test version of - // BluetoothAvrcpInterface. To be used from unit tests only. - static void InitializeForTesting(BluetoothAvrcpInterface* test_instance); - - // Returns the BluetoothAvrcpInterface singleton. If the interface has - // not been initialized, returns nullptr. This method is thread-safe, in that - // it will block if the internal lock is being held by another thread. Don't - // call this re-entrantly from an observer event as this may cause a deadlock. - static BluetoothAvrcpInterface* Get(); - - virtual bool AvrcpControlEnable() = 0; - virtual void AvrcpControlDisable() = 0; - virtual bool AvrcpTargetEnable() = 0; - virtual void AvrcpTargetDisable() = 0; - - // Thread-safety is guaranteed by ObserverList. - virtual void AddTargetObserver(TargetObserver* observer) = 0; - virtual void RemoveTargetObserver(TargetObserver* observer) = 0; - - // Thread-safety is guaranteed by ObserverList. - virtual void AddControlObserver(ControlObserver* observer) = 0; - virtual void RemoveControlObserver(ControlObserver* observer) = 0; - - // The HAL module pointers provided by the shared Bluetooth library - virtual const btrc_interface_t* GetTargetHALInterface() const = 0; - virtual const btrc_ctrl_interface_t* GetControlHALInterface() const = 0; - - protected: - BluetoothAvrcpInterface() = default; - virtual ~BluetoothAvrcpInterface() = default; -}; - -} // namespace hal -} // namespace bluetooth diff --git a/system/service/hal/bluetooth_gatt_interface.cc b/system/service/hal/bluetooth_gatt_interface.cc deleted file mode 100644 index 403786e507..0000000000 --- a/system/service/hal/bluetooth_gatt_interface.cc +++ /dev/null @@ -1,832 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/hal/bluetooth_gatt_interface.h" - -#include <base/logging.h> -#include <base/observer_list.h> - -#include <mutex> -#include <shared_mutex> - -#include "abstract_observer_list.h" -#include "service/hal/bluetooth_interface.h" -#include "service/logging_helpers.h" -#include "types/raw_address.h" - -using std::lock_guard; -using std::unique_lock; -using std::shared_lock; -using std::mutex; -#if defined(OS_GENERIC) && defined(_LIBCPP_VERSION) && (_LIBCPP_VERSION < 3500) -using shared_mutex_impl = std::shared_mutex; -#else -using shared_mutex_impl = std::shared_timed_mutex; -#endif - -namespace bluetooth { -namespace hal { - -namespace { - -// The global BluetoothGattInterface instance. -BluetoothGattInterface* g_interface = nullptr; - -// Mutex used by callbacks to access |g_interface|. If we initialize or clean it -// use unique_lock. If only accessing |g_interface| use shared lock. -// TODO(jpawlowski): this should be just shared_mutex, as we currently don't use -// timed methods. Change to shared_mutex when we upgrade to C++14 -shared_mutex_impl g_instance_lock; - -// Helper for obtaining the observer lists. This is forward declared here -// and defined below since it depends on BluetoothInterfaceImpl. -btbase::AbstractObserverList<BluetoothGattInterface::ScannerObserver>* -GetScannerObservers(); -btbase::AbstractObserverList<BluetoothGattInterface::ClientObserver>* -GetClientObservers(); -btbase::AbstractObserverList<BluetoothGattInterface::ServerObserver>* -GetServerObservers(); - -#define FOR_EACH_SCANNER_OBSERVER(func) \ - for (auto& observer : *GetScannerObservers()) { \ - observer.func; \ - } - -#define FOR_EACH_CLIENT_OBSERVER(func) \ - for (auto& observer : *GetClientObservers()) { \ - observer.func; \ - } - -#define FOR_EACH_SERVER_OBSERVER(func) \ - for (auto& observer : *GetServerObservers()) { \ - observer.func; \ - } - -#define VERIFY_INTERFACE_OR_RETURN() \ - do { \ - if (!g_interface) { \ - LOG(WARNING) << "Callback received while |g_interface| is NULL"; \ - return; \ - } \ - } while (0) - -void RegisterClientCallback(int status, int client_if, - const bluetooth::Uuid& app_uuid) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - status: " << status << " client_if: " << client_if; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_CLIENT_OBSERVER( - RegisterClientCallback(g_interface, status, client_if, app_uuid)); -} - -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<uint8_t> adv_data, - RawAddress* original_bda) { // NOLINT(pass-by-value) - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - CHECK(bda); - - VLOG(2) << __func__ << " - BD_ADDR: " << BtAddrString(bda) - << " RSSI: " << rssi; - FOR_EACH_SCANNER_OBSERVER( - ScanResultCallback(g_interface, *bda, rssi, adv_data)); -} - -void ConnectCallback(int conn_id, int status, int client_if, - const RawAddress& bda) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - - VLOG(2) << __func__ << " - status: " << status << " client_if: " << client_if - << " - BD_ADDR: " << BtAddrString(&bda) << " - conn_id: " << conn_id; - - FOR_EACH_CLIENT_OBSERVER( - ConnectCallback(g_interface, conn_id, status, client_if, bda)); -} - -void DisconnectCallback(int conn_id, int status, int client_if, - const RawAddress& bda) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - - VLOG(2) << __func__ << " - conn_id: " << conn_id << " - status: " << status - << " client_if: " << client_if - << " - BD_ADDR: " << BtAddrString(&bda); - FOR_EACH_CLIENT_OBSERVER( - DisconnectCallback(g_interface, conn_id, status, client_if, bda)); -} - -void SearchCompleteCallback(int conn_id, int status) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - - VLOG(2) << __func__ << " - conn_id: " << conn_id << " - status: " << status; - FOR_EACH_CLIENT_OBSERVER( - SearchCompleteCallback(g_interface, conn_id, status)); -} - -void RegisterForNotificationCallback(int conn_id, int registered, int status, - uint16_t handle) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - - LOG(INFO) << __func__ << " - conn_id: " << conn_id << " - status: " << status - << " - registered: " << registered << " - handle: " << handle; - FOR_EACH_CLIENT_OBSERVER(RegisterForNotificationCallback( - g_interface, conn_id, registered, status, handle)); -} - -void NotifyCallback(int conn_id, const btgatt_notify_params_t& p_data) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - - VLOG(2) << __func__ << " - conn_id: " << conn_id - << " - address: " << BtAddrString(&p_data.bda) - << " - handle: " << p_data.handle << " - len: " << p_data.len - << " - is_notify: " << p_data.is_notify; - - FOR_EACH_CLIENT_OBSERVER(NotifyCallback(g_interface, conn_id, p_data)); -} - -void WriteCharacteristicCallback(int conn_id, int status, uint16_t handle, - uint16_t len, const uint8_t* value) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - - VLOG(2) << __func__ << " - conn_id: " << conn_id << " - status: " << status; - - FOR_EACH_CLIENT_OBSERVER(WriteCharacteristicCallback( - g_interface, conn_id, status, handle, len, value)); -} - -void WriteDescriptorCallback(int conn_id, int status, uint16_t handle, - uint16_t len, const uint8_t* value) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - - VLOG(2) << __func__ << " - conn_id: " << conn_id << " - status: " << status; - - FOR_EACH_CLIENT_OBSERVER(WriteDescriptorCallback(g_interface, conn_id, status, - handle, len, value)); -} - -void MtuChangedCallback(int conn_id, int status, int mtu) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - - VLOG(2) << __func__ << " - conn_id: " << conn_id << " status: " << status - << " mtu: " << mtu; - - FOR_EACH_CLIENT_OBSERVER( - MtuChangedCallback(g_interface, conn_id, status, mtu)); -} - -void GetGattDbCallback(int conn_id, const btgatt_db_element_t* db, int size) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - conn_id: " << conn_id << " size: " << size; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_CLIENT_OBSERVER(GetGattDbCallback(g_interface, conn_id, db, size)); -} - -void ServicesRemovedCallback(int conn_id, uint16_t start_handle, - uint16_t end_handle) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - conn_id: " << conn_id - << " start_handle: " << start_handle << " end_handle: " << end_handle; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_CLIENT_OBSERVER( - ServicesRemovedCallback(g_interface, conn_id, start_handle, end_handle)); -} - -void ServicesAddedCallback(int conn_id, const btgatt_db_element_t& added, - int added_count) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - conn_id: " << conn_id - << " added_count: " << added_count; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_CLIENT_OBSERVER( - ServicesAddedCallback(g_interface, conn_id, added, added_count)); -} - -void RegisterServerCallback(int status, int server_if, - const bluetooth::Uuid& app_uuid) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - status: " << status << " server_if: " << server_if; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_SERVER_OBSERVER( - RegisterServerCallback(g_interface, status, server_if, app_uuid)); -} - -void ConnectionCallback(int conn_id, int server_if, int connected, - const RawAddress& bda) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - conn_id: " << conn_id - << " server_if: " << server_if << " connected: " << connected; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_SERVER_OBSERVER( - ConnectionCallback(g_interface, conn_id, server_if, connected, bda)); -} - -void ServiceAddedCallback(int status, int server_if, - const btgatt_db_element_t* service, - size_t service_count) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - status: " << status << " server_if: " << server_if - << " count: " << service_count; - VERIFY_INTERFACE_OR_RETURN(); - CHECK(service_count); - - FOR_EACH_SERVER_OBSERVER(ServiceAddedCallback( - g_interface, status, server_if, - std::vector<btgatt_db_element_t>(service, service + service_count))); -} - -void ServiceStoppedCallback(int status, int server_if, int srvc_handle) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - status: " << status << " server_if: " << server_if - << " handle: " << srvc_handle; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_SERVER_OBSERVER( - ServiceStoppedCallback(g_interface, status, server_if, srvc_handle)); -} - -void ServiceDeletedCallback(int status, int server_if, int srvc_handle) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - status: " << status << " server_if: " << server_if - << " handle: " << srvc_handle; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_SERVER_OBSERVER( - ServiceDeletedCallback(g_interface, status, server_if, srvc_handle)); -} - -void RequestReadCharacteristicCallback(int conn_id, int trans_id, - const RawAddress& bda, int attr_handle, - int offset, bool is_long) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - conn_id: " << conn_id << " trans_id: " << trans_id - << " attr_handle: " << attr_handle << " offset: " << offset - << " is_long: " << is_long; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_SERVER_OBSERVER(RequestReadCharacteristicCallback( - g_interface, conn_id, trans_id, bda, attr_handle, offset, is_long)); -} - -void RequestReadDescriptorCallback(int conn_id, int trans_id, - const RawAddress& bda, int attr_handle, - int offset, bool is_long) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - conn_id: " << conn_id << " trans_id: " << trans_id - << " attr_handle: " << attr_handle << " offset: " << offset - << " is_long: " << is_long; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_SERVER_OBSERVER(RequestReadDescriptorCallback( - g_interface, conn_id, trans_id, bda, attr_handle, offset, is_long)); -} - -void RequestWriteCharacteristicCallback(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) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - conn_id: " << conn_id << " trans_id: " << trans_id - << " attr_handle: " << attr_handle << " offset: " << offset - << " length: " << length << " need_rsp: " << need_rsp - << " is_prep: " << is_prep; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_SERVER_OBSERVER(RequestWriteCharacteristicCallback( - g_interface, conn_id, trans_id, bda, attr_handle, offset, need_rsp, - is_prep, std::vector(value, value + length))); -} - -void RequestWriteDescriptorCallback(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) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - conn_id: " << conn_id << " trans_id: " << trans_id - << " attr_handle: " << attr_handle << " offset: " << offset - << " length: " << length << " need_rsp: " << need_rsp - << " is_prep: " << is_prep; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_SERVER_OBSERVER(RequestWriteDescriptorCallback( - g_interface, conn_id, trans_id, bda, attr_handle, offset, need_rsp, - is_prep, std::vector(value, value + length))); -} - -void RequestExecWriteCallback(int conn_id, int trans_id, const RawAddress& bda, - int exec_write) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - conn_id: " << conn_id << " trans_id: " << trans_id - << " exec_write: " << exec_write; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_SERVER_OBSERVER(RequestExecWriteCallback(g_interface, conn_id, - trans_id, bda, exec_write)); -} - -void ResponseConfirmationCallback(int status, int handle) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - status: " << status << " handle: " << handle; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_SERVER_OBSERVER( - ResponseConfirmationCallback(g_interface, status, handle)); -} - -void IndicationSentCallback(int conn_id, int status) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - conn_id: " << conn_id << " status: " << status; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_SERVER_OBSERVER( - IndicationSentCallback(g_interface, conn_id, status)); -} - -void MtuChangedCallback(int conn_id, int mtu) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VLOG(2) << __func__ << " - conn_id: " << conn_id << " mtu: " << mtu; - VERIFY_INTERFACE_OR_RETURN(); - - FOR_EACH_SERVER_OBSERVER(MtuChangedCallback(g_interface, conn_id, mtu)); -} - -// The HAL Bluetooth GATT client interface callbacks. These signal a mixture of -// GATT client-role and GAP events. - -const btgatt_scanner_callbacks_t gatt_scanner_callbacks = { - ScanResultCallback, - nullptr, // batchscan_reports_cb - nullptr, // batchscan_threshold_cb - nullptr, // track_adv_event_cb -}; - -const btgatt_client_callbacks_t gatt_client_callbacks = { - RegisterClientCallback, - ConnectCallback, - DisconnectCallback, - SearchCompleteCallback, - RegisterForNotificationCallback, - NotifyCallback, - nullptr, // read_characteristic_cb - WriteCharacteristicCallback, - nullptr, // read_descriptor_cb - WriteDescriptorCallback, - nullptr, // execute_write_cb - nullptr, // read_remote_rssi_cb - MtuChangedCallback, - nullptr, // congestion_cb - GetGattDbCallback, - ServicesRemovedCallback, - ServicesAddedCallback, - nullptr, - nullptr, - nullptr, // service_changed_cb - nullptr, // subrate_chg_cb -}; - -const btgatt_server_callbacks_t gatt_server_callbacks = { - RegisterServerCallback, - ConnectionCallback, - ServiceAddedCallback, - ServiceStoppedCallback, - ServiceDeletedCallback, - RequestReadCharacteristicCallback, - RequestReadDescriptorCallback, - RequestWriteCharacteristicCallback, - RequestWriteDescriptorCallback, - RequestExecWriteCallback, - ResponseConfirmationCallback, - IndicationSentCallback, - nullptr, // congestion_cb - MtuChangedCallback, - nullptr, - nullptr, - nullptr, -}; - -const btgatt_callbacks_t gatt_callbacks = { - sizeof(btgatt_callbacks_t), &gatt_client_callbacks, &gatt_server_callbacks, - &gatt_scanner_callbacks, -}; - -} // namespace - -// BluetoothGattInterface implementation for production. -class BluetoothGattInterfaceImpl : public BluetoothGattInterface { - public: - BluetoothGattInterfaceImpl() : hal_iface_(nullptr) {} - - BluetoothGattInterfaceImpl(const BluetoothGattInterfaceImpl&) = delete; - BluetoothGattInterfaceImpl& operator=(const BluetoothGattInterfaceImpl&) = - delete; - - ~BluetoothGattInterfaceImpl() override { - if (hal_iface_) hal_iface_->cleanup(); - } - - void AddScannerObserver(ScannerObserver* observer) override { - scanner_observers_.AddObserver(observer); - } - - void RemoveScannerObserver(ScannerObserver* observer) override { - scanner_observers_.RemoveObserver(observer); - } - - void AddClientObserver(ClientObserver* observer) override { - client_observers_.AddObserver(observer); - } - - void RemoveClientObserver(ClientObserver* observer) override { - client_observers_.RemoveObserver(observer); - } - - void AddServerObserver(ServerObserver* observer) override { - server_observers_.AddObserver(observer); - } - - void RemoveServerObserver(ServerObserver* observer) override { - server_observers_.RemoveObserver(observer); - } - - BleAdvertiserInterface* GetAdvertiserHALInterface() const override { - return hal_iface_->advertiser; - } - - BleScannerInterface* GetScannerHALInterface() const override { - return hal_iface_->scanner; - } - - const btgatt_client_interface_t* GetClientHALInterface() const override { - return hal_iface_->client; - } - - const btgatt_server_interface_t* GetServerHALInterface() const override { - return hal_iface_->server; - } - - // Initialize the interface. - bool Initialize() { - const bt_interface_t* bt_iface = - BluetoothInterface::Get()->GetHALInterface(); - CHECK(bt_iface); - - const btgatt_interface_t* gatt_iface = - reinterpret_cast<const btgatt_interface_t*>( - bt_iface->get_profile_interface(BT_PROFILE_GATT_ID)); - if (!gatt_iface) { - LOG(ERROR) << "Failed to obtain HAL GATT interface handle"; - return false; - } - - bt_status_t status = gatt_iface->init(&gatt_callbacks); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to initialize HAL GATT interface"; - return false; - } - - hal_iface_ = gatt_iface; - - return true; - } - - btbase::AbstractObserverList<ScannerObserver>* scanner_observers() { - return &scanner_observers_; - } - - btbase::AbstractObserverList<ClientObserver>* client_observers() { - return &client_observers_; - } - - btbase::AbstractObserverList<ServerObserver>* server_observers() { - return &server_observers_; - } - - private: - // List of observers that are interested in notifications from us. - // We're not using a base::ObserverListThreadSafe, which it posts observer - // events automatically on the origin threads, as we want to avoid that - // overhead and simply forward the events to the upper layer. - btbase::AbstractObserverList<ScannerObserver> scanner_observers_; - btbase::AbstractObserverList<ClientObserver> client_observers_; - btbase::AbstractObserverList<ServerObserver> server_observers_; - - // The HAL handle obtained from the shared library. We hold a weak reference - // to this since the actual data resides in the shared Bluetooth library. - const btgatt_interface_t* hal_iface_; -}; - -namespace { - -btbase::AbstractObserverList<BluetoothGattInterface::ScannerObserver>* -GetScannerObservers() { - CHECK(g_interface); - return static_cast<BluetoothGattInterfaceImpl*>(g_interface) - ->scanner_observers(); -} - -btbase::AbstractObserverList<BluetoothGattInterface::ClientObserver>* -GetClientObservers() { - CHECK(g_interface); - return static_cast<BluetoothGattInterfaceImpl*>(g_interface) - ->client_observers(); -} - -btbase::AbstractObserverList<BluetoothGattInterface::ServerObserver>* -GetServerObservers() { - CHECK(g_interface); - return static_cast<BluetoothGattInterfaceImpl*>(g_interface) - ->server_observers(); -} - -} // namespace - -// Default observer implementations. These are provided so that the methods -// themselves are optional. - -void BluetoothGattInterface::ScannerObserver::ScanResultCallback( - BluetoothGattInterface* /* gatt_iface */, const RawAddress& /* bda */, - int /* rssi */, - std::vector<uint8_t> /* adv_data */) { // NOLINT(pass-by-value) - // Do Nothing. -} - -void BluetoothGattInterface::ClientObserver::RegisterClientCallback( - BluetoothGattInterface* /* gatt_iface */, int /* status */, - int /* client_if */, const bluetooth::Uuid& /* app_uuid */) { - // Do nothing. -} - -void BluetoothGattInterface::ClientObserver::ConnectCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* status */, int /* client_if */, const RawAddress& /* bda */) { - // Do nothing -} - -void BluetoothGattInterface::ClientObserver::DisconnectCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* status */, int /* client_if */, const RawAddress& /* bda */) { - // Do nothing -} - -void BluetoothGattInterface::ClientObserver::SearchCompleteCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* status */) { - // Do nothing -} - -void BluetoothGattInterface::ClientObserver::RegisterForNotificationCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* registered */, int /* status */, uint16_t /* handle */) { - // Do nothing -} - -void BluetoothGattInterface::ClientObserver::NotifyCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - const btgatt_notify_params_t& /* p_data */) { - // Do nothing -} - -void BluetoothGattInterface::ClientObserver::WriteCharacteristicCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* status */, uint16_t /* handle */, uint16_t /* len */, - const uint8_t* /* value */) { - // Do nothing -} - -void BluetoothGattInterface::ClientObserver::WriteDescriptorCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* status */, uint16_t /* handle */, uint16_t /* len */, - const uint8_t* /* value */) { - // Do nothing -} - -void BluetoothGattInterface::ClientObserver::MtuChangedCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* statis*/, int /* mtu */) { - // Do nothing. -} - -void BluetoothGattInterface::ClientObserver::GetGattDbCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - const btgatt_db_element_t* /* gatt_db */, int /* size */) { - // Do nothing. -} - -void BluetoothGattInterface::ClientObserver::ServicesRemovedCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - uint16_t /* start_handle */, uint16_t /* end_handle */) { - // Do nothing. -} - -void BluetoothGattInterface::ClientObserver::ServicesAddedCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - const btgatt_db_element_t& /* added */, int /* added_count */) { - // Do nothing. -} - -void BluetoothGattInterface::ServerObserver::RegisterServerCallback( - BluetoothGattInterface* /* gatt_iface */, int /* status */, - int /* server_if */, const bluetooth::Uuid& /* app_uuid */) { - // Do nothing. -} - -void BluetoothGattInterface::ServerObserver::ConnectionCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* server_if */, int /* connected */, const RawAddress& /* bda */) { - // Do nothing. -} - -void BluetoothGattInterface::ServerObserver::ServiceAddedCallback( - BluetoothGattInterface* /* gatt_iface */, int /* status */, - int /* server_if */, - std::vector<btgatt_db_element_t> /* service */) { // NOLINT(pass-by-value) - // Do nothing. -} - -void BluetoothGattInterface::ServerObserver::ServiceStoppedCallback( - BluetoothGattInterface* /* gatt_iface */, int /* status */, - int /* server_if */, int /* srvc_handle */) { - // Do nothing. -} - -void BluetoothGattInterface::ServerObserver::ServiceDeletedCallback( - BluetoothGattInterface* /* gatt_iface */, int /* status */, - int /* server_if */, int /* srvc_handle */) { - // Do nothing. -} - -void BluetoothGattInterface::ServerObserver::RequestReadCharacteristicCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* trans_id */, const RawAddress& /* bda */, int /* attr_handle */, - int /* offset */, bool /* is_long */) { - // Do nothing. -} - -void BluetoothGattInterface::ServerObserver::RequestReadDescriptorCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* trans_id */, const RawAddress& /* bda */, int /* attr_handle */, - int /* offset */, bool /* is_long */) { - // Do nothing. -} - -void BluetoothGattInterface::ServerObserver::RequestWriteCharacteristicCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* trans_id */, const RawAddress& /* bda */, int /* attr_handle */, - int /* offset */, bool /* need_rsp */, bool /* is_prep */, - std::vector<uint8_t> /* value */) { // NOLINT(pass-by-value) - // Do nothing. -} - -void BluetoothGattInterface::ServerObserver::RequestWriteDescriptorCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* trans_id */, const RawAddress& /* bda */, int /* attr_handle */, - int /* offset */, bool /* need_rsp */, bool /* is_prep */, - std::vector<uint8_t> /* value */) { // NOLINT(pass-by-value) - // Do nothing. -} - -void BluetoothGattInterface::ServerObserver::RequestExecWriteCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* trans_id */, const RawAddress& /* bda */, int /* exec_write */) { - // Do nothing. -} - -void BluetoothGattInterface::ServerObserver::ResponseConfirmationCallback( - BluetoothGattInterface* /* gatt_iface */, int /* status */, - int /* handle */) { - // Do nothing -} - -void BluetoothGattInterface::ServerObserver::IndicationSentCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* status */) { - // Do nothing. -} - -void BluetoothGattInterface::ServerObserver::MtuChangedCallback( - BluetoothGattInterface* /* gatt_iface */, int /* conn_id */, - int /* mtu */) { - // Do nothing. -} - -// static -bool BluetoothGattInterface::Initialize() { - unique_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(!g_interface); - - std::unique_ptr<BluetoothGattInterfaceImpl> impl( - new BluetoothGattInterfaceImpl()); - if (!impl->Initialize()) { - LOG(ERROR) << "Failed to initialize BluetoothGattInterface"; - return false; - } - - g_interface = impl.release(); - - return true; -} - -// static -void BluetoothGattInterface::CleanUp() { - unique_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(g_interface); - - delete g_interface; - g_interface = nullptr; -} - -// static -bool BluetoothGattInterface::IsInitialized() { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - - return g_interface != nullptr; -} - -// static -BluetoothGattInterface* BluetoothGattInterface::Get() { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(g_interface); - return g_interface; -} - -// static -void BluetoothGattInterface::InitializeForTesting( - BluetoothGattInterface* test_instance) { - unique_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(test_instance); - CHECK(!g_interface); - - g_interface = test_instance; -} - -bt_status_t BluetoothGattInterface::StartScan(int client_id) { - lock_guard<mutex> lock(scan_clients_lock_); - - // Scan already initiated for this client. - if (scan_client_set_.find(client_id) != scan_client_set_.end()) { - // Assume starting scan multiple times is not error, but warn user. - LOG(WARNING) << "Scan already initiated for client"; - return BT_STATUS_SUCCESS; - } - - // If this is the first scan client, then make a call into the stack. We - // only do this when the reference count changes to or from 0. - if (scan_client_set_.empty()) { - GetScannerHALInterface()->Scan(true); - } - - scan_client_set_.insert(client_id); - - return BT_STATUS_SUCCESS; -} - -bt_status_t BluetoothGattInterface::StopScan(int client_id) { - lock_guard<mutex> lock(scan_clients_lock_); - - // Scan not initiated for this client. - auto iter = scan_client_set_.find(client_id); - if (iter == scan_client_set_.end()) { - // Assume stopping scan multiple times is not error, but warn user. - LOG(WARNING) << "Scan already stopped or not initiated for client"; - return BT_STATUS_SUCCESS; - } - - if (scan_client_set_.size() == 1) { - GetScannerHALInterface()->Scan(false); - } - - scan_client_set_.erase(iter); - return BT_STATUS_SUCCESS; -} - -} // namespace hal -} // namespace bluetooth diff --git a/system/service/hal/bluetooth_gatt_interface.h b/system/service/hal/bluetooth_gatt_interface.h deleted file mode 100644 index ad3f851554..0000000000 --- a/system/service/hal/bluetooth_gatt_interface.h +++ /dev/null @@ -1,268 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <hardware/bluetooth.h> -#include <hardware/bt_gatt.h> - -#include <mutex> -#include <unordered_set> -#include <vector> - -#include "types/raw_address.h" - -namespace bluetooth { -namespace hal { - -// This class represents the standard BT-GATT interface. This class combines -// GATT profile server and client role operations with general GAP profile -// operations of various roles (central, scanner, peripheral, advertiser), -// wrapping around the underlying bt_gatt_interface_t structure. A single -// instance of this class exists per application and it allows multiple classes -// to interface with the global HAL interface by multiplexing callbacks among -// registered clients. -// -// This is declared as an abstract interface so that a fake implementation can -// be injected for testing the upper layer. -class BluetoothGattInterface { - public: - // The HAL interface doesn't allow registering "user data" that carries - // context beyond the callback parameters, forcing implementations to deal - // with global variables. The *Observer interface is to redirect these events - // to interested parties in an object-oriented manner. - - // The standard LE scanner callback interface. - class ScannerObserver { - public: - virtual ~ScannerObserver() = default; - - // All of the events below correspond to callbacks defined in - // "btgatt_scanner_callbacks_t" in the HAL API definitions. - - virtual void ScanResultCallback( - BluetoothGattInterface* gatt_iface, const RawAddress& bda, int rssi, - std::vector<uint8_t> adv_data); // NOLINT(pass-by-value) - }; - - // The standard BT-GATT client callback interface. - class ClientObserver { - public: - virtual ~ClientObserver() = default; - - // All of the events below correspond to callbacks defined in - // "bt_gatt_client_callbacks_t" in the HAL API definitions. - - virtual void RegisterClientCallback(BluetoothGattInterface* gatt_iface, - int status, int client_if, - const bluetooth::Uuid& app_uuid); - - virtual void ConnectCallback(BluetoothGattInterface* gatt_iface, - int conn_id, int status, int client_if, - const RawAddress& bda); - - virtual void DisconnectCallback(BluetoothGattInterface* gatt_iface, - int conn_id, int status, int client_if, - const RawAddress& bda); - - virtual void SearchCompleteCallback(BluetoothGattInterface* gatt_iface, - int conn_id, int status); - - virtual void RegisterForNotificationCallback( - BluetoothGattInterface* gatt_iface, int conn_id, int registered, - int status, uint16_t handle); - - virtual void NotifyCallback(BluetoothGattInterface* gatt_iface, int conn_id, - const btgatt_notify_params_t& p_data); - - virtual void WriteCharacteristicCallback(BluetoothGattInterface* gatt_iface, - int conn_id, int status, - uint16_t handle, uint16_t len, - const uint8_t* value); - - virtual void WriteDescriptorCallback(BluetoothGattInterface* gatt_iface, - int conn_id, int status, - uint16_t handle, uint16_t len, - const uint8_t* value); - - virtual void MtuChangedCallback(BluetoothGattInterface* gatt_iface, - int conn_id, int status, int mtu); - - virtual void GetGattDbCallback(BluetoothGattInterface* gatt_iface, - int conn_id, - const btgatt_db_element_t* gatt_db, - int size); - - virtual void ServicesRemovedCallback(BluetoothGattInterface* gatt_iface, - int conn_id, uint16_t start_handle, - uint16_t end_handle); - - virtual void ServicesAddedCallback(BluetoothGattInterface* gatt_iface, - int conn_id, - const btgatt_db_element_t& added, - int added_count); - }; - - // The standard BT-GATT server callback interface. - class ServerObserver { - public: - virtual ~ServerObserver() = default; - - virtual void RegisterServerCallback(BluetoothGattInterface* gatt_iface, - int status, int server_if, - const bluetooth::Uuid& app_uuid); - - virtual void ConnectionCallback(BluetoothGattInterface* gatt_iface, - int conn_id, int server_if, int connected, - const RawAddress& bda); - - virtual void ServiceAddedCallback( - BluetoothGattInterface* gatt_iface, int status, int server_if, - std::vector<btgatt_db_element_t> service); // NOLINT(pass-by-value) - - virtual void ServiceStoppedCallback(BluetoothGattInterface* gatt_iface, - int status, int server_if, - int srvc_handle); - - virtual void ServiceDeletedCallback(BluetoothGattInterface* gatt_iface, - int status, int server_if, - int srvc_handle); - - virtual void RequestReadCharacteristicCallback( - BluetoothGattInterface* gatt_iface, int conn_id, int trans_id, - const RawAddress& bda, int attr_handle, int offset, bool is_long); - - virtual void RequestReadDescriptorCallback( - BluetoothGattInterface* gatt_iface, int conn_id, int trans_id, - const RawAddress& bda, int attr_handle, int offset, bool is_long); - - virtual void RequestWriteCharacteristicCallback( - BluetoothGattInterface* gatt_iface, int conn_id, int trans_id, - const RawAddress& bda, int attr_handle, int offset, bool need_rsp, - bool is_prep, - std::vector<uint8_t> value); // NOLINT(pass-by-value) - - virtual void RequestWriteDescriptorCallback( - BluetoothGattInterface* gatt_iface, int conn_id, int trans_id, - const RawAddress& bda, int attr_handle, int offset, bool need_rsp, - bool is_prep, - std::vector<uint8_t> value); // NOLINT(pass-by-alue) - - virtual void RequestExecWriteCallback(BluetoothGattInterface* gatt_iface, - int conn_id, int trans_id, - const RawAddress& bda, - int exec_write); - - virtual void ResponseConfirmationCallback( - BluetoothGattInterface* gatt_iface, int status, int handle); - - virtual void IndicationSentCallback(BluetoothGattInterface* gatt_iface, - int conn_id, int status); - - virtual void MtuChangedCallback(BluetoothGattInterface* gatt_iface, - int conn_id, int mtu); - }; - - // Initialize and clean up the BluetoothInterface singleton. Returns false if - // the underlying HAL interface failed to initialize, and true on success. - static bool Initialize(); - - // Shuts down and cleans up the interface. CleanUp must be called on the same - // thread that called Initialize. - static void CleanUp(); - - // Returns true if the interface was initialized and a global singleton has - // been created. - static bool IsInitialized(); - - // Initialize for testing. Use this to inject a test version of - // BluetoothGattInterface. To be used from unit tests only. - static void InitializeForTesting(BluetoothGattInterface* test_instance); - - // Returns the BluetoothGattInterface singleton. If the interface has - // not been initialized, returns nullptr. This method is thread-safe, in that - // it will block if the internal lock is being held by another thread. Don't - // call this re-entrantly from an observer event as this may cause a deadlock. - static BluetoothGattInterface* Get(); - - // Add or remove an observer that is interested in LE scanner interface - // notifications from us. Thread-safety is guaranteed by ObserverList. - virtual void AddScannerObserver(ScannerObserver* observer) = 0; - virtual void RemoveScannerObserver(ScannerObserver* observer) = 0; - - // Add or remove an observer that is interested in GATT client interface - // notifications from us. Thread-safety is guaranteed by ObserverList. - virtual void AddClientObserver(ClientObserver* observer) = 0; - virtual void RemoveClientObserver(ClientObserver* observer) = 0; - - // Add or remove an observer that is interested in GATT server interface - // notifications from us. Thread-safety is guaranteed by ObserverList. - virtual void AddServerObserver(ServerObserver* observer) = 0; - virtual void RemoveServerObserver(ServerObserver* observer) = 0; - - // The HAL module pointer that represents the standard BT LE advertiser - // interface. This is implemented in and provided by the shared Bluetooth - // library, so this isn't owned by us. - // - // Upper layers can make ble_advertiser_interface_t API calls through this - // structure. - virtual BleAdvertiserInterface* GetAdvertiserHALInterface() const = 0; - - // The HAL module pointer that represents the standard BT LE scanner - // interface. This is implemented in and provided by the shared Bluetooth - // library, so this isn't owned by us. - // - // Upper layers can make ble_scanner_interface_t API calls through this - // structure. - virtual BleScannerInterface* GetScannerHALInterface() const = 0; - - // The HAL module pointer that represents the standard BT-GATT client - // interface. This is implemented in and provided by the shared Bluetooth - // library, so this isn't owned by us. - // - // Upper layers can make btgatt_client_interface_t API calls through this - // structure. - virtual const btgatt_client_interface_t* GetClientHALInterface() const = 0; - - // The HAL module pointer that represents the standard BT-GATT server - // interface. This is implemented in and provided by the shared Bluetooth - // library, so this isn't owned by us. - // - // Upper layers can make btgatt_server_interface_t API calls through this - // structure. - virtual const btgatt_server_interface_t* GetServerHALInterface() const = 0; - - // Initiates a regular BLE device scan. This is called internally from each - // LowEnergyClient. This function synchronizes the scan requests and maintains - // an internal reference count for each scan client that is interested. - bt_status_t StartScan(int client_id); - bt_status_t StopScan(int client_id); - - protected: - BluetoothGattInterface() = default; - BluetoothGattInterface(const BluetoothGattInterface&) = delete; - BluetoothGattInterface& operator=(const BluetoothGattInterface&) = delete; - - virtual ~BluetoothGattInterface() = default; - - private: - // Used to keep a reference count for the different BLE scan clients. - std::mutex scan_clients_lock_; - std::unordered_set<int> scan_client_set_; -}; - -} // namespace hal -} // namespace bluetooth diff --git a/system/service/hal/bluetooth_interface.cc b/system/service/hal/bluetooth_interface.cc deleted file mode 100644 index 9b2ad52caa..0000000000 --- a/system/service/hal/bluetooth_interface.cc +++ /dev/null @@ -1,529 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/hal/bluetooth_interface.h" - -#include <base/logging.h> -#include <base/observer_list.h> -#include <dlfcn.h> - -#include <mutex> -#include <shared_mutex> - -#include "abstract_observer_list.h" -#include "btcore/include/hal_util.h" -#include "service/logging_helpers.h" -#include "types/raw_address.h" - -using std::lock_guard; -using std::unique_lock; -using std::shared_lock; -using std::mutex; -#if defined(OS_GENERIC) && defined(_LIBCPP_VERSION) && (_LIBCPP_VERSION < 3500) -using shared_mutex_impl = std::shared_mutex; -#else -using shared_mutex_impl = std::shared_timed_mutex; -#endif - -#ifndef DYNAMIC_LOAD_BLUETOOTH -extern bt_interface_t bluetoothInterface; -#endif - -namespace bluetooth { -namespace hal { - -namespace { - -// The global BluetoothInterface instance. -BluetoothInterface* g_bluetooth_interface = nullptr; - -// Mutex used by callbacks to access |g_interface|. If we initialize or clean it -// use unique_lock. If only accessing |g_interface| use shared lock. -// TODO(jpawlowski): this should be just shared_mutex, as we currently don't use -// timed methods. Change to shared_mutex when we upgrade to C++14 -shared_mutex_impl g_instance_lock; - -// Helper for obtaining the observer list. This is forward declared here and -// defined below since it depends on BluetoothInterfaceImpl. -btbase::AbstractObserverList<BluetoothInterface::Observer>* GetObservers(); - -#define FOR_EACH_BLUETOOTH_OBSERVER(func) \ - for (auto& observer : *GetObservers()) { \ - observer.func; \ - } - -#define VERIFY_INTERFACE_OR_RETURN() \ - do { \ - if (!g_bluetooth_interface) { \ - LOG(WARNING) << "Callback received while |g_interface| is NULL"; \ - return; \ - } \ - } while (0) - -void AdapterStateChangedCallback(bt_state_t state) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - VLOG(1) << "Adapter state changed: " << BtStateText(state); - FOR_EACH_BLUETOOTH_OBSERVER(AdapterStateChangedCallback(state)); -} - -void AdapterPropertiesCallback(bt_status_t status, int num_properties, - bt_property_t* properties) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - VLOG(1) << "Adapter properties changed - status: " << BtStatusText(status) - << ", num_properties: " << num_properties; - FOR_EACH_BLUETOOTH_OBSERVER( - AdapterPropertiesCallback(status, num_properties, properties)); -} - -void RemoteDevicePropertiesCallback(bt_status_t status, - RawAddress* remote_bd_addr, - int num_properties, - bt_property_t* properties) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - VLOG(1) << " Remote device properties changed - status: " - << BtStatusText(status) - << " - BD_ADDR: " << BtAddrString(remote_bd_addr) - << ", num_properties: " << num_properties; - FOR_EACH_BLUETOOTH_OBSERVER(RemoteDevicePropertiesCallback( - status, remote_bd_addr, num_properties, properties)); -} - -void DeviceFoundCallback(int num_properties, bt_property_t* properties) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - VLOG(1) << " Device found."; - FOR_EACH_BLUETOOTH_OBSERVER(DeviceFoundCallback(num_properties, properties)); -} - -void DiscoveryStateChangedCallback(bt_discovery_state_t state) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - VLOG(1) << "Discovery state changed - state: " << BtDiscoveryStateText(state); - FOR_EACH_BLUETOOTH_OBSERVER(DiscoveryStateChangedCallback(state)); -} - -void PinRequestCallback(RawAddress* remote_bd_addr, bt_bdname_t* bd_name, - uint32_t cod, bool min_16_digit) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - VLOG(2) << __func__ << " - remote_bd_addr: " << remote_bd_addr - << " - bd_name: " << bd_name << " - cod: " << cod - << " - min_16_digit: " << min_16_digit; - FOR_EACH_BLUETOOTH_OBSERVER( - PinRequestCallback(remote_bd_addr, bd_name, cod, min_16_digit)); -} - -void SSPRequestCallback(RawAddress* remote_bd_addr, bt_bdname_t* bd_name, - uint32_t cod, bt_ssp_variant_t pairing_variant, - uint32_t pass_key) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - VLOG(2) << __func__ << " - remote_bd_addr: " << remote_bd_addr - << " - bd_name: " << bd_name << " - cod: " << cod - << " - pairing_variant: " << pairing_variant; - FOR_EACH_BLUETOOTH_OBSERVER(SSPRequestCallback(remote_bd_addr, bd_name, cod, - pairing_variant, pass_key)); -} - -void BondStateChangedCallback(bt_status_t status, RawAddress* remote_bd_addr, - bt_bond_state_t state, int fail_reason) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - VLOG(2) << __func__ << " - remote_bd_addr: " << BtAddrString(remote_bd_addr) - << " - status: " << status << " - state: " << state; - FOR_EACH_BLUETOOTH_OBSERVER( - BondStateChangedCallback(status, remote_bd_addr, state, fail_reason)); -} - -void AddressConsolidateCallback(RawAddress* main_bd_addr, - RawAddress* secondary_bd_addr) { - // Do nothing -} - -void LeAddressAssociateCallback(RawAddress* main_bd_addr, - RawAddress* secondary_bd_addr) { - // Do nothing -} - -void AclStateChangedCallback(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) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - CHECK(remote_bd_addr); - VLOG(1) << "Remote device ACL state changed - status: " - << BtStatusText(status) - << " - BD_ADDR: " << BtAddrString(remote_bd_addr) << " - state: " - << ((state == BT_ACL_STATE_CONNECTED) ? "CONNECTED" : "DISCONNECTED") - << " - HCI_REASON: " << std::to_string(hci_reason); - FOR_EACH_BLUETOOTH_OBSERVER(AclStateChangedCallback( - status, *remote_bd_addr, state, transport_link_type, hci_reason, - direction, acl_handle)); -} - -void ThreadEventCallback(bt_cb_thread_evt evt) { - VLOG(1) << "ThreadEventCallback" << BtEventText(evt); - - // TODO(armansito): This callback is completely useless to us but btif borks - // out if this is not set. Consider making this optional. -} - -bool SetWakeAlarmCallout(uint64_t /* delay_millis */, bool /* should_wake */, - alarm_cb /* cb */, void* /* data */) { - // TODO(armansito): According to sharvil@, this interface doesn't even need to - // exist and can be done entirely from within osi by interfacing directly with - // the kernel. Remove these stubs once that's fixed. (See http://b/23390297) - return false; -} - -int AcquireWakeLockCallout(const char* /* lock_name */) { - // TODO(armansito): According to sharvil@, this interface doesn't even need to - // exist and can be done entirely from within osi by interfacing directly with - // the kernel. Remove these stubs once that's fixed. (See http://b/23390297) - // Lie here and return success so that enabling and disabling the controller - // works before this is properly implemented. - return BT_STATUS_SUCCESS; -} - -int ReleaseWakeLockCallout(const char* /* lock_name */) { - // TODO(armansito): According to sharvil@, this interface doesn't even need to - // exist and can be done entirely from within osi by interfacing directly with - // the kernel. Remove these stubs once that's fixed. (See http://b/23390297) - // Lie here and return success so that enabling and disabling the controller - // works before this is properly implemented. - return BT_STATUS_SUCCESS; -} - -void LinkQualityReportCallback(uint64_t timestamp, int report_id, int rssi, - int snr, int retransmission_count, int packets_not_receive_count, - int negative_acknowledgement_count) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - LOG(WARNING) << __func__ << " - timestamp: " << timestamp - << " - report_id: " << report_id << " - rssi: " << rssi - << " - snr: " << snr - << " - retransmission_count: " << retransmission_count - << " - packets_not_receive_count: " << packets_not_receive_count - << " - negative_acknowledgement_count: " - << negative_acknowledgement_count; - FOR_EACH_BLUETOOTH_OBSERVER(LinkQualityReportCallback( - timestamp, report_id, rssi, snr, retransmission_count, - packets_not_receive_count, negative_acknowledgement_count)); -} - -void SwitchBufferSizeCallback(bool is_low_latency_buffer_size) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - LOG(WARNING) << __func__ << " - is_low_latency_buffer_size: " - << is_low_latency_buffer_size; - FOR_EACH_BLUETOOTH_OBSERVER( - SwitchBufferSizeCallback(is_low_latency_buffer_size)); -} - -void SwitchCodecCallback(bool is_low_latency_buffer_size) { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - VERIFY_INTERFACE_OR_RETURN(); - LOG(WARNING) << __func__ << " - is_low_latency_buffer_size: " - << is_low_latency_buffer_size; - FOR_EACH_BLUETOOTH_OBSERVER(SwitchCodecCallback(is_low_latency_buffer_size)); -} - -// The HAL Bluetooth DM callbacks. -bt_callbacks_t bt_callbacks = { - sizeof(bt_callbacks_t), - AdapterStateChangedCallback, - AdapterPropertiesCallback, - RemoteDevicePropertiesCallback, - DeviceFoundCallback, - DiscoveryStateChangedCallback, - PinRequestCallback, - SSPRequestCallback, - BondStateChangedCallback, - AddressConsolidateCallback, - LeAddressAssociateCallback, - AclStateChangedCallback, - ThreadEventCallback, - nullptr, /* energy_info_cb */ - LinkQualityReportCallback, - nullptr /* generate_local_oob_data_cb */, - SwitchBufferSizeCallback, - SwitchCodecCallback, - nullptr /* le_rand_cb */, -}; - -bt_os_callouts_t bt_os_callouts = {sizeof(bt_os_callouts_t), - SetWakeAlarmCallout, AcquireWakeLockCallout, - ReleaseWakeLockCallout}; - -constexpr char kLibbluetooth[] = "libbluetooth.so"; -constexpr char kBluetoothInterfaceSym[] = "bluetoothInterface"; - -int hal_util_load_bt_library_from_dlib(const bt_interface_t** interface) { -#ifndef DYNAMIC_LOAD_BLUETOOTH - (void)kLibbluetooth; - (void)kBluetoothInterfaceSym; - *interface = &bluetoothInterface; - return 0; -#else - bt_interface_t* itf{nullptr}; - - // Always try to load the default Bluetooth stack on GN builds. - void* handle = dlopen(kLibbluetooth, RTLD_NOW); - if (!handle) { - const char* err_str = dlerror(); - LOG(ERROR) << __func__ << ": failed to load bluetooth library, error=" - << (err_str ? err_str : "error unknown"); - goto error; - } - - // Get the address of the bt_interface_t. - itf = (bt_interface_t*)dlsym(handle, kBluetoothInterfaceSym); - if (!itf) { - LOG(ERROR) << __func__ << ": failed to load symbol from Bluetooth library " - << kBluetoothInterfaceSym; - goto error; - } - - // Success. - LOG(INFO) << __func__ << " loaded HAL path=" << kLibbluetooth - << " btinterface=" << itf << " handle=" << handle; - - *interface = itf; - return 0; - -error: - *interface = NULL; - if (handle) dlclose(handle); - - return -EINVAL; -#endif -} - -} // namespace - -// BluetoothInterface implementation for production. -class BluetoothInterfaceImpl : public BluetoothInterface { - public: - BluetoothInterfaceImpl() : hal_iface_(nullptr) {} - - BluetoothInterfaceImpl(const BluetoothInterfaceImpl&) = delete; - BluetoothInterfaceImpl& operator=(const BluetoothInterfaceImpl&) = delete; - - ~BluetoothInterfaceImpl() override { - if (hal_iface_) hal_iface_->cleanup(); - } - - // BluetoothInterface overrides. - void AddObserver(Observer* observer) override { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - observers_.AddObserver(observer); - } - - void RemoveObserver(Observer* observer) override { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - observers_.RemoveObserver(observer); - } - - const bt_interface_t* GetHALInterface() const override { return hal_iface_; } - - bt_callbacks_t* GetHALCallbacks() const override { return &bt_callbacks; } - - // Initialize the interface. This loads the shared Bluetooth library and sets - // up the callbacks. - bool Initialize() { - // Load the Bluetooth shared library module. - const bt_interface_t* interface; - int status = hal_util_load_bt_library_from_dlib(&interface); - if (status) { - LOG(ERROR) << "Failed to open the Bluetooth module"; - return false; - } - - hal_iface_ = interface; - - // Initialize the Bluetooth interface. Set up the adapter (Bluetooth DM) API - // callbacks. - status = hal_iface_->init(&bt_callbacks, false, false, 0, nullptr, false, - nullptr); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to initialize Bluetooth stack"; - return false; - } - - status = hal_iface_->set_os_callouts(&bt_os_callouts); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to set up Bluetooth OS callouts"; - return false; - } - - return true; - } - - btbase::AbstractObserverList<Observer>* observers() { return &observers_; } - - private: - // List of observers that are interested in notifications from us. We're not - // using a base::ObserverListThreadSafe, which it posts observer events - // automatically on the origin threads, as we want to avoid that overhead and - // simply forward the events to the upper layer. - btbase::AbstractObserverList<Observer> observers_; - - // The HAL handle obtained from the shared library. We hold a weak reference - // to this since the actual data resides in the shared Bluetooth library. - const bt_interface_t* hal_iface_; -}; - -namespace { - -// Helper for obtaining the observer list from the global instance. This -// function is NOT thread safe. -btbase::AbstractObserverList<BluetoothInterface::Observer>* GetObservers() { - CHECK(g_bluetooth_interface); - return static_cast<BluetoothInterfaceImpl*>(g_bluetooth_interface) - ->observers(); -} - -} // namespace - -// Default observer implementations. These are provided so that the methods -// themselves are optional. -void BluetoothInterface::Observer::AdapterStateChangedCallback( - bt_state_t /* state*/) { - // Do nothing. -} - -void BluetoothInterface::Observer::AdapterPropertiesCallback( - bt_status_t /* status */, int /* num_properties */, - bt_property_t* /* properties */) { - // Do nothing. -} - -void BluetoothInterface::Observer::RemoteDevicePropertiesCallback( - bt_status_t /* status */, RawAddress* /* remote_bd_addr */, - int /* num_properties */, bt_property_t* /* properties */) { - // Do nothing. -} - -void BluetoothInterface::Observer::DeviceFoundCallback( - int /* num_properties */, bt_property_t* /* properties */) { - // Do nothing. -} - -void BluetoothInterface::Observer::DiscoveryStateChangedCallback( - bt_discovery_state_t /* state */) { - // Do nothing. -} - -void BluetoothInterface::Observer::PinRequestCallback( - RawAddress* remote_bd_addr, bt_bdname_t* bd_name, uint32_t cod, - bool min_16_digit) { - // Do nothing. -} - -void BluetoothInterface::Observer::SSPRequestCallback( - RawAddress* remote_bd_addr, bt_bdname_t* bd_name, uint32_t cod, - bt_ssp_variant_t pairing_variant, uint32_t pass_key) { - // Do nothing. -} - -void BluetoothInterface::Observer::BondStateChangedCallback( - bt_status_t status, RawAddress* remote_bd_addr, bt_bond_state_t state, - int fail_reason) { - // Do nothing. -} - -void BluetoothInterface::Observer::AclStateChangedCallback( - bt_status_t /* status */, const RawAddress& /* remote_bdaddr */, - 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 nothing. -} - -void BluetoothInterface::Observer::LinkQualityReportCallback( - uint64_t /* timestamp */, int /* report_id */, int /* rssi */, - int /* snr */, int /* retransmission_count */, - int /* packets_not_receive_count */, - int /* negative_acknowledgement_count */) { - // Do nothing. -} - -void BluetoothInterface::Observer::SwitchBufferSizeCallback( - bool /* is_low_latency_buffer_size */) { - // Do nothing. -} - -void BluetoothInterface::Observer::SwitchCodecCallback( - bool /* is_low_latency_buffer_size */) { - // Do nothing. -} - -// static -bool BluetoothInterface::Initialize() { - unique_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(!g_bluetooth_interface); - - std::unique_ptr<BluetoothInterfaceImpl> impl(new BluetoothInterfaceImpl()); - if (!impl->Initialize()) { - LOG(ERROR) << "Failed to initialize BluetoothInterface"; - return false; - } - - g_bluetooth_interface = impl.release(); - - return true; -} - -// static -void BluetoothInterface::CleanUp() { - unique_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(g_bluetooth_interface); - - delete g_bluetooth_interface; - g_bluetooth_interface = nullptr; -} - -// static -bool BluetoothInterface::IsInitialized() { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - - return g_bluetooth_interface != nullptr; -} - -// static -BluetoothInterface* BluetoothInterface::Get() { - shared_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(g_bluetooth_interface); - return g_bluetooth_interface; -} - -// static -void BluetoothInterface::InitializeForTesting( - BluetoothInterface* test_instance) { - unique_lock<shared_mutex_impl> lock(g_instance_lock); - CHECK(test_instance); - CHECK(!g_bluetooth_interface); - - g_bluetooth_interface = test_instance; -} - -} // namespace hal -} // namespace bluetooth diff --git a/system/service/hal/bluetooth_interface.h b/system/service/hal/bluetooth_interface.h deleted file mode 100644 index 03b9f20e10..0000000000 --- a/system/service/hal/bluetooth_interface.h +++ /dev/null @@ -1,138 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <hardware/bluetooth.h> - -#include "types/raw_address.h" - -namespace bluetooth { -namespace hal { - -// This class represents the HAL Bluetooth adapter interface, wrapping around -// the underlying bt_interface_t structure, its methods, and callbacks. A single -// instance of this class exists per application and it allows multiple classes -// to interface with the global HAL interface by multiplexing callbacks among -// registered clients. -// -// This is declared as an abstract interface so that a fake implementation can -// be injected for testing the upper layer. -// -// TODO: (expose callback types directly but via redirection) methods for -// initialize, clean up, and set for testing. -class BluetoothInterface { - public: - // The standard Bluetooth adapter management callback interface. The HAL - // interface doesn't allow registering "user data" that carries context beyond - // the callback parameters, forcing implementations to deal with global - // variables. The Observer interface is to redirect these events to interested - // parties in an object-oriented manner. - // - // TODO(armansito): We should fix this in the HAL. - class Observer { - public: - virtual ~Observer() = default; - - // All of the events below correspond to callbacks defined in - // "bt_callbacks_t" in the HAL API definitions. - - virtual void AdapterStateChangedCallback(bt_state_t state); - virtual void AdapterPropertiesCallback(bt_status_t status, - int num_properties, - bt_property_t* properties); - virtual void RemoteDevicePropertiesCallback(bt_status_t status, - RawAddress* remote_bd_addr, - int num_properties, - bt_property_t* properties); - virtual void DeviceFoundCallback(int num_properties, - bt_property_t* properties); - virtual void DiscoveryStateChangedCallback(bt_discovery_state_t state); - virtual void PinRequestCallback(RawAddress* remote_bd_addr, - bt_bdname_t* bd_name, uint32_t cod, - bool min_16_digit); - virtual void SSPRequestCallback(RawAddress* remote_bd_addr, - bt_bdname_t* bd_name, uint32_t cod, - bt_ssp_variant_t pairing_variant, - uint32_t pass_key); - virtual void BondStateChangedCallback(bt_status_t status, - RawAddress* remote_bd_addr, - bt_bond_state_t state, - int fail_reason); - virtual void AclStateChangedCallback(bt_status_t status, - const RawAddress& remote_bdaddr, - 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); - virtual void LinkQualityReportCallback( - uint64_t timestamp, int report_id, int rssi, int snr, - int retransmission_count, int packets_not_receive_count, - int negative_acknowledgement_count); - - virtual void SwitchBufferSizeCallback(bool is_low_latency_buffer_size); - virtual void SwitchCodecCallback(bool is_low_latency_buffer_size); - - // TODO(armansito): Complete the list of callbacks. - }; - - // Initialize and clean up the BluetoothInterface singleton. Returns false if - // the underlying HAL interface failed to initialize, and true on success. - static bool Initialize(); - - // Shuts down and cleans up the interface. CleanUp must be called on the same - // thread that called Initialize. - static void CleanUp(); - - // Returns true if the interface was initialized and a global singleton has - // been created. - static bool IsInitialized(); - - // Initialize for testing. Use this to inject a test version of - // BlueoothInterface. To be used from unit tests only. - static void InitializeForTesting(BluetoothInterface* test_instance); - - // Returns the BluetoothInterface singleton. If the interface has not been - // initialized, returns nullptr. - static BluetoothInterface* Get(); - - // Add or remove an observer that is interested in notifications from us. - virtual void AddObserver(Observer* observer) = 0; - virtual void RemoveObserver(Observer* observer) = 0; - - // The HAL module pointer that represents the standard Bluetooth adapter - // management interface. This is implemented in and provided by the shared - // Bluetooth library, so this isn't owned by us. - // - // Upper layers can make bt_interface_t API calls through this structure. - // However, DO NOT call the "init" function as this is called and managed by - // us. The behavior is undefined if "init" is called directly by upper layers. - virtual const bt_interface_t* GetHALInterface() const = 0; - - // Returns the HAL callbacks that have been initialized previously. - virtual bt_callbacks_t* GetHALCallbacks() const = 0; - - protected: - BluetoothInterface() = default; - BluetoothInterface(const BluetoothInterface&) = delete; - BluetoothInterface& operator=(const BluetoothInterface&) = delete; - - virtual ~BluetoothInterface() = default; -}; - -} // namespace hal -} // namespace bluetooth diff --git a/system/service/hal/fake_bluetooth_av_interface.cc b/system/service/hal/fake_bluetooth_av_interface.cc deleted file mode 100644 index 64866a65b0..0000000000 --- a/system/service/hal/fake_bluetooth_av_interface.cc +++ /dev/null @@ -1,204 +0,0 @@ -// -// Copyright 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/hal/fake_bluetooth_av_interface.h" - -#include "types/raw_address.h" - -namespace bluetooth { -namespace hal { -namespace { - -// The global test handler instances. We have to have globals since the HAL -// interface methods all have to be global and their signatures don't allow us -// to pass in user_data. -std::shared_ptr<FakeBluetoothAvInterface::TestA2dpSourceHandler> - g_a2dp_source_handler{}; -std::shared_ptr<FakeBluetoothAvInterface::TestA2dpSinkHandler> - g_a2dp_sink_handler{}; - -bt_status_t FakeSourceInit( - btav_source_callbacks_t* callbacks, int max_connected_audio_devices, - const std::vector<btav_a2dp_codec_config_t>& codec_priorities, - const std::vector<btav_a2dp_codec_config_t>& offloading_preference) { - return BT_STATUS_SUCCESS; -} - -bt_status_t FakeSinkInit(btav_sink_callbacks_t* callbacks, - int max_connected_audio_devices) { - return BT_STATUS_SUCCESS; -} - -bt_status_t FakeConnect(const RawAddress& bd_addr) { - if (g_a2dp_source_handler) return g_a2dp_source_handler->Connect(bd_addr); - if (g_a2dp_sink_handler) return g_a2dp_sink_handler->Connect(bd_addr); - return BT_STATUS_FAIL; -} - -bt_status_t FakeDisconnect(const RawAddress& bd_addr) { - if (g_a2dp_source_handler) return g_a2dp_source_handler->Disconnect(bd_addr); - if (g_a2dp_sink_handler) return g_a2dp_sink_handler->Disconnect(bd_addr); - return BT_STATUS_FAIL; -} - -void FakeCleanup(void) {} - -void FakeSetAudioFocusState(int focus_state) { - if (g_a2dp_sink_handler) - return g_a2dp_sink_handler->SetAudioFocusState(focus_state); -} - -void FakeSetAudioTrackGain(float gain) { - if (g_a2dp_sink_handler) return g_a2dp_sink_handler->SetAudioTrackGain(gain); -} - -btav_source_interface_t fake_a2dp_source_interface = { - .size = sizeof(btav_source_interface_t), - .init = FakeSourceInit, - .connect = FakeConnect, - .disconnect = FakeDisconnect, - .set_silence_device = nullptr, - .set_active_device = nullptr, - .config_codec = nullptr, - .cleanup = FakeCleanup, -}; - -btav_sink_interface_t fake_a2dp_sink_interface = { - .size = sizeof(btav_sink_interface_t), - .init = FakeSinkInit, - .connect = FakeConnect, - .disconnect = FakeDisconnect, - .cleanup = FakeCleanup, - .set_audio_focus_state = FakeSetAudioFocusState, - .set_audio_track_gain = FakeSetAudioTrackGain, - .set_active_device = nullptr, -}; - -} // namespace - -FakeBluetoothAvInterface::FakeBluetoothAvInterface( - std::shared_ptr<TestA2dpSourceHandler> a2dp_source_handler) { - CHECK(!g_a2dp_source_handler); - - if (a2dp_source_handler) g_a2dp_source_handler = a2dp_source_handler; -} - -FakeBluetoothAvInterface::FakeBluetoothAvInterface( - std::shared_ptr<TestA2dpSinkHandler> a2dp_sink_handler) { - CHECK(!g_a2dp_sink_handler); - - if (a2dp_sink_handler) g_a2dp_sink_handler = a2dp_sink_handler; -} - -FakeBluetoothAvInterface::~FakeBluetoothAvInterface() { - g_a2dp_source_handler = {}; - g_a2dp_sink_handler = {}; -} - -void FakeBluetoothAvInterface::NotifyConnectionState( - const RawAddress& bda, btav_connection_state_t state) { - for (auto& observer : a2dp_source_observers_) { - observer.ConnectionStateCallback(this, bda, state); - } - for (auto& observer : a2dp_sink_observers_) { - observer.ConnectionStateCallback(this, bda, state); - } -} -void FakeBluetoothAvInterface::NotifyAudioState(const RawAddress& bda, - btav_audio_state_t state) { - for (auto& observer : a2dp_source_observers_) { - observer.AudioStateCallback(this, bda, state); - } - for (auto& observer : a2dp_sink_observers_) { - observer.AudioStateCallback(this, bda, state); - } -} -void FakeBluetoothAvInterface::NotifyAudioConfig( - const RawAddress& bda, const btav_a2dp_codec_config_t& codec_config, - const std::vector<btav_a2dp_codec_config_t> codecs_local_capabilities, - const std::vector<btav_a2dp_codec_config_t> - codecs_selectable_capabilities) { - for (auto& observer : a2dp_source_observers_) { - observer.AudioConfigCallback(this, bda, codec_config, - codecs_local_capabilities, - codecs_selectable_capabilities); - } -} -bool FakeBluetoothAvInterface::QueryMandatoryCodecPreferred( - const RawAddress& bda) { - // The mandatory codec is preferred only when all observers disable their - // optional codecs. - for (auto& observer : a2dp_source_observers_) { - if (!observer.MandatoryCodecPreferredCallback(this, bda)) { - return false; - } - } - return true; -} -void FakeBluetoothAvInterface::NotifyAudioConfig(const RawAddress& bda, - uint32_t sample_rate, - uint8_t channel_count) { - for (auto& observer : a2dp_sink_observers_) { - observer.AudioConfigCallback(this, bda, sample_rate, channel_count); - } -} - -bool FakeBluetoothAvInterface::A2dpSourceEnable( - std::vector<btav_a2dp_codec_config_t> codec_priorities) { - return true; -} - -void FakeBluetoothAvInterface::A2dpSourceDisable() {} - -bool FakeBluetoothAvInterface::A2dpSinkEnable() { return true; } - -void FakeBluetoothAvInterface::A2dpSinkDisable() {} - -void FakeBluetoothAvInterface::AddA2dpSourceObserver( - A2dpSourceObserver* observer) { - CHECK(observer); - a2dp_source_observers_.AddObserver(observer); -} - -void FakeBluetoothAvInterface::RemoveA2dpSourceObserver( - A2dpSourceObserver* observer) { - CHECK(observer); - a2dp_source_observers_.RemoveObserver(observer); -} - -void FakeBluetoothAvInterface::AddA2dpSinkObserver(A2dpSinkObserver* observer) { - CHECK(observer); - a2dp_sink_observers_.AddObserver(observer); -} - -void FakeBluetoothAvInterface::RemoveA2dpSinkObserver( - A2dpSinkObserver* observer) { - CHECK(observer); - a2dp_sink_observers_.RemoveObserver(observer); -} - -const btav_source_interface_t* -FakeBluetoothAvInterface::GetA2dpSourceHALInterface() { - return &fake_a2dp_source_interface; -} - -const btav_sink_interface_t* -FakeBluetoothAvInterface::GetA2dpSinkHALInterface() { - return &fake_a2dp_sink_interface; -} - -} // namespace hal -} // namespace bluetooth diff --git a/system/service/hal/fake_bluetooth_av_interface.h b/system/service/hal/fake_bluetooth_av_interface.h deleted file mode 100644 index e4a45ceeed..0000000000 --- a/system/service/hal/fake_bluetooth_av_interface.h +++ /dev/null @@ -1,101 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <base/observer_list.h> - -#include "abstract_observer_list.h" -#include "service/hal/bluetooth_av_interface.h" -#include "types/raw_address.h" - -namespace bluetooth { -namespace hal { - -class FakeBluetoothAvInterface : public BluetoothAvInterface { - public: - // Handles HAL Bluetooth A2DP API calls for testing. Test code can provide a - // fake or mock implementation of this and all calls will be routed to it. - class TestA2dpSourceHandler { - public: - virtual bt_status_t Connect(RawAddress bda) = 0; - virtual bt_status_t Disconnect(RawAddress bda) = 0; - - protected: - virtual ~TestA2dpSourceHandler() = default; - }; - class TestA2dpSinkHandler { - public: - virtual bt_status_t Connect(RawAddress bda) = 0; - virtual bt_status_t Disconnect(RawAddress bda) = 0; - virtual void SetAudioFocusState(int focus_state) = 0; - virtual void SetAudioTrackGain(float gain) = 0; - - protected: - virtual ~TestA2dpSinkHandler() = default; - }; - - // Constructs the fake with the given handlers. Implementations can - // provide their own handlers or simply pass "nullptr" for the default - // behavior in which BT_STATUS_FAIL will be returned from all calls. - FakeBluetoothAvInterface( - std::shared_ptr<TestA2dpSourceHandler> a2dp_source_handler); - FakeBluetoothAvInterface( - std::shared_ptr<TestA2dpSinkHandler> a2dp_sink_handler); - - FakeBluetoothAvInterface(const FakeBluetoothAvInterface&) = delete; - FakeBluetoothAvInterface& operator=(const FakeBluetoothAvInterface&) = delete; - - ~FakeBluetoothAvInterface(); - - // The methods below can be used to notify observers with certain events and - // given parameters. - - // A2DP common callbacks - void NotifyConnectionState(const RawAddress& bda, - btav_connection_state_t state); - void NotifyAudioState(const RawAddress& bda, btav_audio_state_t state); - // A2DP source callbacks - void NotifyAudioConfig( - const RawAddress& bda, const btav_a2dp_codec_config_t& codec_config, - const std::vector<btav_a2dp_codec_config_t> codecs_local_capabilities, - const std::vector<btav_a2dp_codec_config_t> - codecs_selectable_capabilities); - bool QueryMandatoryCodecPreferred(const RawAddress& bda); - // A2DP sink callbacks - void NotifyAudioConfig(const RawAddress& bda, uint32_t sample_rate, - uint8_t channel_count); - - // BluetoothAvInterface overrides: - bool A2dpSourceEnable( - std::vector<btav_a2dp_codec_config_t> codec_priorities) override; - void A2dpSourceDisable() override; - bool A2dpSinkEnable() override; - void A2dpSinkDisable() override; - void AddA2dpSourceObserver(A2dpSourceObserver* observer) override; - void RemoveA2dpSourceObserver(A2dpSourceObserver* observer) override; - void AddA2dpSinkObserver(A2dpSinkObserver* observer) override; - void RemoveA2dpSinkObserver(A2dpSinkObserver* observer) override; - const btav_source_interface_t* GetA2dpSourceHALInterface() override; - const btav_sink_interface_t* GetA2dpSinkHALInterface() override; - - private: - btbase::AbstractObserverList<A2dpSourceObserver> a2dp_source_observers_; - btbase::AbstractObserverList<A2dpSinkObserver> a2dp_sink_observers_; -}; - -} // namespace hal -} // namespace bluetooth diff --git a/system/service/hal/fake_bluetooth_gatt_interface.cc b/system/service/hal/fake_bluetooth_gatt_interface.cc deleted file mode 100644 index eb3d8152e6..0000000000 --- a/system/service/hal/fake_bluetooth_gatt_interface.cc +++ /dev/null @@ -1,345 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/hal/fake_bluetooth_gatt_interface.h" - -#include "types/raw_address.h" - -namespace bluetooth { -namespace hal { -namespace { - -// The global test handler instances. We have to have globals since the HAL -// interface methods all have to be global and their signatures don't allow us -// to pass in user_data. -std::shared_ptr<BleAdvertiserInterface> g_advertiser_handler; -std::shared_ptr<BleScannerInterface> g_scanner_handler; -std::shared_ptr<FakeBluetoothGattInterface::TestClientHandler> g_client_handler; -std::shared_ptr<FakeBluetoothGattInterface::TestServerHandler> g_server_handler; - -bt_status_t FakeRegisterClient(const bluetooth::Uuid& app_uuid, - bool eatt_support) { - if (g_client_handler) - return g_client_handler->RegisterClient(app_uuid, false); - - return BT_STATUS_FAIL; -} - -bt_status_t FakeUnregisterClient(int client_if) { - if (g_client_handler) return g_client_handler->UnregisterClient(client_if); - - return BT_STATUS_FAIL; -} - -bt_status_t FakeConnect(int client_if, const RawAddress& bd_addr, - bool is_direct, int transport, bool opportunistic, - int phy) { - if (g_client_handler) - return g_client_handler->Connect(client_if, bd_addr, is_direct, transport); - - return BT_STATUS_FAIL; -} - -bt_status_t FakeDisconnect(int client_if, const RawAddress& bd_addr, - int conn_id) { - if (g_client_handler) - return g_client_handler->Disconnect(client_if, bd_addr, conn_id); - - return BT_STATUS_FAIL; -} - -bt_status_t FakeRegisterServer(const bluetooth::Uuid& app_uuid, - bool eatt_support) { - if (g_server_handler) - return g_server_handler->RegisterServer(app_uuid, false); - - return BT_STATUS_FAIL; -} - -bt_status_t FakeUnregisterServer(int server_if) { - if (g_server_handler) return g_server_handler->UnregisterServer(server_if); - - return BT_STATUS_FAIL; -} - -bt_status_t FakeAddService(int server_if, const btgatt_db_element_t* service, - size_t service_count) { - if (g_server_handler) - return g_server_handler->AddService( - server_if, std::vector(service, service + service_count)); - - return BT_STATUS_FAIL; -} - -bt_status_t FakeDeleteService(int server_if, int srvc_handle) { - if (g_server_handler) - return g_server_handler->DeleteService(server_if, srvc_handle); - - return BT_STATUS_FAIL; -} - -bt_status_t FakeSendIndication(int server_if, int attribute_handle, int conn_id, - int confirm, const uint8_t* value, - size_t length) { - if (g_server_handler) - return g_server_handler->SendIndication(server_if, attribute_handle, - conn_id, confirm, - std::vector(value, value + length)); - - return BT_STATUS_FAIL; -} - -bt_status_t FakeSendResponse(int conn_id, int trans_id, int status, - const btgatt_response_t& response) { - if (g_server_handler) - return g_server_handler->SendResponse(conn_id, trans_id, status, response); - - return BT_STATUS_FAIL; -} - -btgatt_client_interface_t fake_btgattc_iface = { - FakeRegisterClient, - FakeUnregisterClient, - FakeConnect, - FakeDisconnect, - nullptr, // refresh - nullptr, // search_service - nullptr, // discover_service_by_uuid - nullptr, // read_characteristic - nullptr, // read_using_characteristic_uuid - nullptr, // write_characteristic - nullptr, // read_descriptor - nullptr, // write_descriptor - nullptr, // execute_write - nullptr, // register_for_notification - nullptr, // deregister_for_notification - nullptr, // read_remote_rssi - nullptr, // get_device_type - nullptr, // configure_mtu - nullptr, // conn_parameter_update - nullptr, // set_phy - nullptr, // read_phy - nullptr, // test_command - nullptr, // get_gatt_db - nullptr, // subrate_request -}; - -btgatt_server_interface_t fake_btgatts_iface = { - FakeRegisterServer, - FakeUnregisterServer, - nullptr, // connect - nullptr, // disconnect - FakeAddService, - nullptr, // stop_service - FakeDeleteService, - FakeSendIndication, - FakeSendResponse, - nullptr, // set_phy - nullptr, // read_phy -}; - -} // namespace - -FakeBluetoothGattInterface::FakeBluetoothGattInterface( - std::shared_ptr<BleAdvertiserInterface> advertiser_handler, - std::shared_ptr<BleScannerInterface> scanner_handler, - std::shared_ptr<TestClientHandler> client_handler, - std::shared_ptr<TestServerHandler> server_handler) - : client_handler_(client_handler) { - CHECK(!g_advertiser_handler); - CHECK(!g_scanner_handler); - CHECK(!g_client_handler); - CHECK(!g_server_handler); - - // We allow passing NULL. In this case all calls we fail by default. - if (advertiser_handler) g_advertiser_handler = advertiser_handler; - - if (scanner_handler) g_scanner_handler = scanner_handler; - - if (client_handler) g_client_handler = client_handler; - - if (server_handler) g_server_handler = server_handler; -} - -FakeBluetoothGattInterface::~FakeBluetoothGattInterface() { - if (g_advertiser_handler) g_advertiser_handler = nullptr; - - if (g_scanner_handler) g_scanner_handler = nullptr; - - if (g_client_handler) g_client_handler = nullptr; - - if (g_server_handler) g_server_handler = nullptr; -} - -// The methods below can be used to notify observers with certain events and -// given parameters. -void FakeBluetoothGattInterface::NotifyScanResultCallback( - const RawAddress& bda, int rssi, std::vector<uint8_t> adv_data) { - for (auto& observer : scanner_observers_) { - observer.ScanResultCallback(this, bda, rssi, adv_data); - } -} - -void FakeBluetoothGattInterface::NotifyRegisterClientCallback( - int status, int client_if, const bluetooth::Uuid& app_uuid) { - for (auto& observer : client_observers_) { - observer.RegisterClientCallback(this, status, client_if, app_uuid); - } -} - -void FakeBluetoothGattInterface::NotifyConnectCallback(int conn_id, int status, - int client_if, - const RawAddress& bda) { - for (auto& observer : client_observers_) { - observer.ConnectCallback(this, conn_id, status, client_if, bda); - } -} - -void FakeBluetoothGattInterface::NotifyDisconnectCallback( - int conn_id, int status, int client_if, const RawAddress& bda) { - for (auto& observer : client_observers_) { - observer.DisconnectCallback(this, conn_id, status, client_if, bda); - } -} - -void FakeBluetoothGattInterface::NotifyRegisterServerCallback( - int status, int server_if, const Uuid& app_uuid) { - for (auto& observer : server_observers_) { - observer.RegisterServerCallback(this, status, server_if, app_uuid); - } -} - -void FakeBluetoothGattInterface::NotifyServerConnectionCallback( - int conn_id, int server_if, int connected, const RawAddress& bda) { - for (auto& observer : server_observers_) { - observer.ConnectionCallback(this, conn_id, server_if, connected, bda); - } -} - -void FakeBluetoothGattInterface::NotifyServiceAddedCallback( - int status, int server_if, std::vector<btgatt_db_element_t> service) { - for (auto& observer : server_observers_) { - observer.ServiceAddedCallback(this, status, server_if, service); - } -} - -void FakeBluetoothGattInterface::NotifyRequestReadCharacteristicCallback( - int conn_id, int trans_id, const RawAddress& bda, int attr_handle, - int offset, bool is_long) { - for (auto& observer : server_observers_) { - observer.RequestReadCharacteristicCallback(this, conn_id, trans_id, bda, - attr_handle, offset, is_long); - } -} - -void FakeBluetoothGattInterface::NotifyRequestReadDescriptorCallback( - int conn_id, int trans_id, const RawAddress& bda, int attr_handle, - int offset, bool is_long) { - for (auto& observer : server_observers_) { - observer.RequestReadDescriptorCallback(this, conn_id, trans_id, bda, - attr_handle, offset, is_long); - } -} - -void FakeBluetoothGattInterface::NotifyRequestWriteCharacteristicCallback( - int conn_id, int trans_id, const RawAddress& bda, int attr_handle, - int offset, bool need_rsp, bool is_prep, std::vector<uint8_t> value) { - for (auto& observer : server_observers_) { - observer.RequestWriteCharacteristicCallback(this, conn_id, trans_id, bda, - attr_handle, offset, need_rsp, - is_prep, value); - } -} - -void FakeBluetoothGattInterface::NotifyRequestWriteDescriptorCallback( - int conn_id, int trans_id, const RawAddress& bda, int attr_handle, - int offset, bool need_rsp, bool is_prep, std::vector<uint8_t> value) { - for (auto& observer : server_observers_) { - observer.RequestWriteDescriptorCallback(this, conn_id, trans_id, bda, - attr_handle, offset, need_rsp, - is_prep, value); - } -} - -void FakeBluetoothGattInterface::NotifyRequestExecWriteCallback( - int conn_id, int trans_id, const RawAddress& bda, int exec_write) { - for (auto& observer : server_observers_) { - observer.RequestExecWriteCallback(this, conn_id, trans_id, bda, exec_write); - } -} - -void FakeBluetoothGattInterface::NotifyIndicationSentCallback(int conn_id, - int status) { - for (auto& observer : server_observers_) { - observer.IndicationSentCallback(this, conn_id, status); - } -} - -void FakeBluetoothGattInterface::AddScannerObserver(ScannerObserver* observer) { - CHECK(observer); - scanner_observers_.AddObserver(observer); -} - -void FakeBluetoothGattInterface::RemoveScannerObserver( - ScannerObserver* observer) { - CHECK(observer); - scanner_observers_.RemoveObserver(observer); -} - -void FakeBluetoothGattInterface::AddClientObserver(ClientObserver* observer) { - CHECK(observer); - client_observers_.AddObserver(observer); -} - -void FakeBluetoothGattInterface::RemoveClientObserver( - ClientObserver* observer) { - CHECK(observer); - client_observers_.RemoveObserver(observer); -} - -void FakeBluetoothGattInterface::AddServerObserver(ServerObserver* observer) { - CHECK(observer); - server_observers_.AddObserver(observer); -} - -void FakeBluetoothGattInterface::RemoveServerObserver( - ServerObserver* observer) { - CHECK(observer); - server_observers_.RemoveObserver(observer); -} - -BleAdvertiserInterface* FakeBluetoothGattInterface::GetAdvertiserHALInterface() - const { - return g_advertiser_handler.get(); -} - -BleScannerInterface* FakeBluetoothGattInterface::GetScannerHALInterface() - const { - return g_scanner_handler.get(); -} - -const btgatt_client_interface_t* -FakeBluetoothGattInterface::GetClientHALInterface() const { - return &fake_btgattc_iface; -} - -const btgatt_server_interface_t* -FakeBluetoothGattInterface::GetServerHALInterface() const { - return &fake_btgatts_iface; -} - -} // namespace hal -} // namespace bluetooth diff --git a/system/service/hal/fake_bluetooth_gatt_interface.h b/system/service/hal/fake_bluetooth_gatt_interface.h deleted file mode 100644 index eb3b9bf342..0000000000 --- a/system/service/hal/fake_bluetooth_gatt_interface.h +++ /dev/null @@ -1,158 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <base/observer_list.h> - -#include <vector> - -#include "abstract_observer_list.h" -#include "service/hal/bluetooth_gatt_interface.h" -#include "types/raw_address.h" - -namespace bluetooth { -namespace hal { - -class FakeBluetoothGattInterface : public BluetoothGattInterface { - public: - // Handles HAL Bluetooth GATT client API calls for testing. Test code can - // provide a fake or mock implementation of this and all calls will be routed - // to it. - class TestClientHandler { - public: - virtual ~TestClientHandler() = default; - - virtual bt_status_t RegisterClient(const bluetooth::Uuid& app_uuid, - bool eatt_support) = 0; - virtual bt_status_t UnregisterClient(int client_if) = 0; - - virtual bt_status_t Connect(int client_if, const RawAddress& bd_addr, - bool is_direct, int transport) = 0; - virtual bt_status_t Disconnect(int client_if, const RawAddress& bd_addr, - int conn_id) = 0; - }; - - // Handles HAL Bluetooth GATT server API calls for testing. Test code can - // provide a fake or mock implementation of this and all calls will be routed - // to it. - class TestServerHandler { - public: - virtual ~TestServerHandler() = default; - - virtual bt_status_t RegisterServer(const bluetooth::Uuid& app_uuid, - bool eatt_support) = 0; - virtual bt_status_t UnregisterServer(int server_if) = 0; - virtual bt_status_t AddService( - int server_if, std::vector<btgatt_db_element_t> service) = 0; - virtual bt_status_t DeleteService(int server_if, int srvc_handle) = 0; - virtual bt_status_t SendIndication(int server_if, int attribute_handle, - int conn_id, int confirm, - std::vector<uint8_t> value) = 0; - virtual bt_status_t SendResponse(int conn_id, int trans_id, int status, - const btgatt_response_t& response) = 0; - }; - - // Constructs the fake with the given handlers. Implementations can - // provide their own handlers or simply pass "nullptr" for the default - // behavior in which BT_STATUS_FAIL will be returned from all calls. - FakeBluetoothGattInterface( - std::shared_ptr<BleAdvertiserInterface> advertiser_handler, - std::shared_ptr<BleScannerInterface> scanner_handler, - std::shared_ptr<TestClientHandler> client_handler, - std::shared_ptr<TestServerHandler> server_handler); - - FakeBluetoothGattInterface(const FakeBluetoothGattInterface&) = delete; - FakeBluetoothGattInterface& operator=(const FakeBluetoothGattInterface&) = - delete; - - ~FakeBluetoothGattInterface(); - - // The methods below can be used to notify observers with certain events and - // given parameters. - - void NotifyRegisterScannerCallback(int status, int client_if, - const bluetooth::Uuid& app_uuid); - void NotifyScanResultCallback(const RawAddress& bda, int rssi, - std::vector<uint8_t> adv_data); - - // Client callbacks: - void NotifyRegisterClientCallback(int status, int client_if, - const bluetooth::Uuid& app_uuid); - void NotifyConnectCallback(int conn_id, int status, int client_if, - const RawAddress& bda); - void NotifyDisconnectCallback(int conn_id, int status, int client_if, - const RawAddress& bda); - - // Server callbacks: - void NotifyRegisterServerCallback(int status, int server_if, - const bluetooth::Uuid& app_uuid); - void NotifyServerConnectionCallback(int conn_id, int server_if, int connected, - const RawAddress& bda); - void NotifyServiceAddedCallback(int status, int server_if, - std::vector<btgatt_db_element_t> srvc); - void NotifyCharacteristicAddedCallback(int status, int server_if, - const bluetooth::Uuid& uuid, - int srvc_handle, int char_handle); - void NotifyDescriptorAddedCallback(int status, int server_if, - const bluetooth::Uuid& uuid, - int srvc_handle, int desc_handle); - void NotifyServiceStartedCallback(int status, int server_if, int srvc_handle); - void NotifyRequestReadCharacteristicCallback(int conn_id, int trans_id, - const RawAddress& bda, - int attr_handle, int offset, - bool is_long); - void NotifyRequestReadDescriptorCallback(int conn_id, int trans_id, - const RawAddress& bda, - int attr_handle, int offset, - bool is_long); - void NotifyRequestWriteCharacteristicCallback(int conn_id, int trans_id, - const RawAddress& bda, - int attr_handle, int offset, - bool need_rsp, bool is_prep, - std::vector<uint8_t> value); - void NotifyRequestWriteDescriptorCallback(int conn_id, int trans_id, - const RawAddress& bda, - int attr_handle, int offset, - bool need_rsp, bool is_prep, - std::vector<uint8_t> value); - void NotifyRequestExecWriteCallback(int conn_id, int trans_id, - const RawAddress& bda, int exec_write); - void NotifyIndicationSentCallback(int conn_id, int status); - - // BluetoothGattInterface overrides: - void AddScannerObserver(ScannerObserver* observer) override; - void RemoveScannerObserver(ScannerObserver* observer) override; - void AddClientObserver(ClientObserver* observer) override; - void RemoveClientObserver(ClientObserver* observer) override; - void AddServerObserver(ServerObserver* observer) override; - void RemoveServerObserver(ServerObserver* observer) override; - BleAdvertiserInterface* GetAdvertiserHALInterface() const override; - BleScannerInterface* GetScannerHALInterface() const override; - const btgatt_client_interface_t* GetClientHALInterface() const override; - const btgatt_server_interface_t* GetServerHALInterface() const override; - - private: - btbase::AbstractObserverList<ScannerObserver> scanner_observers_; - btbase::AbstractObserverList<ClientObserver> client_observers_; - btbase::AbstractObserverList<ServerObserver> server_observers_; - std::shared_ptr<BleScannerInterface> scanner_handler_; - std::shared_ptr<TestClientHandler> client_handler_; - std::shared_ptr<TestServerHandler> server_handler_; -}; - -} // namespace hal -} // namespace bluetooth diff --git a/system/service/hal/fake_bluetooth_interface.cc b/system/service/hal/fake_bluetooth_interface.cc deleted file mode 100644 index 9bdc2bd519..0000000000 --- a/system/service/hal/fake_bluetooth_interface.cc +++ /dev/null @@ -1,190 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/hal/fake_bluetooth_interface.h" - -#include "types/raw_address.h" - -namespace bluetooth { -namespace hal { - -namespace { - -FakeBluetoothInterface::Manager g_hal_manager; - -int FakeHALEnable() { - return g_hal_manager.enable_succeed ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; -} - -int FakeHALDisable() { - return g_hal_manager.disable_succeed ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; -} - -int FakeHALGetAdapterProperties() { return BT_STATUS_SUCCESS; } - -int FakeHALSetAdapterProperty(const bt_property_t* /* property */) { - LOG(INFO) << __func__; - return (g_hal_manager.set_property_succeed ? BT_STATUS_SUCCESS - : BT_STATUS_FAIL); -} - -bt_interface_t fake_bt_iface = { - sizeof(bt_interface_t), - nullptr, /* init */ - FakeHALEnable, - FakeHALDisable, - nullptr, /* cleanup */ - FakeHALGetAdapterProperties, - nullptr, /* get_adapter_property */ - FakeHALSetAdapterProperty, - nullptr, /* get_remote_device_properties */ - nullptr, /* get_remote_device_property */ - nullptr, /* set_remote_device_property */ - nullptr, /* get_remote_service_record */ - nullptr, /* get_remote_services */ - nullptr, /* start_discovery */ - nullptr, /* cancel_discovery */ - nullptr, /* create_bond */ - nullptr, /* create_bond_le */ - nullptr, /* create_bond_out_of_band */ - nullptr, /* remove_bond */ - nullptr, /* cancel_bond */ - nullptr, /* get_connection_state */ - nullptr, /* pin_reply */ - nullptr, /* ssp_reply */ - nullptr, /* get_profile_interface */ - nullptr, /* set_os_callouts */ - nullptr, /* read_energy_info */ - nullptr, /* dump */ - nullptr, /* dumpMetrics */ - nullptr, /* config clear */ - nullptr, /* interop_database_clear */ - nullptr, /* interop_database_add */ - nullptr, /* get_avrcp_service */ - nullptr, /* obfuscate_address */ - nullptr, /* get_metric_id */ - nullptr, /* set_dynamic_audio_buffer_size */ - nullptr, /* generate_local_oob_data */ - nullptr, /* allow_low_latency_audio */ - nullptr, /* clear_event_filter */ - nullptr, /* clear_event_mask */ - nullptr, /* clear_filter_accept_list */ - nullptr, /* disconnect_all_acls */ - nullptr, /* le_rand */ - nullptr, /* set_event_filter_connection_setup_all_devices */ - nullptr, /* allow_wake_by_hid */ - nullptr, /* restore_filter_accept_list */ - nullptr, /* set_default_event_mask_except */ - nullptr, /* set_event_filter_inquiry_result_all_devices */ - nullptr, /* get_wbs_supported */ - nullptr, /* metadata_changed */ - nullptr, /* interop_match_addr */ - nullptr, /* interop_match_name */ - nullptr, /* interop_match_addr_or_name */ - nullptr, /* interop_database_add_remove_addr */ - nullptr, /* interop_database_add_remove_name */ -}; - -} // namespace - -// static -FakeBluetoothInterface::Manager* FakeBluetoothInterface::GetManager() { - return &g_hal_manager; -} - -FakeBluetoothInterface::Manager::Manager() - : enable_succeed(false), - disable_succeed(false), - set_property_succeed(false) {} - -void FakeBluetoothInterface::NotifyAdapterStateChanged(bt_state_t state) { - for (auto& observer : observers_) { - observer.AdapterStateChangedCallback(state); - } -} - -void FakeBluetoothInterface::NotifyAdapterPropertiesChanged( - int num_properties, bt_property_t* properties) { - for (auto& observer : observers_) { - observer.AdapterPropertiesCallback(BT_STATUS_SUCCESS, num_properties, - properties); - } -} - -void FakeBluetoothInterface::NotifyAdapterNamePropertyChanged( - const std::string& name) { - bt_bdname_t hal_name; - strncpy(reinterpret_cast<char*>(hal_name.name), name.c_str(), - std::min(sizeof(hal_name) - 1, name.length())); - reinterpret_cast<char*>(hal_name.name)[name.length()] = '\0'; - - bt_property_t property; - property.len = sizeof(hal_name); - property.val = &hal_name; - property.type = BT_PROPERTY_BDNAME; - - NotifyAdapterPropertiesChanged(1, &property); -} - -void FakeBluetoothInterface::NotifyAdapterAddressPropertyChanged( - const RawAddress* address) { - bt_property_t property; - property.len = RawAddress::kLength; - property.val = (void*)address->address; - property.type = BT_PROPERTY_BDADDR; - - NotifyAdapterPropertiesChanged(1, &property); -} - -void FakeBluetoothInterface::NotifyAdapterLocalLeFeaturesPropertyChanged( - const bt_local_le_features_t* features) { - bt_property_t property; - property.len = sizeof(*features); - property.val = (void*)features; - property.type = BT_PROPERTY_LOCAL_LE_FEATURES; - - NotifyAdapterPropertiesChanged(1, &property); -} - -void FakeBluetoothInterface::NotifyAclStateChangedCallback( - bt_status_t status, const RawAddress& remote_bdaddr, 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) { - for (auto& observer : observers_) { - observer.AclStateChangedCallback(status, remote_bdaddr, state, - transport_link_type, hci_reason, direction, - acl_handle); - } -} - -void FakeBluetoothInterface::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} - -void FakeBluetoothInterface::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} - -const bt_interface_t* FakeBluetoothInterface::GetHALInterface() const { - return &fake_bt_iface; -} - -bt_callbacks_t* FakeBluetoothInterface::GetHALCallbacks() const { - return nullptr; -} - -} // namespace hal -} // namespace bluetooth diff --git a/system/service/hal/fake_bluetooth_interface.h b/system/service/hal/fake_bluetooth_interface.h deleted file mode 100644 index 28ed335686..0000000000 --- a/system/service/hal/fake_bluetooth_interface.h +++ /dev/null @@ -1,77 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include <base/observer_list.h> - -#include "abstract_observer_list.h" -#include "service/hal/bluetooth_interface.h" -#include "types/raw_address.h" - -namespace bluetooth { -namespace hal { - -class FakeBluetoothInterface : public BluetoothInterface { - public: - // A Fake HAL Bluetooth interface. This is kept as a global singleton as the - // Bluetooth HAL doesn't support anything otherwise. - // - // TODO(armansito): Use an abstract "TestHandler" interface instead. - struct Manager { - Manager(); - ~Manager() = default; - - // Values that should be returned from bt_interface_t methods. - bool enable_succeed; - bool disable_succeed; - bool set_property_succeed; - }; - - // Returns the global Manager. - static Manager* GetManager(); - - FakeBluetoothInterface() = default; - FakeBluetoothInterface(const FakeBluetoothInterface&) = delete; - FakeBluetoothInterface& operator=(const FakeBluetoothInterface&) = delete; - - ~FakeBluetoothInterface() override = default; - - // Notifies the observers that the adapter state changed to |state|. - void NotifyAdapterStateChanged(bt_state_t state); - - // Triggers an adapter property change event. - void NotifyAdapterPropertiesChanged(int num_properties, - bt_property_t* properties); - void NotifyAdapterNamePropertyChanged(const std::string& name); - void NotifyAdapterAddressPropertyChanged(const RawAddress* address); - void NotifyAdapterLocalLeFeaturesPropertyChanged( - const bt_local_le_features_t* features); - void NotifyAclStateChangedCallback( - bt_status_t status, const RawAddress& remote_bdaddr, 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::BluetoothInterface overrides: - void AddObserver(Observer* observer) override; - void RemoveObserver(Observer* observer) override; - const bt_interface_t* GetHALInterface() const override; - bt_callbacks_t* GetHALCallbacks() const override; - - private: - btbase::AbstractObserverList<Observer> observers_; -}; - -} // namespace hal -} // namespace bluetooth diff --git a/system/service/ipc/binder/bluetooth_a2dp_sink_binder_server.cc b/system/service/ipc/binder/bluetooth_a2dp_sink_binder_server.cc deleted file mode 100644 index 1609aa8516..0000000000 --- a/system/service/ipc/binder/bluetooth_a2dp_sink_binder_server.cc +++ /dev/null @@ -1,222 +0,0 @@ -// -// Copyright 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include "service/ipc/binder/bluetooth_a2dp_sink_binder_server.h" - -#include <base/logging.h> - -#include "service/adapter.h" - -using android::String16; -using android::String8; -using android::binder::Status; - -using android::bluetooth::IBluetoothA2dpSinkCallback; - -namespace ipc { -namespace binder { - -BluetoothA2dpSinkBinderServer::BluetoothA2dpSinkBinderServer( - bluetooth::Adapter* adapter) - : adapter_(adapter) { - CHECK(adapter); -} - -Status BluetoothA2dpSinkBinderServer::Register( - const android::sp<IBluetoothA2dpSinkCallback>& callback, - bool* _aidl_return) { - auto factory = adapter_->GetA2dpSinkFactory(); - *_aidl_return = RegisterInstanceBase(callback, factory); - return Status::ok(); -} - -Status BluetoothA2dpSinkBinderServer::Unregister() { - UnregisterAllBase(); - return Status::ok(); -} - -Status BluetoothA2dpSinkBinderServer::Enable(bool* _aidl_return) { - std::lock_guard<std::mutex> lock(*maps_lock()); - auto a2dp_sink = GetA2dpSink(); - if (!a2dp_sink) { - LOG(ERROR) << "Failed to get A2DP sink instance"; - *_aidl_return = false; - return Status::ok(); - } - - if (!a2dp_sink->Enable()) { - LOG(ERROR) << "Failed to enable"; - *_aidl_return = false; - return Status::ok(); - } - - *_aidl_return = true; - return Status::ok(); -} - -Status BluetoothA2dpSinkBinderServer::Disable(bool* _aidl_return) { - std::lock_guard<std::mutex> lock(*maps_lock()); - auto a2dp_sink = GetA2dpSink(); - if (!a2dp_sink) { - LOG(ERROR) << "Failed to get A2DP sink instance"; - *_aidl_return = false; - return Status::ok(); - } - - a2dp_sink->Disable(); - *_aidl_return = true; - return Status::ok(); -} - -Status BluetoothA2dpSinkBinderServer::Connect(const String16& device_address, - bool* _aidl_return) { - std::lock_guard<std::mutex> lock(*maps_lock()); - auto a2dp_sink = GetA2dpSink(); - if (!a2dp_sink) { - LOG(ERROR) << "Failed to get A2DP sink instance"; - *_aidl_return = false; - return Status::ok(); - } - - if (!a2dp_sink->Connect(String8(device_address).string())) { - LOG(ERROR) << "Failed to connect"; - *_aidl_return = false; - return Status::ok(); - } - - *_aidl_return = true; - return Status::ok(); -} - -Status BluetoothA2dpSinkBinderServer::Disconnect(const String16& device_address, - bool* _aidl_return) { - std::lock_guard<std::mutex> lock(*maps_lock()); - auto a2dp_sink = GetA2dpSink(); - if (!a2dp_sink) { - LOG(ERROR) << "Failed to get A2DP sink instance"; - *_aidl_return = false; - return Status::ok(); - } - - if (!a2dp_sink->Disconnect(String8(device_address).string())) { - LOG(ERROR) << "Failed to connect"; - *_aidl_return = false; - return Status::ok(); - } - - *_aidl_return = true; - return Status::ok(); -} - -Status BluetoothA2dpSinkBinderServer::SetAudioFocusState(int focus_state, - bool* _aidl_return) { - std::lock_guard<std::mutex> lock(*maps_lock()); - auto a2dp_sink = GetA2dpSink(); - if (!a2dp_sink) { - LOG(ERROR) << "Failed to get A2DP instance"; - *_aidl_return = false; - return Status::ok(); - } - - a2dp_sink->SetAudioFocusState(focus_state); - *_aidl_return = true; - return Status::ok(); -} - -Status BluetoothA2dpSinkBinderServer::SetAudioTrackGain(float gain, - bool* _aidl_return) { - std::lock_guard<std::mutex> lock(*maps_lock()); - auto a2dp_sink = GetA2dpSink(); - if (!a2dp_sink) { - LOG(ERROR) << "Failed to get A2DP instance"; - *_aidl_return = false; - return Status::ok(); - } - - a2dp_sink->SetAudioTrackGain(gain); - *_aidl_return = true; - return Status::ok(); -} - -void BluetoothA2dpSinkBinderServer::OnConnectionState( - const std::string& device_address, int state) { - std::lock_guard<std::mutex> lock(*maps_lock()); - auto cb = GetA2dpSinkCallback(); - if (!cb.get()) { - LOG(WARNING) << "Callback for this GattServer was deleted."; - return; - } - - cb->OnConnectionState(String16(device_address.c_str()), state); -} - -void BluetoothA2dpSinkBinderServer::OnAudioState( - const std::string& device_address, int state) { - std::lock_guard<std::mutex> lock(*maps_lock()); - auto cb = GetA2dpSinkCallback(); - if (!cb.get()) { - LOG(WARNING) << "Callback for this GattServer was deleted."; - return; - } - - cb->OnAudioState(String16(device_address.c_str()), state); -} - -void BluetoothA2dpSinkBinderServer::OnAudioConfig( - const std::string& device_address, uint32_t sample_rate, - uint8_t channel_count) { - std::lock_guard<std::mutex> lock(*maps_lock()); - auto cb = GetA2dpSinkCallback(); - if (!cb.get()) { - LOG(WARNING) << "Callback for this GattServer was deleted."; - return; - } - - cb->OnAudioConfig(String16(device_address.c_str()), sample_rate, - channel_count); -} - -bool BluetoothA2dpSinkBinderServer::HasInstance() { - return GetA2dpSink() != nullptr; -} - -android::sp<IBluetoothA2dpSinkCallback> -BluetoothA2dpSinkBinderServer::GetA2dpSinkCallback() { - auto cb = GetCallback(bluetooth::A2dpSink::kSingletonInstanceId); - return android::sp<IBluetoothA2dpSinkCallback>( - static_cast<IBluetoothA2dpSinkCallback*>(cb.get())); -} - -std::shared_ptr<bluetooth::A2dpSink> -BluetoothA2dpSinkBinderServer::GetA2dpSink() { - return std::static_pointer_cast<bluetooth::A2dpSink>( - GetInstance(bluetooth::A2dpSink::kSingletonInstanceId)); -} - -void BluetoothA2dpSinkBinderServer::OnRegisterInstanceImpl( - bluetooth::BLEStatus status, android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) { - VLOG(1) << __func__ << " instance ID: " << instance->GetInstanceId() - << " status: " << status; - bluetooth::A2dpSink* a2dp_sink = static_cast<bluetooth::A2dpSink*>(instance); - a2dp_sink->SetDelegate(this); - - android::sp<IBluetoothA2dpSinkCallback> cb( - static_cast<IBluetoothA2dpSinkCallback*>(callback.get())); - cb->OnRegistered(status); -} - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_a2dp_sink_binder_server.h b/system/service/ipc/binder/bluetooth_a2dp_sink_binder_server.h deleted file mode 100644 index f54733cfa0..0000000000 --- a/system/service/ipc/binder/bluetooth_a2dp_sink_binder_server.h +++ /dev/null @@ -1,86 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <map> -#include <string> - -#include <android/bluetooth/BnBluetoothA2dpSink.h> -#include <android/bluetooth/IBluetoothA2dpSinkCallback.h> - -#include "service/a2dp_sink.h" -#include "service/ipc/binder/interface_with_instances_base.h" - -namespace bluetooth { -class Adapter; -} // namespace bluetooth - -namespace ipc { -namespace binder { - -class BluetoothA2dpSinkBinderServer - : public InterfaceWithInstancesBase, - public android::bluetooth::BnBluetoothA2dpSink, - public bluetooth::A2dpSink::Delegate { - public: - explicit BluetoothA2dpSinkBinderServer(bluetooth::Adapter* adapter); - BluetoothA2dpSinkBinderServer(const BluetoothA2dpSinkBinderServer&) = delete; - BluetoothA2dpSinkBinderServer& operator=( - const BluetoothA2dpSinkBinderServer&) = delete; - - ~BluetoothA2dpSinkBinderServer() override = default; - - // IBluetoothA2dpSink implementation: - android::binder::Status Register( - const android::sp<android::bluetooth::IBluetoothA2dpSinkCallback>& - callback, - bool* _aidl_return) override; - android::binder::Status Enable(bool* _aidl_return) override; - android::binder::Status Disable(bool* _aidl_return) override; - android::binder::Status Unregister() override; - android::binder::Status Connect(const android::String16& device_address, - bool* _aidl_return) override; - android::binder::Status Disconnect(const android::String16& device_address, - bool* _aidl_return) override; - android::binder::Status SetAudioFocusState(int state, - bool* _aidl_return) override; - android::binder::Status SetAudioTrackGain(float gain, - bool* _aidl_return) override; - - // bluetooth::bluetooth::A2dpSink::Delegate implementation: - void OnConnectionState(const std::string& device_address, int state) override; - void OnAudioState(const std::string& device_address, int state) override; - void OnAudioConfig(const std::string& device_address, uint32_t sample_rate, - uint8_t channel_count) override; - - bool HasInstance(); - - private: - android::sp<android::bluetooth::IBluetoothA2dpSinkCallback> - GetA2dpSinkCallback(); - std::shared_ptr<bluetooth::A2dpSink> GetA2dpSink(); - - // InterfaceWithInstancesBase override: - void OnRegisterInstanceImpl(bluetooth::BLEStatus status, - android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) override; - - bluetooth::Adapter* adapter_; // weak -}; - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_a2dp_source_binder_server.cc b/system/service/ipc/binder/bluetooth_a2dp_source_binder_server.cc deleted file mode 100644 index 51e6dffc0c..0000000000 --- a/system/service/ipc/binder/bluetooth_a2dp_source_binder_server.cc +++ /dev/null @@ -1,226 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include "service/ipc/binder/bluetooth_a2dp_source_binder_server.h" - -#include <base/logging.h> - -#include "service/adapter.h" - -#define AIDL_RET(value) \ - do { \ - *_aidl_return = (value); \ - return Status::ok(); \ - } while (0) - -#define TRY_GET_SOURCE() \ - ({ \ - auto source = GetA2dpSource(); \ - if (!source) { \ - LOG(ERROR) << __func__ << ": " \ - << "Failed to get A2DP source interface"; \ - AIDL_RET(false); \ - } \ - source; \ - }) - -#define TRY_GET_CB() \ - ({ \ - auto cb = GetA2dpSourceCallback(); \ - if (!cb.get()) { \ - LOG(WARNING) << "Callback for A2DP SOURCE was deleted"; \ - return; \ - } \ - cb; \ - }) - -#define TRY_RET(expr, msg) \ - do { \ - if (!(expr)) { \ - LOG(ERROR) << msg; \ - AIDL_RET(false); \ - } \ - AIDL_RET(true); \ - } while (0) - -#define TRY_RET_FUNC(expr) TRY_RET(expr, __func__ << " failed") - -using android::String16; -using android::String8; -using android::binder::Status; -using android::bluetooth::BluetoothA2dpCodecConfig; -using android::bluetooth::IBluetoothA2dpSourceCallback; - -using LockGuard = std::lock_guard<std::mutex>; - -namespace ipc { -namespace binder { - -namespace { - -std::vector<bluetooth::A2dpCodecConfig> A2dpCodecsFromBinder( - const std::vector<BluetoothA2dpCodecConfig>& codecs) { - std::vector<bluetooth::A2dpCodecConfig> ret; - ret.reserve(codecs.size()); - for (const auto& config : codecs) { - ret.push_back(config); - } - - return ret; -} - -std::vector<BluetoothA2dpCodecConfig> A2dpCodecsToBinder( - const std::vector<bluetooth::A2dpCodecConfig>& codecs) { - std::vector<BluetoothA2dpCodecConfig> ret; - ret.reserve(codecs.size()); - for (const auto& config : codecs) { - ret.push_back(config); - } - - return ret; -} - -} // namespace - -BluetoothA2dpSourceBinderServer::BluetoothA2dpSourceBinderServer( - bluetooth::Adapter* adapter) - : adapter_(adapter) { - CHECK(adapter); -} - -BluetoothA2dpSourceBinderServer::~BluetoothA2dpSourceBinderServer() = default; - -bool BluetoothA2dpSourceBinderServer::HasInstance() { - return GetA2dpSource() != nullptr; -} - -Status BluetoothA2dpSourceBinderServer::Register( - const android::sp<IBluetoothA2dpSourceCallback>& callback, - bool* _aidl_return) { - auto factory = adapter_->GetA2dpSourceFactory(); - *_aidl_return = RegisterInstanceBase(callback, factory); - return Status::ok(); -} - -Status BluetoothA2dpSourceBinderServer::Unregister() { - UnregisterAllBase(); - return Status::ok(); -} - -Status BluetoothA2dpSourceBinderServer::Enable( - const std::vector<android::bluetooth::BluetoothA2dpCodecConfig>& - codec_priorities, - bool* _aidl_return) { - auto codec_priorities_non_binder = A2dpCodecsFromBinder(codec_priorities); - - LockGuard lock(*maps_lock()); - auto a2dp_source = TRY_GET_SOURCE(); - TRY_RET_FUNC(a2dp_source->Enable(codec_priorities_non_binder)); -} - -Status BluetoothA2dpSourceBinderServer::Disable(bool* _aidl_return) { - LockGuard lock(*maps_lock()); - auto a2dp_source = TRY_GET_SOURCE(); - a2dp_source->Disable(); - AIDL_RET(true); -} - -Status BluetoothA2dpSourceBinderServer::Connect(const String16& device_address, - bool* _aidl_return) { - LockGuard lock(*maps_lock()); - auto a2dp_source = TRY_GET_SOURCE(); - TRY_RET_FUNC(a2dp_source->Connect(String8(device_address).string())); -} - -Status BluetoothA2dpSourceBinderServer::Disconnect( - const String16& device_address, bool* _aidl_return) { - LockGuard lock(*maps_lock()); - auto a2dp_source = TRY_GET_SOURCE(); - TRY_RET_FUNC(a2dp_source->Disconnect(String8(device_address).string())); -} - -Status BluetoothA2dpSourceBinderServer::ConfigCodec( - const android::String16& device_address, - const std::vector<android::bluetooth::BluetoothA2dpCodecConfig>& - codec_preferences, - bool* _aidl_return) { - auto codec_preferences_non_binder = A2dpCodecsFromBinder(codec_preferences); - - LockGuard lock(*maps_lock()); - auto a2dp_source = TRY_GET_SOURCE(); - TRY_RET_FUNC(a2dp_source->ConfigCodec(String8(device_address).string(), - codec_preferences_non_binder)); -} - -void BluetoothA2dpSourceBinderServer::OnConnectionState( - const std::string& device_address, int state) { - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnConnectionState(String16(device_address.c_str()), state); -} - -void BluetoothA2dpSourceBinderServer::OnAudioState( - const std::string& device_address, int state) { - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnAudioState(String16(device_address.c_str()), state); -} - -void BluetoothA2dpSourceBinderServer::OnAudioConfig( - const std::string& device_address, bluetooth::A2dpCodecConfig codec_config, - const std::vector<bluetooth::A2dpCodecConfig>& codecs_local_capabilities, - const std::vector<bluetooth::A2dpCodecConfig>& - codecs_selectable_capabilities) { - auto binder_codecs_local_capabilities = - A2dpCodecsToBinder(codecs_local_capabilities); - auto binder_codecs_selectable_capabilities = - A2dpCodecsToBinder(codecs_selectable_capabilities); - - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnAudioConfig(String16(device_address.c_str()), codec_config, - binder_codecs_local_capabilities, - binder_codecs_selectable_capabilities); -} - -android::sp<IBluetoothA2dpSourceCallback> -BluetoothA2dpSourceBinderServer::GetA2dpSourceCallback() { - auto cb = GetCallback(bluetooth::A2dpSource::kSingletonInstanceId); - return android::sp<IBluetoothA2dpSourceCallback>( - static_cast<IBluetoothA2dpSourceCallback*>(cb.get())); -} - -std::shared_ptr<bluetooth::A2dpSource> -BluetoothA2dpSourceBinderServer::GetA2dpSource() { - return std::static_pointer_cast<bluetooth::A2dpSource>( - GetInstance(bluetooth::A2dpSource::kSingletonInstanceId)); -} - -void BluetoothA2dpSourceBinderServer::OnRegisterInstanceImpl( - bluetooth::BLEStatus status, android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) { - VLOG(1) << __func__ << " instance ID: " << instance->GetInstanceId() - << " status: " << status; - bluetooth::A2dpSource* a2dp_source = - static_cast<bluetooth::A2dpSource*>(instance); - a2dp_source->SetDelegate(this); - - android::sp<IBluetoothA2dpSourceCallback> cb( - static_cast<IBluetoothA2dpSourceCallback*>(callback.get())); - cb->OnRegistered(status); -} - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_a2dp_source_binder_server.h b/system/service/ipc/binder/bluetooth_a2dp_source_binder_server.h deleted file mode 100644 index 3800a962ec..0000000000 --- a/system/service/ipc/binder/bluetooth_a2dp_source_binder_server.h +++ /dev/null @@ -1,96 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <map> -#include <string> -#include <vector> - -#include <android/bluetooth/BnBluetoothA2dpSource.h> -#include <android/bluetooth/IBluetoothA2dpSourceCallback.h> - -#include "service/a2dp_source.h" -#include "service/ipc/binder/interface_with_instances_base.h" - -namespace bluetooth { -class Adapter; -} // namespace bluetooth - -namespace ipc { -namespace binder { - -class BluetoothA2dpSourceBinderServer - : public InterfaceWithInstancesBase, - public android::bluetooth::BnBluetoothA2dpSource, - public bluetooth::A2dpSource::Delegate { - public: - explicit BluetoothA2dpSourceBinderServer(bluetooth::Adapter* adapter); - BluetoothA2dpSourceBinderServer(const BluetoothA2dpSourceBinderServer&) = - delete; - BluetoothA2dpSourceBinderServer& operator=( - const BluetoothA2dpSourceBinderServer&) = delete; - - ~BluetoothA2dpSourceBinderServer() override; - - bool HasInstance(); - - // IBluetoothA2dpSource implementation: - android::binder::Status Register( - const android::sp<android::bluetooth::IBluetoothA2dpSourceCallback>& - callback, - bool* _aidl_return) override; - android::binder::Status Unregister() override; - android::binder::Status Enable( - const std::vector<android::bluetooth::BluetoothA2dpCodecConfig>& - codec_priorities, - bool* _aidl_return) override; - android::binder::Status Disable(bool* _aidl_return) override; - android::binder::Status Connect(const android::String16& device_address, - bool* _aidl_return) override; - android::binder::Status Disconnect(const android::String16& device_address, - bool* _aidl_return) override; - android::binder::Status ConfigCodec( - const android::String16& device_address, - const std::vector<android::bluetooth::BluetoothA2dpCodecConfig>& - codec_preferences, - bool* _aidl_return) override; - - private: - // bluetooth::bluetooth::A2dpSource::Delegate implementation: - void OnConnectionState(const std::string& device_address, int state) override; - void OnAudioState(const std::string& device_address, int state) override; - void OnAudioConfig( - const std::string& device_address, - bluetooth::A2dpCodecConfig codec_config, - const std::vector<bluetooth::A2dpCodecConfig>& codecs_local_capabilities, - const std::vector<bluetooth::A2dpCodecConfig>& - codecs_selectable_capabilities) override; - - android::sp<android::bluetooth::IBluetoothA2dpSourceCallback> - GetA2dpSourceCallback(); - std::shared_ptr<bluetooth::A2dpSource> GetA2dpSource(); - - // InterfaceWithInstancesBase override: - void OnRegisterInstanceImpl(bluetooth::BLEStatus status, - android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) override; - - bluetooth::Adapter* const adapter_; // weak -}; - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_avrcp_control_binder_server.cc b/system/service/ipc/binder/bluetooth_avrcp_control_binder_server.cc deleted file mode 100644 index d81685928f..0000000000 --- a/system/service/ipc/binder/bluetooth_avrcp_control_binder_server.cc +++ /dev/null @@ -1,236 +0,0 @@ -// -// Copyright 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include "service/ipc/binder/bluetooth_avrcp_control_binder_server.h" - -#include <string> - -#include "base/logging.h" - -#include "service/adapter.h" - -using android::String16; -using android::String8; -using android::binder::Status; -using android::bluetooth::IBluetoothAvrcpControlCallback; - -namespace ipc { -namespace binder { - -namespace { -const int kInvalidInstanceId = -1; -} // namespace - -BluetoothAvrcpControlBinderServer::BluetoothAvrcpControlBinderServer( - bluetooth::Adapter* adapter) - : adapter_(adapter) { - CHECK(adapter_); -} - -Status BluetoothAvrcpControlBinderServer::Register( - const android::sp<IBluetoothAvrcpControlCallback>& callback, - bool* _aidl_return) { - VLOG(2) << __func__; - - bluetooth::AvrcpControlFactory* gatt_client_factory = - adapter_->GetAvrcpControlFactory(); - - *_aidl_return = RegisterInstanceBase(callback, gatt_client_factory); - return Status::ok(); -} - -Status BluetoothAvrcpControlBinderServer::Unregister(int32_t id) { - VLOG(2) << __func__; - UnregisterInstanceBase(id); - return Status::ok(); -} - -Status BluetoothAvrcpControlBinderServer::UnregisterAll() { - VLOG(2) << __func__; - UnregisterAllBase(); - return Status::ok(); -} - -Status BluetoothAvrcpControlBinderServer::Enable(int32_t id, - bool* _aidl_return) { - std::lock_guard<std::mutex> lock(*maps_lock()); - auto avrcp_control = GetAvrcpControl(id); - if (!avrcp_control) { - LOG(ERROR) << "Failed to get avrcp control instance"; - *_aidl_return = false; - return Status::ok(); - } - - if (!avrcp_control->Enable()) { - LOG(ERROR) << "Failed to enable"; - *_aidl_return = false; - return Status::ok(); - } - - *_aidl_return = true; - return Status::ok(); -} - -Status BluetoothAvrcpControlBinderServer::Disable(int32_t id, - bool* _aidl_return) { - std::lock_guard<std::mutex> lock(*maps_lock()); - auto avrcp_control = GetAvrcpControl(id); - if (!avrcp_control) { - LOG(ERROR) << "Failed to get avrcp control instance"; - *_aidl_return = false; - return Status::ok(); - } - - avrcp_control->Disable(); - *_aidl_return = true; - return Status::ok(); -} - -Status BluetoothAvrcpControlBinderServer::SendPassThroughCommand( - int32_t id, const String16& device_address, int32_t key_code, - bool key_pressed, bool* _aidl_return) { - std::lock_guard<std::mutex> lock(*maps_lock()); - auto avrcp_control = GetAvrcpControl(id); - if (!avrcp_control) { - LOG(ERROR) << "Failed to get avrcp control instance"; - *_aidl_return = false; - return Status::ok(); - } - - if (!avrcp_control->SendPassThroughCommand(String8(device_address).string(), - key_code, key_pressed)) { - LOG(ERROR) << "Failed to send pass through command"; - *_aidl_return = false; - return Status::ok(); - } - - *_aidl_return = true; - return Status::ok(); -} - -android::binder::Status BluetoothAvrcpControlBinderServer::SetAbsVolumeResponse( - int32_t id, const android::String16& device_address, int32_t abs_vol, - int32_t label, bool* _aidl_return) { - std::lock_guard<std::mutex> lock(*maps_lock()); - auto avrcp_control = GetAvrcpControl(id); - if (!avrcp_control) { - LOG(ERROR) << "Failed to get avrcp control instance"; - *_aidl_return = false; - return Status::ok(); - } - - if (!avrcp_control->SetAbsVolumeResponse(String8(device_address).string(), - abs_vol, label)) { - LOG(ERROR) << "Failed to send set absolute volume response"; - *_aidl_return = false; - return Status::ok(); - } - *_aidl_return = true; - return Status::ok(); -} - -android::binder::Status -BluetoothAvrcpControlBinderServer::RegisterForAbsVolumeCallbackResponse( - int32_t id, const android::String16& device_address, int32_t response_type, - int32_t abs_vol, int32_t label, bool* _aidl_return) { - std::lock_guard<std::mutex> lock(*maps_lock()); - auto avrcp_control = GetAvrcpControl(id); - if (!avrcp_control) { - LOG(ERROR) << "Failed to get avrcp control instance"; - *_aidl_return = false; - return Status::ok(); - } - - if (!avrcp_control->RegisterForAbsVolumeCallbackResponse( - String8(device_address).string(), response_type, abs_vol, label)) { - LOG(ERROR) - << "Failed to send register for absolute volume callback response"; - *_aidl_return = false; - return Status::ok(); - } - *_aidl_return = true; - return Status::ok(); -} - -void BluetoothAvrcpControlBinderServer::OnConnectionState( - bool rc_connect, bool bt_connect, const std::string& device_address) { - auto func = [rc_connect, bt_connect, &device_address](IInterface* cb) { - auto avrcp_control_cb = static_cast<IBluetoothAvrcpControlCallback*>(cb); - avrcp_control_cb->OnConnectionState(rc_connect, bt_connect, - String16(device_address.c_str())); - }; - - ForEachCallback(func); -} - -void BluetoothAvrcpControlBinderServer::OnTrackChanged( - const std::string& device_address, const bluetooth::AvrcpMediaAttr& attr) { - auto binder_attr = android::bluetooth::BluetoothAvrcpMediaAttr(attr); - - auto func = [&device_address, &binder_attr](IInterface* cb) { - auto avrcp_control_cb = static_cast<IBluetoothAvrcpControlCallback*>(cb); - avrcp_control_cb->OnTrackChanged(String16(device_address.c_str()), - binder_attr); - }; - - ForEachCallback(func); -} - -void BluetoothAvrcpControlBinderServer::OnSetAbsVolumeRequest( - const std::string& device_address, int32_t abs_vol, int32_t label) { - auto addr_s16 = String16(device_address.c_str(), device_address.size()); - auto func = [&addr_s16, abs_vol, label](IInterface* cb) { - auto avrcp_control_cb = static_cast<IBluetoothAvrcpControlCallback*>(cb); - avrcp_control_cb->OnSetAbsVolumeRequest(addr_s16, abs_vol, label); - }; - - ForEachCallback(func); -} - -void BluetoothAvrcpControlBinderServer::OnRegisterForAbsVolumeCallbackRequest( - const std::string& device_address, int32_t label) { - auto addr_s16 = String16(device_address.c_str(), device_address.size()); - auto func = [&addr_s16, label](IInterface* cb) { - auto avrcp_control_cb = static_cast<IBluetoothAvrcpControlCallback*>(cb); - avrcp_control_cb->OnRegisterForAbsVolumeCallbackRequest(addr_s16, label); - }; - - ForEachCallback(func); -} - -std::shared_ptr<bluetooth::AvrcpControl> -BluetoothAvrcpControlBinderServer::GetAvrcpControl(int id) { - return std::static_pointer_cast<bluetooth::AvrcpControl>(GetInstance(id)); -} - -void BluetoothAvrcpControlBinderServer::OnRegisterInstanceImpl( - bluetooth::BLEStatus status, android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) { - VLOG(1) << __func__ << " client ID: " << instance->GetInstanceId() - << " status: " << status; - - bluetooth::AvrcpControl* avrcp_control = - static_cast<bluetooth::AvrcpControl*>(instance); - avrcp_control->SetDelegate(this); - - android::sp<IBluetoothAvrcpControlCallback> cb( - static_cast<IBluetoothAvrcpControlCallback*>(callback.get())); - cb->OnRegistered(status, (status == bluetooth::BLE_STATUS_SUCCESS) - ? instance->GetInstanceId() - : kInvalidInstanceId); -} - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_avrcp_control_binder_server.h b/system/service/ipc/binder/bluetooth_avrcp_control_binder_server.h deleted file mode 100644 index 00b5921b8e..0000000000 --- a/system/service/ipc/binder/bluetooth_avrcp_control_binder_server.h +++ /dev/null @@ -1,90 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <map> -#include <string> - -#include "android/bluetooth/BnBluetoothAvrcpControl.h" -#include "android/bluetooth/IBluetoothAvrcpControlCallback.h" - -#include "service/avrcp_control.h" -#include "service/ipc/binder/interface_with_instances_base.h" - -namespace bluetooth { -class Adapter; -} // namespace bluetooth - -namespace ipc { -namespace binder { - -class BluetoothAvrcpControlBinderServer - : public InterfaceWithInstancesBase, - public android::bluetooth::BnBluetoothAvrcpControl, - public bluetooth::AvrcpControl::Delegate { - public: - explicit BluetoothAvrcpControlBinderServer(bluetooth::Adapter* adapter); - BluetoothAvrcpControlBinderServer(const BluetoothAvrcpControlBinderServer&) = - delete; - BluetoothAvrcpControlBinderServer& operator=( - const BluetoothAvrcpControlBinderServer&) = delete; - - ~BluetoothAvrcpControlBinderServer() override = default; - - // IBluetoothAvrcpControl implementation: - android::binder::Status Register( - const android::sp<::android::bluetooth::IBluetoothAvrcpControlCallback>& - callback, - bool* _aidl_return) override; - android::binder::Status Unregister(int32_t id) override; - android::binder::Status UnregisterAll() override; - android::binder::Status Enable(int32_t id, bool* _aidl_return) override; - android::binder::Status Disable(int32_t id, bool* _aidl_return) override; - android::binder::Status SendPassThroughCommand( - int32_t id, const android::String16& device_address, int32_t key_code, - bool key_pressed, bool* _aidl_return) override; - android::binder::Status SetAbsVolumeResponse( - int32_t id, const android::String16& device_address, int32_t abs_vol, - int32_t label, bool* _aidl_return) override; - android::binder::Status RegisterForAbsVolumeCallbackResponse( - int32_t id, const android::String16& device_address, - int32_t response_type, int32_t abs_vol, int32_t label, - bool* _aidl_return) override; - - private: - // bluetooth::bluetooth::AvrcpControl::Delegate implementation: - void OnConnectionState(bool rc_connect, bool bt_connect, - const std::string& device_address) override; - void OnTrackChanged(const std::string& device_address, - const bluetooth::AvrcpMediaAttr& attr) override; - void OnSetAbsVolumeRequest(const std::string& device_address, int32_t abs_vol, - int32_t label) override; - void OnRegisterForAbsVolumeCallbackRequest(const std::string& device_address, - int32_t label) override; - - // InterfaceWithInstancesBase override: - void OnRegisterInstanceImpl(bluetooth::BLEStatus status, - android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) override; - - std::shared_ptr<bluetooth::AvrcpControl> GetAvrcpControl(int id); - - bluetooth::Adapter* adapter_; // weak -}; - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_avrcp_target_binder_server.cc b/system/service/ipc/binder/bluetooth_avrcp_target_binder_server.cc deleted file mode 100644 index 1652b10f2b..0000000000 --- a/system/service/ipc/binder/bluetooth_avrcp_target_binder_server.cc +++ /dev/null @@ -1,339 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include "service/ipc/binder/bluetooth_avrcp_target_binder_server.h" - -#include <string> - -#include "base/logging.h" - -#include "service/adapter.h" - -#define AIDL_RET(value) \ - do { \ - *_aidl_return = (value); \ - return Status::ok(); \ - } while (0) - -#define TRY_GET_TARGET() \ - ({ \ - auto target = GetAvrcpTarget(); \ - if (!target) { \ - LOG(ERROR) << __func__ << ": " \ - << "Failed to get AVRCP target interface"; \ - AIDL_RET(false); \ - } \ - target; \ - }) - -#define TRY_GET_CB() \ - ({ \ - auto cb = GetAvrcpTargetCallback(); \ - if (!cb.get()) { \ - LOG(WARNING) << "Callback for AVRCP target was deleted"; \ - return; \ - } \ - cb; \ - }) - -#define TRY_RET(expr, msg) \ - do { \ - if (!(expr)) { \ - LOG(ERROR) << msg; \ - AIDL_RET(false); \ - } \ - AIDL_RET(true); \ - } while (0) - -#define TRY_RET_FUNC(expr) TRY_RET(expr, __func__ << " failed") - -using android::String16; -using android::String8; -using android::binder::Status; -using android::bluetooth::BluetoothAvrcpIntValue; -using android::bluetooth::IBluetoothAvrcpTargetCallback; - -using LockGuard = std::lock_guard<std::mutex>; - -namespace ipc { -namespace binder { - -BluetoothAvrcpTargetBinderServer::BluetoothAvrcpTargetBinderServer( - bluetooth::Adapter* adapter) - : adapter_(adapter) { - CHECK(adapter_); -} - -BluetoothAvrcpTargetBinderServer::~BluetoothAvrcpTargetBinderServer() = default; - -bool BluetoothAvrcpTargetBinderServer::HasInstance() { - return GetAvrcpTarget() != nullptr; -} - -Status BluetoothAvrcpTargetBinderServer::Register( - const android::sp<IBluetoothAvrcpTargetCallback>& callback, - bool* _aidl_return) { - VLOG(2) << __func__; - - bluetooth::AvrcpTargetFactory* gatt_client_factory = - adapter_->GetAvrcpTargetFactory(); - - *_aidl_return = RegisterInstanceBase(callback, gatt_client_factory); - return Status::ok(); -} - -Status BluetoothAvrcpTargetBinderServer::Unregister(int32_t id) { - VLOG(2) << __func__; - UnregisterInstanceBase(id); - return Status::ok(); -} - -Status BluetoothAvrcpTargetBinderServer::UnregisterAll() { - VLOG(2) << __func__; - UnregisterAllBase(); - return Status::ok(); -} - -Status BluetoothAvrcpTargetBinderServer::Enable(bool* _aidl_return) { - auto avrcp_target = TRY_GET_TARGET(); - TRY_RET_FUNC(avrcp_target->Enable()); -} - -Status BluetoothAvrcpTargetBinderServer::Disable(bool* _aidl_return) { - auto avrcp_target = TRY_GET_TARGET(); - avrcp_target->Disable(); - AIDL_RET(true); -} - -Status BluetoothAvrcpTargetBinderServer::GetPlayStatusResponse( - const android::String16& addr, int32_t play_status, int32_t song_len, - int32_t song_pos, bool* _aidl_return) { - auto avrcp_target = TRY_GET_TARGET(); - TRY_RET_FUNC(avrcp_target->GetPlayStatusResponse( - String8(addr).string(), play_status, song_len, song_pos)); -} - -Status BluetoothAvrcpTargetBinderServer::ListPlayerAppAttrResponse( - const android::String16& addr, const std::vector<int32_t>& attrs, - bool* _aidl_return) { - auto avrcp_target = TRY_GET_TARGET(); - TRY_RET_FUNC( - avrcp_target->ListPlayerAppAttrResponse(String8(addr).string(), attrs)); -} - -Status BluetoothAvrcpTargetBinderServer::GetPlayerAppValueResponse( - const android::String16& addr, - const std::vector<::android::bluetooth::BluetoothAvrcpIntValue>& values, - bool* _aidl_return) { - auto avrcp_target = TRY_GET_TARGET(); - std::vector<bluetooth::AvrcpIntValue> non_binder; - non_binder.reserve(values.size()); - for (const auto& val : values) { - non_binder.push_back(val); - } - TRY_RET_FUNC(avrcp_target->GetPlayerAppValueResponse(String8(addr).string(), - non_binder)); -} - -Status BluetoothAvrcpTargetBinderServer::GetPlayerAppAttrTextResponse( - const android::String16& addr, - const std::vector<::android::bluetooth::BluetoothAvrcpStringValue>& attrs, - bool* _aidl_return) { - auto avrcp_target = TRY_GET_TARGET(); - std::vector<bluetooth::AvrcpStringValue> non_binder; - non_binder.reserve(attrs.size()); - for (const auto& val : attrs) { - non_binder.push_back(val); - } - TRY_RET_FUNC(avrcp_target->GetPlayerAppAttrTextResponse( - String8(addr).string(), non_binder)); -} - -Status BluetoothAvrcpTargetBinderServer::GetPlayerAppValueTextResponse( - const android::String16& addr, - const std::vector<::android::bluetooth::BluetoothAvrcpStringValue>& values, - bool* _aidl_return) { - auto avrcp_target = TRY_GET_TARGET(); - std::vector<bluetooth::AvrcpStringValue> non_binder; - non_binder.reserve(values.size()); - for (const auto& val : values) { - non_binder.push_back(val); - } - TRY_RET_FUNC(avrcp_target->GetPlayerAppValueTextResponse( - String8(addr).string(), non_binder)); -} - -Status BluetoothAvrcpTargetBinderServer::GetElementAttrResponse( - const android::String16& addr, - const std::vector<::android::bluetooth::BluetoothAvrcpStringValue>& attrs, - bool* _aidl_return) { - auto avrcp_target = TRY_GET_TARGET(); - std::vector<bluetooth::AvrcpStringValue> non_binder; - non_binder.reserve(attrs.size()); - for (const auto& val : attrs) { - non_binder.push_back(val); - } - TRY_RET_FUNC( - avrcp_target->GetElementAttrResponse(String8(addr).string(), non_binder)); -} - -Status BluetoothAvrcpTargetBinderServer::SetPlayerAppValueResponse( - const android::String16& addr, int32_t rsp_status, bool* _aidl_return) { - auto avrcp_target = TRY_GET_TARGET(); - TRY_RET_FUNC(avrcp_target->SetPlayerAppValueResponse(String8(addr).string(), - rsp_status)); -} - -Status BluetoothAvrcpTargetBinderServer::RegisterNotificationResponse( - int32_t event_id, int32_t type, - const ::android::bluetooth::BluetoothAvrcpRegisterNotificationResponse& - param, - bool* _aidl_return) { - auto avrcp_target = TRY_GET_TARGET(); - TRY_RET_FUNC( - avrcp_target->RegisterNotificationResponse(event_id, type, param)); -} - -Status BluetoothAvrcpTargetBinderServer::SetVolume(int32_t volume, - bool* _aidl_return) { - auto avrcp_target = TRY_GET_TARGET(); - TRY_RET_FUNC(avrcp_target->SetVolume(volume)); -} - -void BluetoothAvrcpTargetBinderServer::OnGetRemoteFeatures( - const std::string& addr, int32_t features) { - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnGetRemoteFeatures(String16(addr.data(), addr.size()), features); -} - -void BluetoothAvrcpTargetBinderServer::OnGetPlayStatus( - const std::string& addr) { - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnGetPlayStatus(String16(addr.data(), addr.size())); -} - -void BluetoothAvrcpTargetBinderServer::OnListPlayerAppAttr( - const std::string& addr) { - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnListPlayerAppAttr(String16(addr.data(), addr.size())); -} - -void BluetoothAvrcpTargetBinderServer::OnListPlayerAppValues( - const std::string& addr, int32_t attr_id) { - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnListPlayerAppValues(String16(addr.data(), addr.size()), attr_id); -} - -void BluetoothAvrcpTargetBinderServer::OnGetPlayerAppValue( - const std::string& addr, const std::vector<int32_t>& attrs) { - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnGetPlayerAppValue(String16(addr.data(), addr.size()), attrs); -} - -void BluetoothAvrcpTargetBinderServer::OnGetPlayerAppAttrsText( - const std::string& addr, const std::vector<int32_t>& attrs) { - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnGetPlayerAppAttrsText(String16(addr.data(), addr.size()), attrs); -} - -void BluetoothAvrcpTargetBinderServer::OnGetPlayerAppValuesText( - const std::string& addr, int32_t attr_id, - const std::vector<int32_t>& values) { - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnGetPlayerAppValuesText(String16(addr.data(), addr.size()), attr_id, - values); -} - -void BluetoothAvrcpTargetBinderServer::OnSetPlayerAppValue( - const std::string& addr, - const std::vector<bluetooth::AvrcpIntValue>& values) { - std::vector<BluetoothAvrcpIntValue> binder_values; - binder_values.reserve(values.size()); - for (const auto& val : values) { - binder_values.push_back(val); - } - - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnSetPlayerAppValue(String16(addr.data(), addr.size()), binder_values); -} - -void BluetoothAvrcpTargetBinderServer::OnGetElementAttrs( - const std::string& addr, const std::vector<int32_t>& attrs) { - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnGetElementAttrs(String16(addr.data(), addr.size()), attrs); -} - -void BluetoothAvrcpTargetBinderServer::OnRegisterNotification( - const std::string& addr, int32_t event_id, uint32_t param) { - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnRegisterNotification(String16(addr.data(), addr.size()), event_id, - param); -} - -void BluetoothAvrcpTargetBinderServer::OnVolumeChange(const std::string& addr, - int32_t volume, - int32_t ctype) { - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnVolumeChange(String16(addr.data(), addr.size()), volume, ctype); -} - -void BluetoothAvrcpTargetBinderServer::OnPassThroughCommand( - const std::string& addr, int32_t id, int32_t key_state) { - LockGuard lock(*maps_lock()); - auto cb = TRY_GET_CB(); - cb->OnPassThroughCommand(String16(addr.data(), addr.size()), id, key_state); -} - -android::sp<IBluetoothAvrcpTargetCallback> -BluetoothAvrcpTargetBinderServer::GetAvrcpTargetCallback() { - auto cb = GetCallback(bluetooth::AvrcpTarget::kSingletonInstanceId); - return android::sp<IBluetoothAvrcpTargetCallback>( - static_cast<IBluetoothAvrcpTargetCallback*>(cb.get())); -} - -std::shared_ptr<bluetooth::AvrcpTarget> -BluetoothAvrcpTargetBinderServer::GetAvrcpTarget() { - return std::static_pointer_cast<bluetooth::AvrcpTarget>( - GetInstance(bluetooth::AvrcpTarget::kSingletonInstanceId)); -} - -void BluetoothAvrcpTargetBinderServer::OnRegisterInstanceImpl( - bluetooth::BLEStatus status, android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) { - VLOG(1) << __func__ << " client ID: " << instance->GetInstanceId() - << " status: " << status; - - bluetooth::AvrcpTarget* avrcp_target = - static_cast<bluetooth::AvrcpTarget*>(instance); - avrcp_target->SetDelegate(this); - - android::sp<IBluetoothAvrcpTargetCallback> cb( - static_cast<IBluetoothAvrcpTargetCallback*>(callback.get())); - cb->OnRegistered(status); -} - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_avrcp_target_binder_server.h b/system/service/ipc/binder/bluetooth_avrcp_target_binder_server.h deleted file mode 100644 index aeab315978..0000000000 --- a/system/service/ipc/binder/bluetooth_avrcp_target_binder_server.h +++ /dev/null @@ -1,132 +0,0 @@ -// -// Copyright (C) 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <map> -#include <string> -#include <vector> - -#include "android/bluetooth/BnBluetoothAvrcpTarget.h" -#include "android/bluetooth/IBluetoothAvrcpTargetCallback.h" - -#include "service/avrcp_target.h" -#include "service/ipc/binder/interface_with_instances_base.h" - -namespace bluetooth { -class Adapter; -} // namespace bluetooth - -namespace ipc { -namespace binder { - -class BluetoothAvrcpTargetBinderServer - : public InterfaceWithInstancesBase, - public android::bluetooth::BnBluetoothAvrcpTarget, - public bluetooth::AvrcpTarget::Delegate { - public: - explicit BluetoothAvrcpTargetBinderServer(bluetooth::Adapter* adapter); - BluetoothAvrcpTargetBinderServer(const BluetoothAvrcpTargetBinderServer&) = - delete; - BluetoothAvrcpTargetBinderServer& operator=( - const BluetoothAvrcpTargetBinderServer&) = delete; - - ~BluetoothAvrcpTargetBinderServer() override; - - bool HasInstance(); - - // IBluetoothAvrcpTarget implementation: - android::binder::Status Register( - const android::sp<android::bluetooth::IBluetoothAvrcpTargetCallback>& - callback, - bool* _aidl_return) override; - android::binder::Status Unregister(int32_t id) override; - android::binder::Status UnregisterAll() override; - android::binder::Status Enable(bool* _aidl_return) override; - android::binder::Status Disable(bool* _aidl_return) override; - android::binder::Status GetPlayStatusResponse(const android::String16& addr, - int32_t play_status, - int32_t song_len, - int32_t song_pos, - bool* _aidl_return) override; - android::binder::Status ListPlayerAppAttrResponse( - const android::String16& addr, const std::vector<int32_t>& attrs, - bool* _aidl_return) override; - android::binder::Status GetPlayerAppValueResponse( - const android::String16& addr, - const std::vector<android::bluetooth::BluetoothAvrcpIntValue>& values, - bool* _aidl_return) override; - android::binder::Status GetPlayerAppAttrTextResponse( - const android::String16& addr, - const std::vector<android::bluetooth::BluetoothAvrcpStringValue>& attrs, - bool* _aidl_return) override; - android::binder::Status GetPlayerAppValueTextResponse( - const android::String16& addr, - const std::vector<android::bluetooth::BluetoothAvrcpStringValue>& values, - bool* _aidl_return) override; - android::binder::Status GetElementAttrResponse( - const android::String16& addr, - const std::vector<android::bluetooth::BluetoothAvrcpStringValue>& attrs, - bool* _aidl_return) override; - android::binder::Status SetPlayerAppValueResponse( - const android::String16& addr, int32_t rsp_status, - bool* _aidl_return) override; - android::binder::Status RegisterNotificationResponse( - int32_t event_id, int32_t type, - const android::bluetooth::BluetoothAvrcpRegisterNotificationResponse& - param, - bool* _aidl_return) override; - android::binder::Status SetVolume(int32_t volume, - bool* _aidl_return) override; - - private: - // bluetooth::bluetooth::AvrcpTarget::Delegate implementation: - void OnGetRemoteFeatures(const std::string& addr, int32_t features) override; - void OnGetPlayStatus(const std::string& addr) override; - void OnListPlayerAppAttr(const std::string& addr) override; - void OnListPlayerAppValues(const std::string& addr, int32_t attr_id) override; - void OnGetPlayerAppValue(const std::string& addr, - const std::vector<int32_t>& attrs) override; - void OnGetPlayerAppAttrsText(const std::string& addr, - const std::vector<int32_t>& attrs) override; - void OnGetPlayerAppValuesText(const std::string& addr, int32_t attr_id, - const std::vector<int32_t>& values) override; - void OnSetPlayerAppValue( - const std::string& addr, - const std::vector<bluetooth::AvrcpIntValue>& values) override; - void OnGetElementAttrs(const std::string& addr, - const std::vector<int32_t>& attrs) override; - void OnRegisterNotification(const std::string& addr, int32_t event_id, - uint32_t param) override; - void OnVolumeChange(const std::string& addr, int32_t volume, - int32_t ctype) override; - void OnPassThroughCommand(const std::string& addr, int32_t id, - int32_t key_state) override; - - // InterfaceWithInstancesBase override: - void OnRegisterInstanceImpl(bluetooth::BLEStatus status, - android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) override; - - android::sp<android::bluetooth::IBluetoothAvrcpTargetCallback> - GetAvrcpTargetCallback(); - std::shared_ptr<bluetooth::AvrcpTarget> GetAvrcpTarget(); - - bluetooth::Adapter* const adapter_; // weak -}; - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_binder_server.cc b/system/service/ipc/binder/bluetooth_binder_server.cc deleted file mode 100644 index 097abb7664..0000000000 --- a/system/service/ipc/binder/bluetooth_binder_server.cc +++ /dev/null @@ -1,489 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/ipc/binder/bluetooth_binder_server.h" - -#include <base/logging.h> - -#include "service/ipc/binder/bluetooth_a2dp_sink_binder_server.h" -#include "service/ipc/binder/bluetooth_a2dp_source_binder_server.h" -#include "service/ipc/binder/bluetooth_avrcp_control_binder_server.h" -#include "service/ipc/binder/bluetooth_avrcp_target_binder_server.h" -#include "service/ipc/binder/bluetooth_gatt_client_binder_server.h" -#include "service/ipc/binder/bluetooth_gatt_server_binder_server.h" -#include "service/ipc/binder/bluetooth_le_advertiser_binder_server.h" -#include "service/ipc/binder/bluetooth_le_scanner_binder_server.h" -#include "service/ipc/binder/bluetooth_low_energy_binder_server.h" - -#include "service/hal/bluetooth_interface.h" - -using android::sp; -using android::String8; -using android::String16; - -using android::bluetooth::IBluetoothCallback; -using android::bluetooth::IBluetoothGattClient; -using android::bluetooth::IBluetoothGattServer; - -namespace ipc { -namespace binder { - -BluetoothBinderServer::BluetoothBinderServer(bluetooth::Adapter* adapter) - : adapter_(adapter) { - CHECK(adapter_); - adapter_->AddObserver(this); -} - -BluetoothBinderServer::~BluetoothBinderServer() { - adapter_->RemoveObserver(this); -} - -// binder::BnBluetooth overrides: -Status BluetoothBinderServer::IsEnabled(bool* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = adapter_->IsEnabled(); - return Status::ok(); -} - -Status BluetoothBinderServer::GetState(int32_t* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = adapter_->GetState(); - return Status::ok(); -} - -Status BluetoothBinderServer::Enable(bool* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = adapter_->Enable(); - return Status::ok(); -} - -Status BluetoothBinderServer::EnableNoAutoConnect(bool* _aidl_return) { - VLOG(2) << __func__; - // TODO(armansito): Implement. - *_aidl_return = false; - return Status::ok(); -} - -Status BluetoothBinderServer::Disable(bool* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = adapter_->Disable(); - return Status::ok(); -} - -Status BluetoothBinderServer::GetAddress(::android::String16* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = String16(String8(adapter_->GetAddress().c_str())); - return Status::ok(); -} - -Status BluetoothBinderServer::GetUUIDs( - ::std::vector<::android::bluetooth::UUID>* _aidl_return) { - VLOG(2) << __func__; - // TODO(armansito): Implement. - *_aidl_return = std::vector<android::bluetooth::UUID>(); - return Status::ok(); -} - -Status BluetoothBinderServer::SetName(const ::android::String16& name, - bool* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = adapter_->SetName(std::string(String8(name).string())); - return Status::ok(); -} - -Status BluetoothBinderServer::GetName(::android::String16* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = String16(String8(adapter_->GetName().c_str())); - return Status::ok(); -} - -Status BluetoothBinderServer::SetScanMode(int32_t scan_mode, - bool* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = adapter_->SetScanMode(scan_mode); - return Status::ok(); -} - -Status BluetoothBinderServer::SetScanEnable(bool scan_enable, - bool* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = adapter_->SetScanEnable(scan_enable); - return Status::ok(); -} - -Status BluetoothBinderServer::SspReply( - const ::android::String16& device_address, int32_t variant, bool accept, - int32_t passkey, bool* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = adapter_->SspReply(String8(device_address).string(), variant, - accept, passkey); - return Status::ok(); -} - -Status BluetoothBinderServer::CreateBond( - const ::android::String16& device_address, int32_t transport, - bool* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = - adapter_->CreateBond(String8(device_address).string(), transport); - return Status::ok(); -} - -Status BluetoothBinderServer::GetBondedDevices(bool* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = adapter_->GetBondedDevices(); - return Status::ok(); -} - -Status BluetoothBinderServer::RemoveBond( - const ::android::String16& device_address, bool* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = adapter_->RemoveBond(String8(device_address).string()); - return Status::ok(); -} - -Status BluetoothBinderServer::GetRemoteDeviceProperties( - const ::android::String16& device_address, bool* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = - adapter_->GetRemoteDeviceProperties(String8(device_address).string()); - return Status::ok(); -} - -Status BluetoothBinderServer::RegisterCallback( - const ::android::sp<IBluetoothCallback>& callback) { - VLOG(2) << __func__; - if (!callback.get()) { - LOG(ERROR) << "RegisterCallback called with NULL binder. Ignoring."; - return Status::ok(); - } - callbacks_.Register(callback); - return Status::ok(); -} - -Status BluetoothBinderServer::UnregisterCallback( - const ::android::sp<IBluetoothCallback>& callback) { - VLOG(2) << __func__; - if (!callback.get()) { - LOG(ERROR) << "UnregisterCallback called with NULL binder. Ignoring."; - return Status::ok(); - } - callbacks_.Unregister(callback); - return Status::ok(); -} - -Status BluetoothBinderServer::IsMultiAdvertisementSupported( - bool* _aidl_return) { - VLOG(2) << __func__; - *_aidl_return = adapter_->IsMultiAdvertisementSupported(); - return Status::ok(); -} - -Status BluetoothBinderServer::GetA2dpSinkInterface( - ::android::sp<IBluetoothA2dpSink>* _aidl_return) { - VLOG(2) << __func__; - - if (!adapter_->IsEnabled()) { - LOG(ERROR) << "Cannot obtain IBluetoothA2dpSink interface while disabled"; - *_aidl_return = nullptr; - return Status::ok(); - } - - if (!a2dp_sink_interface_.get()) - a2dp_sink_interface_ = new BluetoothA2dpSinkBinderServer(adapter_); - - if (a2dp_sink_interface_->HasInstance()) { - LOG(ERROR) << "Only one A2dpSink interface allowed at a time"; - *_aidl_return = nullptr; - return Status::ok(); - } - - *_aidl_return = a2dp_sink_interface_; - return Status::ok(); -} - -Status BluetoothBinderServer::GetA2dpSourceInterface( - ::android::sp<IBluetoothA2dpSource>* _aidl_return) { - VLOG(2) << __func__; - - if (!adapter_->IsEnabled()) { - LOG(ERROR) << "Cannot obtain IBluetoothA2dpSource interface while disabled"; - *_aidl_return = nullptr; - return Status::ok(); - } - - if (!a2dp_source_interface_.get()) - a2dp_source_interface_ = new BluetoothA2dpSourceBinderServer(adapter_); - - if (a2dp_source_interface_->HasInstance()) { - LOG(ERROR) << "Only one A2dpSource interface allowed at a time"; - *_aidl_return = nullptr; - return Status::ok(); - } - - *_aidl_return = a2dp_source_interface_; - return Status::ok(); -} - -Status BluetoothBinderServer::GetLowEnergyInterface( - ::android::sp<IBluetoothLowEnergy>* _aidl_return) { - VLOG(2) << __func__; - - if (!adapter_->IsEnabled()) { - LOG(ERROR) << "Cannot obtain IBluetoothLowEnergy interface while disabled"; - *_aidl_return = NULL; - return Status::ok(); - } - - if (!low_energy_interface_.get()) - low_energy_interface_ = new BluetoothLowEnergyBinderServer(adapter_); - - *_aidl_return = low_energy_interface_; - return Status::ok(); -} - -Status BluetoothBinderServer::GetLeAdvertiserInterface( - ::android::sp<IBluetoothLeAdvertiser>* _aidl_return) { - VLOG(2) << __func__; - - if (!adapter_->IsEnabled()) { - LOG(ERROR) - << "Cannot obtain IBluetoothLeAdvertiser interface while disabled"; - *_aidl_return = NULL; - return Status::ok(); - } - - if (!le_advertiser_interface_.get()) - le_advertiser_interface_ = new BluetoothLeAdvertiserBinderServer(adapter_); - - *_aidl_return = le_advertiser_interface_; - return Status::ok(); -} - -Status BluetoothBinderServer::GetLeScannerInterface( - ::android::sp<IBluetoothLeScanner>* _aidl_return) { - VLOG(2) << __func__; - - if (!adapter_->IsEnabled()) { - LOG(ERROR) << "Cannot obtain IBluetoothLeScanner interface while disabled"; - *_aidl_return = NULL; - return Status::ok(); - } - - if (!le_scanner_interface_.get()) - le_scanner_interface_ = new BluetoothLeScannerBinderServer(adapter_); - - *_aidl_return = le_scanner_interface_; - return Status::ok(); -} - -Status BluetoothBinderServer::GetGattClientInterface( - ::android::sp<IBluetoothGattClient>* _aidl_return) { - VLOG(2) << __func__; - - if (!adapter_->IsEnabled()) { - LOG(ERROR) << "Cannot obtain IBluetoothGattClient interface while disabled"; - *_aidl_return = NULL; - return Status::ok(); - } - - if (!gatt_client_interface_.get()) - gatt_client_interface_ = new BluetoothGattClientBinderServer(adapter_); - - *_aidl_return = gatt_client_interface_; - return Status::ok(); -} - -Status BluetoothBinderServer::GetGattServerInterface( - ::android::sp<IBluetoothGattServer>* _aidl_return) { - VLOG(2) << __func__; - - if (!adapter_->IsEnabled()) { - LOG(ERROR) << "Cannot obtain IBluetoothGattServer interface while disabled"; - *_aidl_return = NULL; - return Status::ok(); - } - - if (!gatt_server_interface_.get()) - gatt_server_interface_ = new BluetoothGattServerBinderServer(adapter_); - - *_aidl_return = gatt_server_interface_; - return Status::ok(); -} - -Status BluetoothBinderServer::GetAvrcpControlInterface( - ::android::sp<IBluetoothAvrcpControl>* _aidl_return) { - VLOG(2) << __func__; - - if (!adapter_->IsEnabled()) { - LOG(ERROR) - << "Cannot obtain IBluetoothAvrcpControl interface while disabled"; - *_aidl_return = NULL; - return Status::ok(); - } - - if (!avrcp_control_interface_.get()) - avrcp_control_interface_ = new BluetoothAvrcpControlBinderServer(adapter_); - - *_aidl_return = avrcp_control_interface_; - return Status::ok(); -} - -Status BluetoothBinderServer::GetAvrcpTargetInterface( - ::android::sp<IBluetoothAvrcpTarget>* _aidl_return) { - VLOG(2) << __func__; - - if (!adapter_->IsEnabled()) { - LOG(ERROR) - << "Cannot obtain IBluetoothAvrcpTarget interface while disabled"; - *_aidl_return = NULL; - return Status::ok(); - } - - if (!avrcp_target_interface_.get()) - avrcp_target_interface_ = new BluetoothAvrcpTargetBinderServer(adapter_); - - if (avrcp_target_interface_->HasInstance()) { - LOG(ERROR) << "Only one AVRCP target interface allowed at a time"; - *_aidl_return = nullptr; - return Status::ok(); - } - - *_aidl_return = avrcp_target_interface_; - return Status::ok(); -} - -android::status_t BluetoothBinderServer::dump( - int fd, const android::Vector<android::String16>& args) { - VLOG(2) << __func__ << " called with fd " << fd; - if (args.size() > 0) { - // TODO (jamuraa): Parse arguments and switch on --proto, --proto_text - for (const auto& x : args) { - VLOG(2) << __func__ << "argument: " << x.string(); - } - } - // TODO (jamuraa): enumerate profiles and dump profile information - const bt_interface_t* iface = - bluetooth::hal::BluetoothInterface::Get()->GetHALInterface(); - iface->dump(fd, NULL); - return android::NO_ERROR; -} - -void BluetoothBinderServer::OnAdapterStateChanged( - bluetooth::Adapter* adapter, bluetooth::AdapterState prev_state, - bluetooth::AdapterState new_state) { - CHECK_EQ(adapter, adapter_); - VLOG(2) << "Received adapter state update - prev: " << prev_state - << " new: " << new_state; - callbacks_.ForEach([prev_state, new_state](IBluetoothCallback* callback) { - callback->OnBluetoothStateChange(prev_state, new_state); - }); -} - -void BluetoothBinderServer::OnDeviceConnectionStateChanged( - bluetooth::Adapter* adapter, const std::string& device_address, - bool connected) { - CHECK_EQ(adapter, adapter_); - auto addr_s16 = String16(device_address.c_str(), device_address.size()); - callbacks_.ForEach([&addr_s16, connected](IBluetoothCallback* callback) { - callback->OnDeviceConnectionStateChanged(addr_s16, connected); - }); -} - -void BluetoothBinderServer::OnScanEnableChanged(bluetooth::Adapter* adapter, - bool scan_enabled) { - CHECK_EQ(adapter, adapter_); - callbacks_.ForEach([scan_enabled](IBluetoothCallback* callback) { - callback->OnScanEnableChanged(scan_enabled); - }); -} - -void BluetoothBinderServer::OnSspRequest(bluetooth::Adapter* adapter, - const std::string& device_address, - const std::string& device_name, - int cod, int pairing_variant, - int pass_key) { - CHECK_EQ(adapter, adapter_); - VLOG(2) << "Received ssp request: device_address: " << device_address - << ", device_name: " << device_name << ", cod: " << cod - << ", pairing_variant: " << pairing_variant - << ", pass_key: " << pass_key; - - android::String16 addr_s16(device_address.c_str()); - android::String16 name_s16(device_name.c_str()); - callbacks_.ForEach([&addr_s16, &name_s16, cod, pairing_variant, - pass_key](IBluetoothCallback* callback) { - callback->OnSspRequest(addr_s16, name_s16, cod, pairing_variant, pass_key); - }); -} - -void BluetoothBinderServer::OnBondStateChanged( - bluetooth::Adapter* adapter, int status, const std::string& device_address, - int state) { - CHECK_EQ(adapter, adapter_); - VLOG(2) << "Received " << __func__ << " " - << "status: " << status << ", device_address: " << device_address - << ", state: " << state; - android::String16 addr_s16(device_address.c_str(), device_address.size()); - callbacks_.ForEach([status, &addr_s16, state](IBluetoothCallback* callback) { - callback->OnBondStateChanged(status, addr_s16, state); - }); -} - -void BluetoothBinderServer::OnGetBondedDevices( - bluetooth::Adapter* adapter, int status, - const std::vector<std::string>& bonded_devices) { - CHECK_EQ(adapter, adapter_); - VLOG(2) << "Received " << __func__; - std::vector<android::String16> devices_s16; - devices_s16.reserve(bonded_devices.size()); - for (const auto& device : bonded_devices) - devices_s16.emplace_back(device.c_str(), device.size()); - - callbacks_.ForEach([status, &devices_s16](IBluetoothCallback* callback) { - callback->OnGetBondedDevices(status, devices_s16); - }); -} - -void BluetoothBinderServer::OnGetRemoteDeviceProperties( - bluetooth::Adapter* adapter, int status, const std::string& device_address, - const bluetooth::RemoteDeviceProps& properties) { - CHECK_EQ(adapter, adapter_); - VLOG(2) << "Received " << __func__ << " " - << "status: " << status << ", device_address: " << device_address; - android::String16 addr_s16(device_address.c_str(), device_address.size()); - auto binder_props = - android::bluetooth::BluetoothRemoteDeviceProps(properties); - callbacks_.ForEach( - [status, &addr_s16, &binder_props](IBluetoothCallback* callback) { - callback->OnGetRemoteDeviceProperties(status, addr_s16, binder_props); - }); -} - -void BluetoothBinderServer::OnDeviceFound( - bluetooth::Adapter* adapter, - const bluetooth::RemoteDeviceProps& properties) { - CHECK_EQ(adapter, adapter_); - VLOG(2) << "Received " << __func__ << " "; - auto binder_props = - android::bluetooth::BluetoothRemoteDeviceProps(properties); - callbacks_.ForEach([&binder_props](IBluetoothCallback* callback) { - callback->OnDeviceFound(binder_props); - }); -} - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_binder_server.h b/system/service/ipc/binder/bluetooth_binder_server.h deleted file mode 100644 index a389d3f6af..0000000000 --- a/system/service/ipc/binder/bluetooth_binder_server.h +++ /dev/null @@ -1,197 +0,0 @@ -// -// Copyright (C) 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <string> -#include <vector> - -#include <utils/String16.h> -#include <utils/Vector.h> - -#include <android/bluetooth/BnBluetooth.h> -#include <android/bluetooth/IBluetoothA2dpSink.h> -#include <android/bluetooth/IBluetoothA2dpSource.h> -#include <android/bluetooth/IBluetoothAvrcpControl.h> -#include <android/bluetooth/IBluetoothAvrcpTarget.h> -#include <android/bluetooth/IBluetoothCallback.h> -#include <android/bluetooth/IBluetoothGattClient.h> -#include <android/bluetooth/IBluetoothGattServer.h> -#include <android/bluetooth/IBluetoothLeAdvertiser.h> -#include <android/bluetooth/IBluetoothLeScanner.h> -#include <android/bluetooth/IBluetoothLowEnergy.h> - -#include "bluetooth/uuid.h" -#include "service/adapter.h" -#include "service/ipc/binder/remote_callback_list.h" - -using android::String16; -using android::binder::Status; - -using android::bluetooth::BnBluetooth; -using android::bluetooth::IBluetoothA2dpSink; -using android::bluetooth::IBluetoothA2dpSource; -using android::bluetooth::IBluetoothAvrcpControl; -using android::bluetooth::IBluetoothAvrcpTarget; -using android::bluetooth::IBluetoothCallback; -using android::bluetooth::IBluetoothGattClient; -using android::bluetooth::IBluetoothGattServer; -using android::bluetooth::IBluetoothLeAdvertiser; -using android::bluetooth::IBluetoothLeScanner; -using android::bluetooth::IBluetoothLowEnergy; - -namespace ipc { -namespace binder { - -class BluetoothA2dpSinkBinderServer; -class BluetoothA2dpSourceBinderServer; -class BluetoothAvrcpTargetBinderServer; - -// Implements the server side of the IBluetooth Binder interface. -class BluetoothBinderServer : public BnBluetooth, - public bluetooth::Adapter::Observer { - public: - explicit BluetoothBinderServer(bluetooth::Adapter* adapter); - - BluetoothBinderServer(const BluetoothBinderServer&) = delete; - BluetoothBinderServer& operator=(const BluetoothBinderServer&) = delete; - - ~BluetoothBinderServer() override; - - // IBluetooth overrides: - Status IsEnabled(bool* _aidl_return) override; - Status GetState(int32_t* _aidl_return) override; - Status Enable(bool* _aidl_return) override; - Status EnableNoAutoConnect(bool* _aidl_return) override; - Status Disable(bool* _aidl_return) override; - - Status GetAddress(::android::String16* _aidl_return) override; - Status GetUUIDs( - ::std::vector<::android::bluetooth::UUID>* _aidl_return) override; - Status SetName(const ::android::String16& name, bool* _aidl_return) override; - Status GetName(::android::String16* _aidl_return) override; - Status SetScanMode(int32_t scan_mode, bool* _aidl_return) override; - Status SetScanEnable(bool scan_enable, bool* _aidl_return) override; - Status SspReply(const ::android::String16& device_address, int32_t variant, - bool accept, int32_t passkey, bool* _aidl_return) override; - Status CreateBond(const ::android::String16& device_address, - int32_t transport, bool* _aidl_return) override; - Status GetBondedDevices(bool* _aidl_return) override; - Status RemoveBond(const ::android::String16& device_address, - bool* _aidl_return) override; - Status GetRemoteDeviceProperties(const ::android::String16& device_address, - bool* _aidl_return) override; - - Status RegisterCallback( - const ::android::sp<IBluetoothCallback>& callback) override; - Status UnregisterCallback( - const ::android::sp<IBluetoothCallback>& callback) override; - Status IsMultiAdvertisementSupported(bool* _aidl_return) override; - Status GetA2dpSinkInterface( - ::android::sp<IBluetoothA2dpSink>* _aidl_return) override; - Status GetA2dpSourceInterface( - ::android::sp<IBluetoothA2dpSource>* _aidl_return) override; - Status GetLowEnergyInterface( - ::android::sp<IBluetoothLowEnergy>* _aidl_return) override; - Status GetLeAdvertiserInterface( - ::android::sp<IBluetoothLeAdvertiser>* _aidl_return) override; - Status GetLeScannerInterface( - ::android::sp<IBluetoothLeScanner>* _aidl_return) override; - Status GetGattClientInterface( - ::android::sp<IBluetoothGattClient>* _aidl_return) override; - Status GetGattServerInterface( - ::android::sp<IBluetoothGattServer>* _aidl_return) override; - Status GetAvrcpControlInterface( - ::android::sp<IBluetoothAvrcpControl>* _aidl_return) override; - Status GetAvrcpTargetInterface( - ::android::sp<IBluetoothAvrcpTarget>* _aidl_return) override; - - android::status_t dump( - int fd, const android::Vector<android::String16>& args) override; - - // bluetooth::Adapter::Observer overrides: - void OnAdapterStateChanged(bluetooth::Adapter* adapter, - bluetooth::AdapterState prev_state, - bluetooth::AdapterState new_state) override; - - void OnDeviceConnectionStateChanged(bluetooth::Adapter* adapter, - const std::string& device_address, - bool connected) override; - - void OnScanEnableChanged(bluetooth::Adapter* adapter, - bool scan_enabled) override; - - void OnSspRequest(bluetooth::Adapter* adapter, - const std::string& device_address, - const std::string& device_name, int cod, - int pairing_variant, int pass_key) override; - - void OnBondStateChanged(bluetooth::Adapter* adapter, int status, - const std::string& device_address, - int state) override; - void OnGetBondedDevices( - bluetooth::Adapter* adapter, int status, - const std::vector<std::string>& bonded_devices) override; - void OnGetRemoteDeviceProperties( - bluetooth::Adapter* adapter, int status, - const std::string& device_address, - const bluetooth::RemoteDeviceProps& properties) override; - void OnDeviceFound(bluetooth::Adapter* adapter, - const bluetooth::RemoteDeviceProps& properties) override; - - private: - bluetooth::Adapter* adapter_; // weak - RemoteCallbackList<IBluetoothCallback> callbacks_; - - // The IBluetoothA2dpSink interface handle. This is lazily initialized on the - // first call to GetA2dpSinkInterface(). - android::sp<BluetoothA2dpSinkBinderServer> a2dp_sink_interface_; - - // The IBluetoothA2dpSource interface handle. This is lazily initialized on - // the first call to GetA2dpSourceInterface(). - android::sp<BluetoothA2dpSourceBinderServer> a2dp_source_interface_; - - // The IBluetoothLowEnergy interface handle. This is lazily initialized on the - // first call to GetLowEnergyInterface(). - android::sp<IBluetoothLowEnergy> low_energy_interface_; - - // The IBluetoothLeAdvertiser interface handle. This is lazily initialized on - // the first call to GetLeAdvertiserInterface(). - android::sp<IBluetoothLeAdvertiser> le_advertiser_interface_; - - // The IBluetoothLeScanner interface handle. This is lazily initialized on the - // first call to GetLeScannerInterface(). - android::sp<IBluetoothLeScanner> le_scanner_interface_; - - // The IBluetoothGattClient interface handle. This is lazily initialized on - // the first call to GetGattClientInterface(). - android::sp<IBluetoothGattClient> gatt_client_interface_; - - // The IBluetoothGattServer interface handle. This is lazily initialized on - // the first call to GetGattServerInterface(). - android::sp<IBluetoothGattServer> gatt_server_interface_; - - // The IBluetoothAvrcpControl interface handle. This is lazily initialized on - // the first call to GetAvrcpControlInterface(). - android::sp<IBluetoothAvrcpControl> avrcp_control_interface_; - - // The IBluetoothAvrcpTarget interface handle. This is lazily initialized on - // the first call to GetAvrcpTargetInterface(). - android::sp<BluetoothAvrcpTargetBinderServer> avrcp_target_interface_; -}; - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_gatt_client_binder_server.cc b/system/service/ipc/binder/bluetooth_gatt_client_binder_server.cc deleted file mode 100644 index f72767f2d1..0000000000 --- a/system/service/ipc/binder/bluetooth_gatt_client_binder_server.cc +++ /dev/null @@ -1,89 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/ipc/binder/bluetooth_gatt_client_binder_server.h" - -#include <base/logging.h> - -#include "service/adapter.h" - -using android::bluetooth::IBluetoothGattClientCallback; - -namespace ipc { -namespace binder { - -namespace { -const int kInvalidInstanceId = -1; -} // namespace - -BluetoothGattClientBinderServer::BluetoothGattClientBinderServer( - bluetooth::Adapter* adapter) - : adapter_(adapter) { - CHECK(adapter_); -} - -Status BluetoothGattClientBinderServer::RegisterClient( - const android::sp<IBluetoothGattClientCallback>& callback, - bool* _aidl_return) { - VLOG(2) << __func__; - - bluetooth::GattClientFactory* gatt_client_factory = - adapter_->GetGattClientFactory(); - - *_aidl_return = RegisterInstanceBase(callback, gatt_client_factory); - return Status::ok(); -} - -Status BluetoothGattClientBinderServer::UnregisterClient(int client_id) { - VLOG(2) << __func__; - UnregisterInstanceBase(client_id); - return Status::ok(); -} - -Status BluetoothGattClientBinderServer::UnregisterAll() { - VLOG(2) << __func__; - UnregisterAllBase(); - return Status::ok(); -} - -android::sp<IBluetoothGattClientCallback> -BluetoothGattClientBinderServer::GetGattClientCallback(int client_id) { - auto cb = GetCallback(client_id); - return android::sp<IBluetoothGattClientCallback>( - static_cast<IBluetoothGattClientCallback*>(cb.get())); -} - -std::shared_ptr<bluetooth::GattClient> -BluetoothGattClientBinderServer::GetGattClient(int client_id) { - return std::static_pointer_cast<bluetooth::GattClient>( - GetInstance(client_id)); -} - -void BluetoothGattClientBinderServer::OnRegisterInstanceImpl( - bluetooth::BLEStatus status, android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) { - VLOG(1) << __func__ << " client ID: " << instance->GetInstanceId() - << " status: " << status; - - android::sp<IBluetoothGattClientCallback> cb( - static_cast<IBluetoothGattClientCallback*>(callback.get())); - cb->OnClientRegistered(status, (status == bluetooth::BLE_STATUS_SUCCESS) - ? instance->GetInstanceId() - : kInvalidInstanceId); -} - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_gatt_client_binder_server.h b/system/service/ipc/binder/bluetooth_gatt_client_binder_server.h deleted file mode 100644 index 28fa325545..0000000000 --- a/system/service/ipc/binder/bluetooth_gatt_client_binder_server.h +++ /dev/null @@ -1,77 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <android/bluetooth/BnBluetoothGattClient.h> -#include <android/bluetooth/IBluetoothGattClientCallback.h> - -#include "service/gatt_client.h" -#include "service/ipc/binder/interface_with_instances_base.h" - -using android::bluetooth::BnBluetoothGattClient; -using android::bluetooth::IBluetoothGattClientCallback; - -using ::android::binder::Status; - -namespace bluetooth { -class Adapter; -} // namespace bluetooth - -namespace ipc { -namespace binder { - -// Implements the server side of the IBluetoothGattClient interface. -class BluetoothGattClientBinderServer : public BnBluetoothGattClient, - public InterfaceWithInstancesBase { - public: - explicit BluetoothGattClientBinderServer(bluetooth::Adapter* adapter); - - BluetoothGattClientBinderServer(const BluetoothGattClientBinderServer&) = - delete; - BluetoothGattClientBinderServer& operator=( - const BluetoothGattClientBinderServer&) = delete; - - ~BluetoothGattClientBinderServer() override = default; - - // IBluetoothGattClient overrides: - Status RegisterClient( - const android::sp<IBluetoothGattClientCallback>& callback, - bool* _aidl_return) override; - Status UnregisterClient(int client_id) override; - Status UnregisterAll() override; - - private: - // Returns a pointer to the IBluetoothGattClientCallback instance - // associated with |client_id|. Returns NULL if such a callback cannot be - // found. - android::sp<IBluetoothGattClientCallback> GetGattClientCallback( - int client_id); - - // Returns a pointer to the GattClient instance associated with |client_id|. - // Returns NULL if such a client cannot be found. - std::shared_ptr<bluetooth::GattClient> GetGattClient(int client_id); - - // InterfaceWithInstancesBase override: - void OnRegisterInstanceImpl(bluetooth::BLEStatus status, - android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) override; - - bluetooth::Adapter* adapter_; // weak -}; - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_gatt_server_binder_server.cc b/system/service/ipc/binder/bluetooth_gatt_server_binder_server.cc deleted file mode 100644 index 8dffef74ec..0000000000 --- a/system/service/ipc/binder/bluetooth_gatt_server_binder_server.cc +++ /dev/null @@ -1,309 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/ipc/binder/bluetooth_gatt_server_binder_server.h" - -#include <base/logging.h> - -#include "service/adapter.h" - -using ::android::String8; -using ::android::String16; -using ::android::binder::Status; - -using ::android::bluetooth::IBluetoothGattServerCallback; - -namespace ipc { -namespace binder { - -namespace { -const int kInvalidInstanceId = -1; -} // namespace - -BluetoothGattServerBinderServer::BluetoothGattServerBinderServer( - bluetooth::Adapter* adapter) - : adapter_(adapter) { - CHECK(adapter_); -} - -Status BluetoothGattServerBinderServer::RegisterServer( - const ::android::sp<IBluetoothGattServerCallback>& callback, - bool* _aidl_return) { - VLOG(2) << __func__; - bluetooth::GattServerFactory* gatt_server_factory = - adapter_->GetGattServerFactory(); - - *_aidl_return = RegisterInstanceBase(callback, gatt_server_factory); - return Status::ok(); -} - -Status BluetoothGattServerBinderServer::UnregisterServer(int server_id) { - VLOG(2) << __func__; - UnregisterInstanceBase(server_id); - return Status::ok(); -} - -Status BluetoothGattServerBinderServer::UnregisterAll() { - VLOG(2) << __func__; - UnregisterAllBase(); - return Status::ok(); -} - -Status BluetoothGattServerBinderServer::AddService( - int server_id, const android::bluetooth::BluetoothGattService& service, - bool* _aidl_return) { - VLOG(2) << __func__; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto gatt_server = GetGattServer(server_id); - if (!gatt_server) { - LOG(ERROR) << "Unknown server_id: " << server_id; - *_aidl_return = false; - return Status::ok(); - } - - // Create a weak pointer and pass that to the callback to prevent a potential - // use after free. - android::wp<BluetoothGattServerBinderServer> weak_ptr_to_this(this); - auto callback = [=](bluetooth::BLEStatus status, - const bluetooth::Service& service) { - auto sp_to_this = weak_ptr_to_this.promote(); - if (!sp_to_this.get()) { - VLOG(2) << "BluetoothLowEnergyBinderServer was deleted"; - return; - } - - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto gatt_cb = GetGattServerCallback(server_id); - if (!gatt_cb.get()) { - VLOG(2) << "The callback was deleted"; - return; - } - - gatt_cb->OnServiceAdded(status, service); - }; - - if (!gatt_server->AddService(service, callback)) { - LOG(ERROR) << "Failed to add service"; - *_aidl_return = false; - return Status::ok(); - } - - *_aidl_return = true; - return Status::ok(); -} - -Status BluetoothGattServerBinderServer::SendResponse( - int server_id, const String16& device_address, int request_id, int status, - int offset, const std::vector<uint8_t>& value, bool* _aidl_return) { - VLOG(2) << __func__; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto gatt_server = GetGattServer(server_id); - if (!gatt_server) { - LOG(ERROR) << "Unknown server_id: " << server_id; - *_aidl_return = false; - return Status::ok(); - } - - *_aidl_return = gatt_server->SendResponse( - std::string(String8(device_address).string()), request_id, - static_cast<bluetooth::GATTError>(status), offset, value); - - return Status::ok(); -} - -Status BluetoothGattServerBinderServer::SendNotification( - int server_id, const String16& device_address, int handle, bool confirm, - const std::vector<uint8_t>& value, bool* _aidl_return) { - VLOG(2) << __func__; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto gatt_server = GetGattServer(server_id); - if (!gatt_server) { - LOG(ERROR) << "Unknown server_id: " << server_id; - *_aidl_return = false; - return Status::ok(); - } - - // Create a weak pointer and pass that to the callback to prevent a potential - // use after free. - android::wp<BluetoothGattServerBinderServer> weak_ptr_to_this(this); - auto callback = [=](bluetooth::GATTError error) { - auto sp_to_this = weak_ptr_to_this.promote(); - if (!sp_to_this.get()) { - VLOG(2) << "BluetoothLowEnergyBinderServer was deleted"; - return; - } - - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto gatt_cb = GetGattServerCallback(server_id); - if (!gatt_cb.get()) { - VLOG(2) << "The callback was deleted"; - return; - } - - gatt_cb->OnNotificationSent(device_address, error); - }; - - if (!gatt_server->SendNotification( - std::string(String8(device_address).string()), handle, confirm, value, - callback)) { - LOG(ERROR) << "Failed to send notification"; - *_aidl_return = false; - return Status::ok(); - } - - *_aidl_return = true; - return Status::ok(); -} - -void BluetoothGattServerBinderServer::OnCharacteristicReadRequest( - bluetooth::GattServer* gatt_server, const std::string& device_address, - int request_id, int offset, bool is_long, uint16_t handle) { - VLOG(2) << __func__; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto gatt_cb = GetGattServerCallback(gatt_server->GetInstanceId()); - if (!gatt_cb.get()) { - LOG(WARNING) << "Callback for this GattServer was deleted."; - return; - } - - gatt_cb->OnCharacteristicReadRequest( - String16(device_address.c_str(), device_address.length()), request_id, - offset, is_long, handle); -} - -void BluetoothGattServerBinderServer::OnDescriptorReadRequest( - bluetooth::GattServer* gatt_server, const std::string& device_address, - int request_id, int offset, bool is_long, uint16_t handle) { - VLOG(2) << __func__; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto gatt_cb = GetGattServerCallback(gatt_server->GetInstanceId()); - if (!gatt_cb.get()) { - LOG(WARNING) << "Callback for this GattServer was deleted."; - return; - } - - gatt_cb->OnDescriptorReadRequest( - String16(device_address.c_str(), device_address.length()), request_id, - offset, is_long, handle); -} - -android::sp<IBluetoothGattServerCallback> -BluetoothGattServerBinderServer::GetGattServerCallback(int server_id) { - auto cb = GetCallback(server_id); - return android::sp<IBluetoothGattServerCallback>( - static_cast<IBluetoothGattServerCallback*>(cb.get())); -} - -std::shared_ptr<bluetooth::GattServer> -BluetoothGattServerBinderServer::GetGattServer(int server_id) { - return std::static_pointer_cast<bluetooth::GattServer>( - GetInstance(server_id)); -} - -void BluetoothGattServerBinderServer::OnRegisterInstanceImpl( - bluetooth::BLEStatus status, android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) { - VLOG(1) << __func__ << " instance ID: " << instance->GetInstanceId() - << " status: " << status; - bluetooth::GattServer* gatt_server = - static_cast<bluetooth::GattServer*>(instance); - gatt_server->SetDelegate(this); - - android::sp<IBluetoothGattServerCallback> cb( - static_cast<IBluetoothGattServerCallback*>(callback.get())); - cb->OnServerRegistered(status, (status == bluetooth::BLE_STATUS_SUCCESS) - ? instance->GetInstanceId() - : kInvalidInstanceId); -} - -void BluetoothGattServerBinderServer::OnCharacteristicWriteRequest( - bluetooth::GattServer* gatt_server, const std::string& device_address, - int request_id, int offset, bool is_prepare_write, bool need_response, - const std::vector<uint8_t>& value, uint16_t handle) { - VLOG(2) << __func__; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto gatt_cb = GetGattServerCallback(gatt_server->GetInstanceId()); - if (!gatt_cb.get()) { - LOG(WARNING) << "Callback for this GattServer was deleted."; - return; - } - - gatt_cb->OnCharacteristicWriteRequest( - String16(device_address.c_str(), device_address.length()), request_id, - offset, is_prepare_write, need_response, value, handle); -} - -void BluetoothGattServerBinderServer::OnDescriptorWriteRequest( - bluetooth::GattServer* gatt_server, const std::string& device_address, - int request_id, int offset, bool is_prepare_write, bool need_response, - const std::vector<uint8_t>& value, uint16_t handle) { - VLOG(2) << __func__; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto gatt_cb = GetGattServerCallback(gatt_server->GetInstanceId()); - if (!gatt_cb.get()) { - LOG(WARNING) << "Callback for this GattServer was deleted."; - return; - } - - gatt_cb->OnDescriptorWriteRequest( - String16(device_address.c_str(), device_address.length()), request_id, - offset, is_prepare_write, need_response, value, handle); -} - -void BluetoothGattServerBinderServer::OnExecuteWriteRequest( - bluetooth::GattServer* gatt_server, const std::string& device_address, - int request_id, bool is_execute) { - VLOG(2) << __func__; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto gatt_cb = GetGattServerCallback(gatt_server->GetInstanceId()); - if (!gatt_cb.get()) { - LOG(WARNING) << "Callback for this GattServer was deleted."; - return; - } - - gatt_cb->OnExecuteWriteRequest( - String16(device_address.c_str(), device_address.length()), request_id, - is_execute); -} - -void BluetoothGattServerBinderServer::OnConnectionStateChanged( - bluetooth::GattServer* gatt_server, const std::string& device_address, - bool connected) { - VLOG(2) << __func__; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto gatt_cb = GetGattServerCallback(gatt_server->GetInstanceId()); - if (!gatt_cb.get()) { - LOG(WARNING) << "Callback for this GattServer was deleted."; - return; - } - - gatt_cb->OnConnectionStateChanged( - String16(device_address.c_str(), device_address.length()), connected); -} - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_gatt_server_binder_server.h b/system/service/ipc/binder/bluetooth_gatt_server_binder_server.h deleted file mode 100644 index 34fb7c5843..0000000000 --- a/system/service/ipc/binder/bluetooth_gatt_server_binder_server.h +++ /dev/null @@ -1,119 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <android/bluetooth/BnBluetoothGattServer.h> -#include <android/bluetooth/IBluetoothGattServerCallback.h> - -#include "service/gatt_server.h" -#include "service/ipc/binder/interface_with_instances_base.h" - -using android::bluetooth::BnBluetoothGattServer; -using android::bluetooth::IBluetoothGattServerCallback; - -using ::android::binder::Status; - -namespace bluetooth { -class Adapter; -} // namespace bluetooth - -namespace ipc { -namespace binder { - -// Implements the server side of the IBluetoothGattServer interface. -class BluetoothGattServerBinderServer : public BnBluetoothGattServer, - public InterfaceWithInstancesBase, - public bluetooth::GattServer::Delegate { - public: - explicit BluetoothGattServerBinderServer(bluetooth::Adapter* adapter); - - BluetoothGattServerBinderServer(const BluetoothGattServerBinderServer&) = - delete; - BluetoothGattServerBinderServer& operator=( - const BluetoothGattServerBinderServer&) = delete; - - ~BluetoothGattServerBinderServer() override = default; - - // IBluetoothGattServer overrides: - Status RegisterServer( - const ::android::sp<::android::bluetooth::IBluetoothGattServerCallback>& - callback, - bool* _aidl_return) override; - Status UnregisterServer(int32_t server_id) override; - Status UnregisterAll() override; - Status AddService(int32_t server_id, - const ::android::bluetooth::BluetoothGattService& service, - bool* _aidl_return) override; - Status SendResponse(int32_t server_id, - const ::android::String16& device_address, - int32_t request_id, int32_t status, int32_t offset, - const ::std::vector<uint8_t>& value, - bool* _aidl_return) override; - Status SendNotification(int32_t server_id, - const ::android::String16& device_address, int handle, - bool confirm, const ::std::vector<uint8_t>& value, - bool* _aidl_return) override; - - // bluetooth::GattServer::Delegate overrides: - void OnCharacteristicReadRequest(bluetooth::GattServer* gatt_server, - const std::string& device_address, - int request_id, int offset, bool is_long, - uint16_t handle) override; - void OnDescriptorReadRequest(bluetooth::GattServer* gatt_server, - const std::string& device_address, - int request_id, int offset, bool is_long, - uint16_t handle) override; - void OnCharacteristicWriteRequest(bluetooth::GattServer* gatt_server, - const std::string& device_address, - int request_id, int offset, - bool is_prepare_write, bool need_response, - const std::vector<uint8_t>& value, - uint16_t handle) override; - void OnDescriptorWriteRequest(bluetooth::GattServer* gatt_server, - const std::string& device_address, - int request_id, int offset, - bool is_prepare_write, bool need_response, - const std::vector<uint8_t>& value, - uint16_t handle) override; - void OnExecuteWriteRequest(bluetooth::GattServer* gatt_server, - const std::string& device_address, int request_id, - bool is_execute) override; - void OnConnectionStateChanged(bluetooth::GattServer* gatt_server, - const std::string& device_addres, - bool connected) override; - - private: - // Returns a pointer to the IBluetoothGattServerCallback instance - // associated with |server_id|. Returns NULL if such a callback cannot be - // found. - android::sp<IBluetoothGattServerCallback> GetGattServerCallback( - int server_id); - - // Returns a pointer to the GattServer instance associated with |server_id|. - // Returns NULL if such an instance cannot be found. - std::shared_ptr<bluetooth::GattServer> GetGattServer(int server_id); - - // InterfaceWithInstancesBase override: - void OnRegisterInstanceImpl(bluetooth::BLEStatus status, - android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) override; - - bluetooth::Adapter* adapter_; // weak -}; - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_le_advertiser_binder_server.cc b/system/service/ipc/binder/bluetooth_le_advertiser_binder_server.cc deleted file mode 100644 index 91f70d49d8..0000000000 --- a/system/service/ipc/binder/bluetooth_le_advertiser_binder_server.cc +++ /dev/null @@ -1,184 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/ipc/binder/bluetooth_le_advertiser_binder_server.h" - -#include <base/logging.h> - -#include "service/adapter.h" - -using android::String8; -using android::String16; -using android::binder::Status; - -namespace ipc { -namespace binder { - -namespace { -const int kInvalidInstanceId = -1; -} // namespace - -BluetoothLeAdvertiserBinderServer::BluetoothLeAdvertiserBinderServer( - bluetooth::Adapter* adapter) - : adapter_(adapter) { - CHECK(adapter_); -} - -BluetoothLeAdvertiserBinderServer::~BluetoothLeAdvertiserBinderServer() {} - -Status BluetoothLeAdvertiserBinderServer::RegisterAdvertiser( - const android::sp<IBluetoothLeAdvertiserCallback>& callback, - bool* _aidl_return) { - VLOG(2) << __func__; - bluetooth::LowEnergyAdvertiserFactory* adv_factory = - adapter_->GetLeAdvertiserFactory(); - - *_aidl_return = RegisterInstanceBase(callback, adv_factory); - return Status::ok(); -} - -Status BluetoothLeAdvertiserBinderServer::UnregisterAdvertiser( - int advertiser_id) { - VLOG(2) << __func__; - UnregisterInstanceBase(advertiser_id); - return Status::ok(); -} - -Status BluetoothLeAdvertiserBinderServer::UnregisterAll() { - VLOG(2) << __func__; - UnregisterAllBase(); - return Status::ok(); -} - -Status BluetoothLeAdvertiserBinderServer::StartMultiAdvertising( - int advertiser_id, const android::bluetooth::AdvertiseData& advertise_data, - const android::bluetooth::AdvertiseData& scan_response, - const android::bluetooth::AdvertiseSettings& settings, bool* _aidl_return) { - VLOG(2) << __func__ << " advertiser_id: " << advertiser_id; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto advertiser = GetLEAdvertiser(advertiser_id); - if (!advertiser) { - LOG(ERROR) << "Unknown advertiser_id: " << advertiser_id; - *_aidl_return = false; - return Status::ok(); - } - - // Create a weak pointer and pass that to the callback to prevent a potential - // use after free. - android::wp<BluetoothLeAdvertiserBinderServer> weak_ptr_to_this(this); - auto settings_copy = settings; - auto callback = [=](bluetooth::BLEStatus status) { - auto sp_to_this = weak_ptr_to_this.promote(); - if (!sp_to_this.get()) { - VLOG(2) << "BluetoothLeAdvertiserBinderServer was deleted"; - return; - } - - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto cb = GetLECallback(advertiser_id); - if (!cb.get()) { - VLOG(1) << "Advertiser was removed before callback: " << advertiser_id; - return; - } - - cb->OnMultiAdvertiseCallback(status, true /* is_start */, settings_copy); - }; - - if (!advertiser->StartAdvertising(settings, advertise_data, scan_response, - callback)) { - LOG(ERROR) << "Failed to initiate call to start advertising"; - *_aidl_return = false; - return Status::ok(); - } - - *_aidl_return = true; - return Status::ok(); -} - -Status BluetoothLeAdvertiserBinderServer::StopMultiAdvertising( - int advertiser_id, bool* _aidl_return) { - VLOG(2) << __func__; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto advertiser = GetLEAdvertiser(advertiser_id); - if (!advertiser) { - LOG(ERROR) << "Unknown advertiser_id: " << advertiser_id; - *_aidl_return = false; - return Status::ok(); - } - - // Create a weak pointer and pass that to the callback to prevent a potential - // use after free. - android::wp<BluetoothLeAdvertiserBinderServer> weak_ptr_to_this(this); - auto settings_copy = advertiser->advertise_settings(); - auto callback = [=](bluetooth::BLEStatus status) { - auto sp_to_this = weak_ptr_to_this.promote(); - if (!sp_to_this.get()) { - VLOG(2) << "BluetoothLeAdvertiserBinderServer was deleted"; - return; - } - - auto cb = GetLECallback(advertiser_id); - if (!cb.get()) { - VLOG(2) << "Advertiser was unregistered - advertiser_id: " - << advertiser_id; - return; - } - - std::lock_guard<std::mutex> lock(*maps_lock()); - - cb->OnMultiAdvertiseCallback(status, false /* is_start */, settings_copy); - }; - - if (!advertiser->StopAdvertising(callback)) { - LOG(ERROR) << "Failed to initiate call to start advertising"; - *_aidl_return = false; - return Status::ok(); - } - - *_aidl_return = true; - return Status::ok(); -} - -android::sp<IBluetoothLeAdvertiserCallback> -BluetoothLeAdvertiserBinderServer::GetLECallback(int advertiser_id) { - auto cb = GetCallback(advertiser_id); - return android::sp<IBluetoothLeAdvertiserCallback>( - static_cast<IBluetoothLeAdvertiserCallback*>(cb.get())); -} - -std::shared_ptr<bluetooth::LowEnergyAdvertiser> -BluetoothLeAdvertiserBinderServer::GetLEAdvertiser(int advertiser_id) { - return std::static_pointer_cast<bluetooth::LowEnergyAdvertiser>( - GetInstance(advertiser_id)); -} - -void BluetoothLeAdvertiserBinderServer::OnRegisterInstanceImpl( - bluetooth::BLEStatus status, android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) { - VLOG(1) << __func__ << " status: " << status; - - android::sp<IBluetoothLeAdvertiserCallback> cb( - static_cast<IBluetoothLeAdvertiserCallback*>(callback.get())); - cb->OnAdvertiserRegistered(status, (status == bluetooth::BLE_STATUS_SUCCESS) - ? instance->GetInstanceId() - : kInvalidInstanceId); -} - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_le_advertiser_binder_server.h b/system/service/ipc/binder/bluetooth_le_advertiser_binder_server.h deleted file mode 100644 index a8fca24d42..0000000000 --- a/system/service/ipc/binder/bluetooth_le_advertiser_binder_server.h +++ /dev/null @@ -1,87 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <memory> - -#include <android/bluetooth/IBluetoothLeAdvertiserCallback.h> -#include "android/bluetooth/BnBluetoothLeAdvertiser.h" - -#include "service/common/bluetooth/low_energy_constants.h" -#include "service/ipc/binder/interface_with_instances_base.h" -#include "service/low_energy_advertiser.h" - -using android::binder::Status; -using android::String16; - -using android::bluetooth::BnBluetoothLeAdvertiser; -using android::bluetooth::IBluetoothLeAdvertiserCallback; - -namespace bluetooth { -class Adapter; -} // namespace bluetooth - -namespace ipc { -namespace binder { - -// Implements the server side of the IBluetoothLowEnergy interface. -class BluetoothLeAdvertiserBinderServer : public BnBluetoothLeAdvertiser, - public InterfaceWithInstancesBase { - public: - explicit BluetoothLeAdvertiserBinderServer(bluetooth::Adapter* adapter); - - BluetoothLeAdvertiserBinderServer(const BluetoothLeAdvertiserBinderServer&) = - delete; - BluetoothLeAdvertiserBinderServer& operator=( - const BluetoothLeAdvertiserBinderServer&) = delete; - - ~BluetoothLeAdvertiserBinderServer() override; - - // IBluetoothLowEnergy overrides: - Status RegisterAdvertiser( - const android::sp<IBluetoothLeAdvertiserCallback>& callback, - bool* _aidl_return) override; - Status UnregisterAdvertiser(int advertiser_id) override; - Status UnregisterAll() override; - Status StartMultiAdvertising( - int advertiser_id, - const android::bluetooth::AdvertiseData& advertise_data, - const android::bluetooth::AdvertiseData& scan_response, - const android::bluetooth::AdvertiseSettings& settings, - bool* _aidl_return) override; - Status StopMultiAdvertising(int advertiser_id, bool* _aidl_return) override; - - private: - // Returns a pointer to the IBluetoothLeAdvertiserCallback instance associated - // with |advertiser_id|. Returns NULL if such a callback cannot be found. - android::sp<IBluetoothLeAdvertiserCallback> GetLECallback(int advertiser_id); - - // Returns a pointer to the LowEnergyAdvertiser instance associated with - // |advertiser_id|. Returns NULL if such a advertiser cannot be found. - std::shared_ptr<bluetooth::LowEnergyAdvertiser> GetLEAdvertiser( - int advertiser_id); - - // InterfaceWithInstancesBase override: - void OnRegisterInstanceImpl(bluetooth::BLEStatus status, - android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) override; - - bluetooth::Adapter* adapter_; // weak -}; - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_le_scanner_binder_server.cc b/system/service/ipc/binder/bluetooth_le_scanner_binder_server.cc deleted file mode 100644 index b6072be1dc..0000000000 --- a/system/service/ipc/binder/bluetooth_le_scanner_binder_server.cc +++ /dev/null @@ -1,148 +0,0 @@ -// -// Copyright 2016 The Android Open Source Project -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/ipc/binder/bluetooth_le_scanner_binder_server.h" - -#include <base/logging.h> - -#include "service/adapter.h" - -using android::String8; -using android::String16; -using android::binder::Status; - -namespace ipc { -namespace binder { - -namespace { -const int kInvalidInstanceId = -1; -} // namespace - -BluetoothLeScannerBinderServer::BluetoothLeScannerBinderServer( - bluetooth::Adapter* adapter) - : adapter_(adapter) { - CHECK(adapter_); -} - -BluetoothLeScannerBinderServer::~BluetoothLeScannerBinderServer() {} - -Status BluetoothLeScannerBinderServer::RegisterScanner( - const android::sp<IBluetoothLeScannerCallback>& callback, - bool* _aidl_return) { - VLOG(2) << __func__; - bluetooth::LowEnergyScannerFactory* ble_factory = - adapter_->GetLeScannerFactory(); - - *_aidl_return = RegisterInstanceBase(callback, ble_factory); - return Status::ok(); -} - -Status BluetoothLeScannerBinderServer::UnregisterScanner(int scanner_id) { - VLOG(2) << __func__; - UnregisterInstanceBase(scanner_id); - return Status::ok(); -} - -Status BluetoothLeScannerBinderServer::UnregisterAll() { - VLOG(2) << __func__; - UnregisterAllBase(); - return Status::ok(); -} - -Status BluetoothLeScannerBinderServer::StartScan( - int scanner_id, const android::bluetooth::ScanSettings& settings, - const std::vector<android::bluetooth::ScanFilter>& filters, - bool* _aidl_return) { - VLOG(2) << __func__ << " scanner_id: " << scanner_id; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto scanner = GetLEScanner(scanner_id); - if (!scanner) { - LOG(ERROR) << "Unknown scanner_id: " << scanner_id; - *_aidl_return = false; - return Status::ok(); - } - - std::vector<bluetooth::ScanFilter> flt; - for (const auto& filter : filters) { - flt.push_back(filter); - } - - *_aidl_return = scanner->StartScan(settings, flt); - return Status::ok(); -} - -Status BluetoothLeScannerBinderServer::StopScan(int scanner_id, - bool* _aidl_return) { - VLOG(2) << __func__ << " scanner_id: " << scanner_id; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto scanner = GetLEScanner(scanner_id); - if (!scanner) { - LOG(ERROR) << "Unknown scanner_id: " << scanner_id; - *_aidl_return = false; - return Status::ok(); - } - - *_aidl_return = scanner->StopScan(); - return Status::ok(); -} - -void BluetoothLeScannerBinderServer::OnScanResult( - bluetooth::LowEnergyScanner* scanner, const bluetooth::ScanResult& result) { - VLOG(2) << __func__; - std::lock_guard<std::mutex> lock(*maps_lock()); - - int scanner_id = scanner->GetInstanceId(); - auto cb = GetLECallback(scanner->GetInstanceId()); - if (!cb.get()) { - VLOG(2) << "Scanner was unregistered - scanner_id: " << scanner_id; - return; - } - - cb->OnScanResult(result); -} - -android::sp<IBluetoothLeScannerCallback> -BluetoothLeScannerBinderServer::GetLECallback(int scanner_id) { - auto cb = GetCallback(scanner_id); - return android::sp<IBluetoothLeScannerCallback>( - static_cast<IBluetoothLeScannerCallback*>(cb.get())); -} - -std::shared_ptr<bluetooth::LowEnergyScanner> -BluetoothLeScannerBinderServer::GetLEScanner(int scanner_id) { - return std::static_pointer_cast<bluetooth::LowEnergyScanner>( - GetInstance(scanner_id)); -} - -void BluetoothLeScannerBinderServer::OnRegisterInstanceImpl( - bluetooth::BLEStatus status, android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) { - VLOG(1) << __func__ << " status: " << status; - bluetooth::LowEnergyScanner* le_scanner = - static_cast<bluetooth::LowEnergyScanner*>(instance); - le_scanner->SetDelegate(this); - - android::sp<IBluetoothLeScannerCallback> cb( - static_cast<IBluetoothLeScannerCallback*>(callback.get())); - cb->OnScannerRegistered(status, (status == bluetooth::BLE_STATUS_SUCCESS) - ? instance->GetInstanceId() - : kInvalidInstanceId); -} - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_le_scanner_binder_server.h b/system/service/ipc/binder/bluetooth_le_scanner_binder_server.h deleted file mode 100644 index 3288a4cc93..0000000000 --- a/system/service/ipc/binder/bluetooth_le_scanner_binder_server.h +++ /dev/null @@ -1,88 +0,0 @@ -// -// Copyright 2016 The Android Open Source Project -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <memory> - -#include <android/bluetooth/IBluetoothLeScannerCallback.h> -#include "android/bluetooth/BnBluetoothLeScanner.h" - -#include "service/common/bluetooth/low_energy_constants.h" -#include "service/ipc/binder/interface_with_instances_base.h" -#include "service/low_energy_scanner.h" - -using android::binder::Status; -using android::String16; - -using android::bluetooth::BnBluetoothLeScanner; -using android::bluetooth::IBluetoothLeScannerCallback; - -namespace bluetooth { -class Adapter; -} // namespace bluetooth - -namespace ipc { -namespace binder { - -// Implements the server side of the IBluetoothLowEnergy interface. -class BluetoothLeScannerBinderServer - : public BnBluetoothLeScanner, - public InterfaceWithInstancesBase, - public bluetooth::LowEnergyScanner::Delegate { - public: - explicit BluetoothLeScannerBinderServer(bluetooth::Adapter* adapter); - BluetoothLeScannerBinderServer(const BluetoothLeScannerBinderServer&) = - delete; - BluetoothLeScannerBinderServer& operator=( - const BluetoothLeScannerBinderServer&) = delete; - - ~BluetoothLeScannerBinderServer() override; - - // IBluetoothLowEnergy overrides: - Status RegisterScanner( - const android::sp<IBluetoothLeScannerCallback>& callback, - bool* _aidl_return) override; - Status UnregisterScanner(int scanner_id) override; - Status UnregisterAll() override; - Status StartScan(int scanner_id, - const android::bluetooth::ScanSettings& settings, - const std::vector<android::bluetooth::ScanFilter>& filters, - bool* _aidl_return) override; - Status StopScan(int scanner_id, bool* _aidl_return) override; - - void OnScanResult(bluetooth::LowEnergyScanner* scanner, - const bluetooth::ScanResult& result) override; - - private: - // Returns a pointer to the IBluetoothLowEnergyCallback instance associated - // with |scanner_id|. Returns NULL if such a callback cannot be found. - android::sp<IBluetoothLeScannerCallback> GetLECallback(int scanner_id); - - // Returns a pointer to the LowEnergyScanner instance associated with - // |scanner_id|. Returns NULL if such a scanner cannot be found. - std::shared_ptr<bluetooth::LowEnergyScanner> GetLEScanner(int scanner_id); - - // InterfaceWithInstancesBase override: - void OnRegisterInstanceImpl(bluetooth::BLEStatus status, - android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) override; - - bluetooth::Adapter* adapter_; // weak -}; - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_low_energy_binder_server.cc b/system/service/ipc/binder/bluetooth_low_energy_binder_server.cc deleted file mode 100644 index 2520d6db83..0000000000 --- a/system/service/ipc/binder/bluetooth_low_energy_binder_server.cc +++ /dev/null @@ -1,181 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/ipc/binder/bluetooth_low_energy_binder_server.h" - -#include <base/logging.h> - -#include "service/adapter.h" - -using android::String8; -using android::String16; -using android::binder::Status; - -namespace ipc { -namespace binder { - -namespace { -const int kInvalidInstanceId = -1; -} // namespace - -BluetoothLowEnergyBinderServer::BluetoothLowEnergyBinderServer( - bluetooth::Adapter* adapter) - : adapter_(adapter) { - CHECK(adapter_); -} - -BluetoothLowEnergyBinderServer::~BluetoothLowEnergyBinderServer() {} - -Status BluetoothLowEnergyBinderServer::RegisterClient( - const android::sp<IBluetoothLowEnergyCallback>& callback, - bool* _aidl_return) { - VLOG(2) << __func__; - bluetooth::LowEnergyClientFactory* ble_factory = - adapter_->GetLowEnergyClientFactory(); - - *_aidl_return = RegisterInstanceBase(callback, ble_factory); - return Status::ok(); -} - -Status BluetoothLowEnergyBinderServer::UnregisterClient(int client_id) { - VLOG(2) << __func__; - UnregisterInstanceBase(client_id); - return Status::ok(); -} - -Status BluetoothLowEnergyBinderServer::UnregisterAll() { - VLOG(2) << __func__; - UnregisterAllBase(); - return Status::ok(); -} - -Status BluetoothLowEnergyBinderServer::Connect(int client_id, - const String16& address, - bool is_direct, - bool* _aidl_return) { - VLOG(2) << __func__ << " client_id: " << client_id << " address: " << address - << " is_direct: " << is_direct; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto client = GetLEClient(client_id); - if (!client) { - LOG(ERROR) << "Unknown client_id: " << client_id; - *_aidl_return = false; - return Status::ok(); - } - - *_aidl_return = - client->Connect(std::string(String8(address).string()), is_direct); - return Status::ok(); -} - -Status BluetoothLowEnergyBinderServer::Disconnect(int client_id, - const String16& address, - bool* _aidl_return) { - VLOG(2) << __func__ << " client_id: " << client_id << " address: " << address; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto client = GetLEClient(client_id); - if (!client) { - LOG(ERROR) << "Unknown client_id: " << client_id; - *_aidl_return = false; - return Status::ok(); - } - - *_aidl_return = client->Disconnect(std::string(String8(address).string())); - return Status::ok(); -} - -Status BluetoothLowEnergyBinderServer::SetMtu(int client_id, - const String16& address, int mtu, - bool* _aidl_return) { - VLOG(2) << __func__ << " client_id: " << client_id << " address: " << address - << " mtu: " << mtu; - std::lock_guard<std::mutex> lock(*maps_lock()); - - auto client = GetLEClient(client_id); - if (!client) { - LOG(ERROR) << "Unknown client_id: " << client_id; - *_aidl_return = false; - return Status::ok(); - } - - *_aidl_return = client->SetMtu(std::string(String8(address).string()), mtu); - return Status::ok(); -} - -void BluetoothLowEnergyBinderServer::OnConnectionState( - bluetooth::LowEnergyClient* client, int status, const char* address, - bool connected) { - VLOG(2) << __func__ << " address: " << address << " connected: " << connected; - - int client_id = client->GetInstanceId(); - auto cb = GetLECallback(client->GetInstanceId()); - if (!cb.get()) { - VLOG(2) << "Client was unregistered - client_id: " << client_id; - return; - } - - cb->OnConnectionState(status, client_id, - String16(address, std::strlen(address)), connected); -} - -void BluetoothLowEnergyBinderServer::OnMtuChanged( - bluetooth::LowEnergyClient* client, int status, const char* address, - int mtu) { - VLOG(2) << __func__ << " address: " << address << " status: " << status - << " mtu: " << mtu; - - int client_id = client->GetInstanceId(); - auto cb = GetLECallback(client_id); - if (!cb.get()) { - VLOG(2) << "Client was unregistered - client_id: " << client_id; - return; - } - - cb->OnMtuChanged(status, String16(address, std::strlen(address)), mtu); -} - -android::sp<IBluetoothLowEnergyCallback> -BluetoothLowEnergyBinderServer::GetLECallback(int client_id) { - auto cb = GetCallback(client_id); - return android::sp<IBluetoothLowEnergyCallback>( - static_cast<IBluetoothLowEnergyCallback*>(cb.get())); -} - -std::shared_ptr<bluetooth::LowEnergyClient> -BluetoothLowEnergyBinderServer::GetLEClient(int client_id) { - return std::static_pointer_cast<bluetooth::LowEnergyClient>( - GetInstance(client_id)); -} - -void BluetoothLowEnergyBinderServer::OnRegisterInstanceImpl( - bluetooth::BLEStatus status, android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) { - VLOG(1) << __func__ << " status: " << status; - bluetooth::LowEnergyClient* le_client = - static_cast<bluetooth::LowEnergyClient*>(instance); - le_client->SetDelegate(this); - - android::sp<IBluetoothLowEnergyCallback> cb( - static_cast<IBluetoothLowEnergyCallback*>(callback.get())); - cb->OnClientRegistered(status, (status == bluetooth::BLE_STATUS_SUCCESS) - ? instance->GetInstanceId() - : kInvalidInstanceId); -} - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/bluetooth_low_energy_binder_server.h b/system/service/ipc/binder/bluetooth_low_energy_binder_server.h deleted file mode 100644 index 0db2312fb8..0000000000 --- a/system/service/ipc/binder/bluetooth_low_energy_binder_server.h +++ /dev/null @@ -1,92 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <memory> - -#include <android/bluetooth/IBluetoothLowEnergyCallback.h> -#include "android/bluetooth/BnBluetoothLowEnergy.h" - -#include "service/common/bluetooth/low_energy_constants.h" -#include "service/ipc/binder/interface_with_instances_base.h" -#include "service/low_energy_client.h" - -using android::binder::Status; -using android::String16; - -using android::bluetooth::BnBluetoothLowEnergy; -using android::bluetooth::IBluetoothLowEnergyCallback; - -namespace bluetooth { -class Adapter; -} // namespace bluetooth - -namespace ipc { -namespace binder { - -// Implements the server side of the IBluetoothLowEnergy interface. -class BluetoothLowEnergyBinderServer - : public BnBluetoothLowEnergy, - public InterfaceWithInstancesBase, - public bluetooth::LowEnergyClient::Delegate { - public: - explicit BluetoothLowEnergyBinderServer(bluetooth::Adapter* adapter); - BluetoothLowEnergyBinderServer(const BluetoothLowEnergyBinderServer&) = - delete; - BluetoothLowEnergyBinderServer& operator=( - const BluetoothLowEnergyBinderServer&) = delete; - - ~BluetoothLowEnergyBinderServer() override; - - // IBluetoothLowEnergy overrides: - Status RegisterClient( - const android::sp<IBluetoothLowEnergyCallback>& callback, - bool* _aidl_return) override; - Status UnregisterClient(int client_id) override; - Status UnregisterAll() override; - Status Connect(int client_id, const String16& address, bool is_direct, - bool* _aidl_return) override; - Status Disconnect(int client_id, const String16& address, - bool* _aidl_return) override; - Status SetMtu(int client_id, const String16& address, int mtu, - bool* _aidl_return) override; - - // bluetooth::LowEnergyClient::Delegate overrides: - void OnConnectionState(bluetooth::LowEnergyClient* client, int status, - const char* address, bool connected) override; - void OnMtuChanged(bluetooth::LowEnergyClient* client, int status, - const char* address, int mtu) override; - - private: - // Returns a pointer to the IBluetoothLowEnergyCallback instance associated - // with |client_id|. Returns NULL if such a callback cannot be found. - android::sp<IBluetoothLowEnergyCallback> GetLECallback(int client_id); - - // Returns a pointer to the LowEnergyClient instance associated with - // |client_id|. Returns NULL if such a client cannot be found. - std::shared_ptr<bluetooth::LowEnergyClient> GetLEClient(int client_id); - - // InterfaceWithInstancesBase override: - void OnRegisterInstanceImpl(bluetooth::BLEStatus status, - android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) override; - - bluetooth::Adapter* adapter_; // weak -}; - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/interface_with_instances_base.cc b/system/service/ipc/binder/interface_with_instances_base.cc deleted file mode 100644 index 1716bbd9ef..0000000000 --- a/system/service/ipc/binder/interface_with_instances_base.cc +++ /dev/null @@ -1,163 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/ipc/binder/interface_with_instances_base.h" - -#include <base/logging.h> - -namespace ipc { -namespace binder { - -bool InterfaceWithInstancesBase::RegisterInstanceBase( - const android::sp<IInterface>& callback, - bluetooth::BluetoothInstanceFactory* factory) { - VLOG(2) << __func__; - CHECK(factory); - - if (!callback.get()) { - LOG(ERROR) << "Cannot register a NULL callback"; - return false; - } - - // Store the callback in the pending list. It will get removed later when the - // stack notifies us asynchronously. - bluetooth::Uuid app_uuid = bluetooth::Uuid::GetRandom(); - if (!pending_callbacks_.Register(app_uuid, callback)) { - LOG(ERROR) << "Failed to store |callback| to map"; - return false; - } - - // Create a weak pointer and pass that to the callback to prevent an invalid - // access later. Since this object is managed using Android's StrongPointer - // (sp) we are using a wp here rather than std::weak_ptr. - android::wp<InterfaceWithInstancesBase> weak_ptr_to_this(this); - - bluetooth::BluetoothInstanceFactory::RegisterCallback cb = - [weak_ptr_to_this]( - bluetooth::BLEStatus status, const bluetooth::Uuid& in_uuid, - std::unique_ptr<bluetooth::BluetoothInstance> instance) { - // If the weak pointer was invalidated then there is nothing we can do. - android::sp<InterfaceWithInstancesBase> strong_ptr_to_this = - weak_ptr_to_this.promote(); - if (!strong_ptr_to_this.get()) { - VLOG(2) << "InterfaceWithInstancesBase was deleted while instance was" - << " being registered"; - return; - } - - strong_ptr_to_this->OnRegisterInstance(status, in_uuid, - std::move(instance)); - }; - - if (factory->RegisterInstance(app_uuid, cb)) return true; - - LOG(ERROR) << "Failed to register instance"; - pending_callbacks_.Remove(app_uuid); - - return false; -} - -void InterfaceWithInstancesBase::UnregisterInstanceBase(int instance_id) { - VLOG(2) << __func__; - std::lock_guard<std::mutex> lock(maps_lock_); - - id_to_cb_.Remove(instance_id); - id_to_instance_.erase(instance_id); -} - -void InterfaceWithInstancesBase::UnregisterAllBase() { - VLOG(2) << __func__; - std::lock_guard<std::mutex> lock(maps_lock_); - - id_to_cb_.Clear(); - id_to_instance_.clear(); -} - -void InterfaceWithInstancesBase::ForEachCallback( - const std::function<void(IInterface*)>& func) { - VLOG(2) << __func__; - std::lock_guard<std::mutex> lock(maps_lock_); - for (auto& pair : id_to_instance_) { - auto cb = id_to_cb_.Get(pair.first); - func(cb.get()); - } -} - -android::sp<IInterface> InterfaceWithInstancesBase::GetCallback( - int instance_id) { - return id_to_cb_.Get(instance_id); -} - -std::shared_ptr<bluetooth::BluetoothInstance> -InterfaceWithInstancesBase::GetInstance(int instance_id) { - auto iter = id_to_instance_.find(instance_id); - if (iter == id_to_instance_.end()) - return std::shared_ptr<bluetooth::BluetoothInstance>(); - return iter->second; -} - -void InterfaceWithInstancesBase::OnRegisterInstance( - bluetooth::BLEStatus status, const bluetooth::Uuid& uuid, - std::unique_ptr<bluetooth::BluetoothInstance> instance) { - VLOG(2) << __func__ << " - status: " << status; - - // Simply remove the callback from |pending_callbacks_| as it no longer - // belongs in there. - sp<IInterface> callback = pending_callbacks_.Remove(uuid); - - // |callback| might be NULL if it was removed from the pending list, e.g. the - // remote process that owns the callback died. - if (!callback.get()) { - VLOG(1) << "Callback was removed before the call to \"RegisterInstance\" " - << "returned; unregistering instance"; - return; - } - - if (status != bluetooth::BLE_STATUS_SUCCESS) { - // The call wasn't successful. Notify the implementation and return. - LOG(ERROR) << "Failed to register instance: " << status; - OnRegisterInstanceImpl(status, callback, nullptr); - return; - } - - std::lock_guard<std::mutex> lock(maps_lock_); - int instance_id = instance->GetInstanceId(); - if (!id_to_cb_.Register(instance_id, callback, this)) { - LOG(ERROR) << "Failed to store callback"; - OnRegisterInstanceImpl(bluetooth::BLE_STATUS_FAILURE, callback, nullptr); - return; - } - - VLOG(1) << "Registered BluetoothInstance - ID: " << instance_id; - - auto shared_instance = - std::shared_ptr<bluetooth::BluetoothInstance>(instance.release()); - id_to_instance_[instance_id] = shared_instance; - - OnRegisterInstanceImpl(status, callback, shared_instance.get()); -} - -void InterfaceWithInstancesBase::OnRemoteCallbackRemoved(const int& key) { - VLOG(2) << __func__ << " instance_id: " << key; - std::lock_guard<std::mutex> lock(maps_lock_); - - // No need to remove from the callback map as the entry should be already - // removed when this callback gets called. - id_to_instance_.erase(key); -} - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/interface_with_instances_base.h b/system/service/ipc/binder/interface_with_instances_base.h deleted file mode 100644 index 4501b00456..0000000000 --- a/system/service/ipc/binder/interface_with_instances_base.h +++ /dev/null @@ -1,107 +0,0 @@ -// -// Copyright (C) 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <memory> -#include <unordered_map> - -#include "bluetooth/uuid.h" -#include "service/bluetooth_instance.h" -#include "service/ipc/binder/remote_callback_map.h" - -namespace ipc { -namespace binder { - -// InterfaceWithInstancesBase provides a common base class for Binder interface -// servers that involve instance callback Binders registered with an integer -// instance ID over an asynchronous lower-level stack API. This class abstracts -// away the common procedures of managing pending callbacks, listening to death -// notifications, and maintaining multiple internal maps in one common base -// class. -// TODO: add code example here. -class InterfaceWithInstancesBase - : public RemoteCallbackMap<int, android::IInterface>::Delegate, - virtual public android::RefBase { - public: - InterfaceWithInstancesBase() = default; - InterfaceWithInstancesBase(const InterfaceWithInstancesBase&) = delete; - InterfaceWithInstancesBase& operator=(const InterfaceWithInstancesBase&) = - delete; - - ~InterfaceWithInstancesBase() override = default; - - protected: - // The initial entry point for registering a instance. Invoke this from the - // registration API to add a instance/Uuid pair to the pending list and set up - // the generic asynchronous callback handler and initiate the process with the - // given |factory| instance. Returns false, if there were any errors that - // could be synchronously reported. - bool RegisterInstanceBase(const android::sp<IInterface>& callback, - bluetooth::BluetoothInstanceFactory* factory); - - // Unregister the instance with the given ID, if it was registered before. - void UnregisterInstanceBase(int instance_id); - - // Unregisters all registered instances. - void UnregisterAllBase(); - - void ForEachCallback(const std::function<void(IInterface*)>& func); - - // Returns a handle to the lock used to synchronize access to the internal - // data structures. Subclasses should acquire this before accessing the maps. - std::mutex* maps_lock() { return &maps_lock_; } - - // Returns the callback interface binder that is assigned to the given - // instance ID |instance_id|. The returned pointer will contain NULL if an - // entry for the given ID cannot be found. - android::sp<IInterface> GetCallback(int instance_id); - - // Returns the instance instance that is assigned to the given instance ID - // |instance_id|. The returned pointer will contain NULL if an entry for the - // given ID cannot be found. - std::shared_ptr<bluetooth::BluetoothInstance> GetInstance(int instance_id); - - private: - // Base implementation of the register callback. - void OnRegisterInstance( - bluetooth::BLEStatus status, const bluetooth::Uuid& uuid, - std::unique_ptr<bluetooth::BluetoothInstance> instance); - - // Called when the callback registration has completed. |instance| is owned by - // the base class and should not be deleted by the implementation. If the - // operation failed, nullptr will be passed for |instance|. - virtual void OnRegisterInstanceImpl( - bluetooth::BLEStatus status, android::sp<IInterface> callback, - bluetooth::BluetoothInstance* instance) = 0; - - // RemoteCallbackMap<int, IBluetoothLowEnergyCallback>::Delegate override: - void OnRemoteCallbackRemoved(const int& key) override; - - // Instances that are pending registration. Once their registration is - // complete, the entry will be removed from this map. - RemoteCallbackMap<bluetooth::Uuid, android::IInterface> pending_callbacks_; - - // We keep two maps here: one from instance_id IDs to callback Binders and one - // from instance_id IDs to the BluetoothInstance structures themselves. - std::mutex maps_lock_; // Needed for |id_to_instance_|. - RemoteCallbackMap<int, IInterface> id_to_cb_; - std::unordered_map<int, std::shared_ptr<bluetooth::BluetoothInstance>> - id_to_instance_; -}; - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/ipc_handler_binder.cc b/system/service/ipc/binder/ipc_handler_binder.cc deleted file mode 100644 index c8249066bc..0000000000 --- a/system/service/ipc/binder/ipc_handler_binder.cc +++ /dev/null @@ -1,79 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/ipc/binder/ipc_handler_binder.h" - -#include <base/functional/bind.h> -#include <base/logging.h> -#include <binder/IPCThreadState.h> -#include <binder/IServiceManager.h> -#include <binder/ProcessState.h> - -#include "abstract_message_loop.h" -#include "service/ipc/binder/bluetooth_binder_server.h" - -using android::defaultServiceManager; -using android::sp; -using android::status_t; -using android::String8; -using android::String16; - -namespace ipc { - -std::string kServiceName = "bluetooth-service"; - -IPCHandlerBinder::IPCHandlerBinder(bluetooth::Adapter* adapter, - IPCManager::Delegate* delegate) - : IPCHandler(adapter, delegate) {} - -IPCHandlerBinder::~IPCHandlerBinder() {} - -bool IPCHandlerBinder::Run() { - CHECK(adapter()); - - // Register the IBluetooth service with the Android ServiceManager. - android::sp<binder::BluetoothBinderServer> bt_server = - new binder::BluetoothBinderServer(adapter()); - status_t status = defaultServiceManager()->addService( - String16(String8(kServiceName.c_str())), bt_server); - if (status != android::NO_ERROR) { - LOG(ERROR) << "Failed to register Bluetooth service with ServiceManager"; - return false; - } - - // Notify the delegate. We do this in the message loop to avoid reentrancy. - if (delegate()) { - btbase::AbstractMessageLoop::current_task_runner()->PostTask( - FROM_HERE, base::Bind(&IPCHandlerBinder::NotifyStarted, this)); - } - - android::ProcessState::self()->startThreadPool(); - - return true; -} - -void IPCHandlerBinder::Stop() { - // TODO(armansito): There are several methods in android::IPCThreadState that - // are related to shutting down the threadpool, however I haven't been able to - // make them shut things down cleanly. Figure out the right way to stop the - // Binder IPC here. -} - -void IPCHandlerBinder::NotifyStarted() { - if (delegate()) delegate()->OnIPCHandlerStarted(IPCManager::TYPE_BINDER); -} - -} // namespace ipc diff --git a/system/service/ipc/binder/ipc_handler_binder.h b/system/service/ipc/binder/ipc_handler_binder.h deleted file mode 100644 index db10e96340..0000000000 --- a/system/service/ipc/binder/ipc_handler_binder.h +++ /dev/null @@ -1,44 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include "service/ipc/ipc_handler.h" -#include "service/ipc/ipc_manager.h" - -namespace ipc { - -// Implements a Binder based IPCHandler. -class IPCHandlerBinder : public IPCHandler { - public: - IPCHandlerBinder(bluetooth::Adapter* adapter, IPCManager::Delegate* delegate); - - IPCHandlerBinder() = delete; - IPCHandlerBinder(const IPCHandlerBinder&) = delete; - IPCHandlerBinder& operator=(const IPCHandlerBinder&) = delete; - - ~IPCHandlerBinder() override; - - // IPCHandler overrides: - bool Run() override; - void Stop() override; - - private: - // Notify the delegate that IPC has started. - void NotifyStarted(); -}; - -} // namespace ipc diff --git a/system/service/ipc/binder/remote_callback_list.h b/system/service/ipc/binder/remote_callback_list.h deleted file mode 100644 index f78bc60855..0000000000 --- a/system/service/ipc/binder/remote_callback_list.h +++ /dev/null @@ -1,204 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <functional> -#include <mutex> -#include <unordered_map> - -#include <base/logging.h> -#include <binder/IBinder.h> -#include <binder/IInterface.h> - -namespace ipc { -namespace binder { - -// Takes care of the grunt work of maintaining a list of remote interfaces, -// typically for the use of performing registered callbacks from a remote -// service. This is a native equivalent of the the android.os.RemoteCallbackList -// Java class. The type "T" must inherit from android::IInterface. -// -// TODO(armansito): We need to unit test this class. Right now it's defined as a -// simple template interface over the native libbinder types directly and we -// can't compile libbinder for host unless the Binder kernel module is enabled -// on the system. Figure out whether to: -// 1) write the Binder test-code in a new target-only executable; -// 2) conditionally compile into the host-native test suite if the Binder -// module is built; -// 3) provide a test-only static library that re-defines the libbinder -// classes as mocks. -// (See http://b/23386387) -// -// TODO(armansito): We should make this class non-final and the template -// interface abstract, so that code that depends on this can be unit tested -// against a mock version of this class. -// -// TODO(armansito): Consider submitting this class to frameworks/native/binder. -template <typename T> -class RemoteCallbackList final { - public: - RemoteCallbackList() = default; - RemoteCallbackList(const RemoteCallbackList&) = delete; - RemoteCallbackList& operator=(const RemoteCallbackList&) = delete; - - ~RemoteCallbackList(); - - // Register and unregister a callback interface. Registering will - // automatically start tracking for death notifications in case the remote - // process hosting the Binder dies. In such a case, the Binder is - // automatically removed from the list. - bool Register(const android::sp<T>& callback); - bool Unregister(const android::sp<T>& callback); - - // Calls the given function on each of the contained callbacks. The internal - // mutex is locked for the duration of the iteration. - void ForEach(const std::function<void(T*)>& callback); - - private: - class CallbackDeathRecipient : public android::IBinder::DeathRecipient { - public: - CallbackDeathRecipient(const android::sp<T>& callback, - RemoteCallbackList* owner); - - android::sp<T> get_callback() const { return callback_; } - - // android::IBinder::DeathRecipient override: - void binderDied(const android::wp<android::IBinder>& who) override; - - private: - android::sp<T> callback_; - RemoteCallbackList<T>* owner_; // weak - }; - - // Typedef for internal map container. This keeps track of a given Binder and - // a death receiver associated with it. - using CallbackMap = std::unordered_map<android::IBinder*, - android::sp<CallbackDeathRecipient>>; - - bool UnregisterInternal(typename CallbackMap::iterator iter); - - std::mutex map_lock_; - CallbackMap callbacks_; -}; - -// Template Implementation details below - -using android::IBinder; -using android::IInterface; -using android::sp; -using android::wp; - -template <typename T> -RemoteCallbackList<T>::~RemoteCallbackList() { - std::lock_guard<std::mutex> lock(map_lock_); - for (auto iter = callbacks_.begin(); iter != callbacks_.end(); ++iter) - UnregisterInternal(iter); -} - -template <typename T> -bool RemoteCallbackList<T>::Register(const sp<T>& callback) { - std::lock_guard<std::mutex> lock(map_lock_); - - sp<IBinder> binder = IInterface::asBinder(callback.get()); - if (callbacks_.find(binder.get()) != callbacks_.end()) { - VLOG(1) << "Callback list already contains given callback"; - return false; - } - - sp<CallbackDeathRecipient> dr(new CallbackDeathRecipient(callback, this)); - - if (binder->linkToDeath(dr) != android::NO_ERROR) { - LOG(ERROR) << "Failed to link death recipient to binder"; - return false; - } - - callbacks_[binder.get()] = dr; - - VLOG(2) << "Callback successfully registered with list"; - - return true; -} - -template <typename T> -bool RemoteCallbackList<T>::Unregister(const sp<T>& callback) { - std::lock_guard<std::mutex> lock(map_lock_); - - sp<IBinder> binder = IInterface::asBinder(callback.get()); - auto iter = callbacks_.find(binder.get()); - if (iter == callbacks_.end()) { - VLOG(2) << "Given callback not registered with this list"; - return false; - } - - return UnregisterInternal(iter); -} - -template <typename T> -void RemoteCallbackList<T>::ForEach(const std::function<void(T*)>& callback) { - std::lock_guard<std::mutex> lock(map_lock_); - for (const auto& iter : callbacks_) - callback(iter.second->get_callback().get()); -} - -template <typename T> -bool RemoteCallbackList<T>::UnregisterInternal( - typename CallbackMap::iterator iter) { - sp<CallbackDeathRecipient> dr = iter->second; - callbacks_.erase(iter); - - if (IInterface::asBinder(dr->get_callback().get())->unlinkToDeath(dr) != - android::NO_ERROR) { - LOG(ERROR) << "Failed to unlink death recipient from binder"; - - // We removed the entry from |map_| but unlinkToDeath failed. There isn't - // really much we can do here other than deleting the binder and returning - // an error. - return false; - } - - VLOG(2) << "Callback successfully removed from list"; - - return true; -} - -template <typename T> -RemoteCallbackList<T>::CallbackDeathRecipient::CallbackDeathRecipient( - const sp<T>& callback, RemoteCallbackList<T>* owner) - : callback_(callback), owner_(owner) { - CHECK(callback_.get()); - CHECK(owner_); -} - -template <typename T> -void RemoteCallbackList<T>::CallbackDeathRecipient::binderDied( - const wp<IBinder>& who) { - VLOG(1) << "Received binderDied"; - - sp<IBinder> binder = IInterface::asBinder(callback_.get()); - CHECK(who.unsafe_get() == binder.get()); - - // Remove the callback but no need to call unlinkToDeath. - std::lock_guard<std::mutex> lock(owner_->map_lock_); - auto iter = owner_->callbacks_.find(binder.get()); - CHECK(iter != owner_->callbacks_.end()); - owner_->callbacks_.erase(iter); - - VLOG(1) << "Callback from dead process unregistered"; -} - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/binder/remote_callback_map.h b/system/service/ipc/binder/remote_callback_map.h deleted file mode 100644 index 96a717b7f0..0000000000 --- a/system/service/ipc/binder/remote_callback_map.h +++ /dev/null @@ -1,245 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <mutex> -#include <unordered_map> - -#include <base/logging.h> -#include <binder/IBinder.h> -#include <binder/IInterface.h> - -namespace ipc { -namespace binder { - -// A map of remote interfaces where the value type "V" must inherit from -// android::IInterface. This is just like RemoteCallbackList except it provides -// a key-value mapping. -// -// TODO(armansito): We should make this class non-final and the template -// interface abstract, so that code that depends on this can be unit tested -// against a mock version of this class. -template <typename K, typename V> -class RemoteCallbackMap final { - public: - RemoteCallbackMap() = default; - RemoteCallbackMap(const RemoteCallbackMap&) = delete; - RemoteCallbackMap& operator=(const RemoteCallbackMap&) = delete; - - ~RemoteCallbackMap(); - - // The Delegate interface is used to notify when a registered callback is - // removed from the map as a result of the death of the remote process that - // owns the registered callback. - class Delegate { - public: - virtual ~Delegate() = default; - - // Called when a remote callback associated with the key |key| has been - // removed. This won't get called if the callback was removed as a result of - // a call to RemoteCallbackMap::Unregister. - virtual void OnRemoteCallbackRemoved(const K& key) = 0; - }; - - // Register a callback interface and associate it with the given key. - // Registering will automatically start tracking for death notifications in - // case the remote process hosting the Binder dies. In such a case, the Binder - // is automatically removed from the map. - // - // An optional |delegate| can be passed which will be assocated with the given - // key/value pair. |delegate| must outlive this map. - bool Register(const K& key, const android::sp<V>& callback, - Delegate* delegate = nullptr); - - // Unregisters a previously registered callback with the given key. Returns - // false if |key| doesn't exist. - bool Unregister(const K& key); - - // Returns the callback associated with the given key. Returns NULL if |key| - // doesn't exist. - android::sp<V> Get(const K& key); - - // Removes the callback associated with the given key from the map and returns - // the value. Returns NULL if the key doesn't exists. - android::sp<V> Remove(const K& key); - - // Clear the contents of the map. - void Clear(); - - private: - class CallbackDeathRecipient : public android::IBinder::DeathRecipient { - public: - CallbackDeathRecipient(const K& key, const android::sp<V>& callback, - RemoteCallbackMap<K, V>* owner, Delegate* delegate); - - android::sp<V> get_callback() const { return callback_; } - - // android::IBinder::DeathRecipient override: - void binderDied(const android::wp<android::IBinder>& who) override; - - private: - K key_; - android::sp<V> callback_; - RemoteCallbackMap<K, V>* owner_; // weak - Delegate* delegate_; // weak - }; - - // Typedef for internal map container. - using CallbackMap = - std::unordered_map<K, android::sp<CallbackDeathRecipient>>; - - bool UnregisterInternal(typename CallbackMap::iterator iter); - - std::mutex map_lock_; - CallbackMap map_; -}; - -// Template Implementation details below - -using android::IBinder; -using android::IInterface; -using android::sp; -using android::wp; -using std::lock_guard; -using std::mutex; - -template <typename K, typename V> -RemoteCallbackMap<K, V>::~RemoteCallbackMap() { - Clear(); -} - -template <typename K, typename V> -bool RemoteCallbackMap<K, V>::Register(const K& key, const sp<V>& callback, - Delegate* delegate) { - lock_guard<mutex> lock(map_lock_); - - if (map_.find(key) != map_.end()) { - VLOG(1) << "Callback map already contains key"; - return false; - } - - sp<CallbackDeathRecipient> dr( - new CallbackDeathRecipient(key, callback, this, delegate)); - sp<IBinder> binder = IInterface::asBinder(callback.get()); - if (binder->linkToDeath(dr) != android::NO_ERROR) { - LOG(ERROR) << "Failed to link death recipient to binder"; - return false; - } - - map_[key] = dr; - - VLOG(2) << "Callback successfully registered with map"; - - return true; -} - -template <typename K, typename V> -bool RemoteCallbackMap<K, V>::Unregister(const K& key) { - lock_guard<mutex> lock(map_lock_); - - auto iter = map_.find(key); - if (iter == map_.end()) { - VLOG(1) << "Callback with given key not found"; - return false; - } - - return UnregisterInternal(iter); -} - -template <typename K, typename V> -sp<V> RemoteCallbackMap<K, V>::Get(const K& key) { - lock_guard<mutex> lock(map_lock_); - - auto iter = map_.find(key); - if (iter == map_.end()) return nullptr; - - return iter->second->get_callback(); -} - -template <typename K, typename V> -sp<V> RemoteCallbackMap<K, V>::Remove(const K& key) { - lock_guard<mutex> lock(map_lock_); - - auto iter = map_.find(key); - if (iter == map_.end()) return nullptr; - - sp<V> val = iter->second->get_callback(); - UnregisterInternal(iter); - - return val; -} -template <typename K, typename V> -void RemoteCallbackMap<K, V>::Clear() { - lock_guard<mutex> lock(map_lock_); - - for (auto iter = map_.begin(); iter != map_.end();) - UnregisterInternal(iter++); -} - -template <typename K, typename V> -bool RemoteCallbackMap<K, V>::UnregisterInternal( - typename CallbackMap::iterator iter) { - sp<CallbackDeathRecipient> dr = iter->second; - map_.erase(iter); - - if (IInterface::asBinder(dr->get_callback().get())->unlinkToDeath(dr) != - android::NO_ERROR) { - LOG(ERROR) << "Failed to unlink death recipient from binder"; - - // We removed the entry from |map_| but unlinkToDeath failed. There isn't - // really much we can do here other than deleting the binder and returning - // an error. - return false; - } - - VLOG(2) << "Callback successfully removed from map"; - - return true; -} - -template <typename K, typename V> -RemoteCallbackMap<K, V>::CallbackDeathRecipient::CallbackDeathRecipient( - const K& key, const sp<V>& callback, RemoteCallbackMap<K, V>* owner, - Delegate* delegate) - : key_(key), callback_(callback), owner_(owner), delegate_(delegate) { - CHECK(callback_.get()); -} - -template <typename K, typename V> -void RemoteCallbackMap<K, V>::CallbackDeathRecipient::binderDied( - const wp<IBinder>& who) { - VLOG(1) << "Received binderDied"; - - sp<IBinder> binder = IInterface::asBinder(callback_.get()); - CHECK(who.unsafe_get() == binder.get()); - - // Remove the callback but no need to call unlinkToDeath. - { - lock_guard<mutex> lock(owner_->map_lock_); - auto iter = owner_->map_.find(key_); - CHECK(iter != owner_->map_.end()); - owner_->map_.erase(iter); - } - - VLOG(1) << "Callback from dead process unregistered; notifying delegate"; - - // Notify delegate. - if (delegate_) delegate_->OnRemoteCallbackRemoved(key_); -} - -} // namespace binder -} // namespace ipc diff --git a/system/service/ipc/dbus/bluetooth_adapter.cc b/system/service/ipc/dbus/bluetooth_adapter.cc deleted file mode 100644 index 6831c1b932..0000000000 --- a/system/service/ipc/dbus/bluetooth_adapter.cc +++ /dev/null @@ -1,122 +0,0 @@ -// -// Copyright 2016 The Android Open Source Project -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/ipc/dbus/bluetooth_adapter.h" -#include <base/files/file_util.h> -#include <base/logging.h> -#include "service/hal/bluetooth_interface.h" - -using ::dbus::Bus; -using ::dbus::ExportedObject; -using ::dbus::MethodCall; -using ::dbus::MessageWriter; -using ::dbus::Response; -using ::dbus::ObjectPath; -using ::dbus::ErrorResponse; - -namespace { - -const std::string kBluetoothAdapterInterface = "org.fluoride.BluetoothAdapter"; -const std::string kEnable = "Enable"; -const std::string kDisable = "Disable"; -const std::string kBluetoothAdapter = "org.fluoride.BluetoothAdapter"; -const std::string kBluetoothAdapterPath = "/org/fluoride/BluetoothAdapter"; - -// TODO(jpawlowski): right now xml interface files are in service/ipc/dbus/ -// folder. Make a script to move them into /usr/share/dbus-1/interfaces -const char kBindingsPath[] = - "/usr/share/dbus-1/interfaces/org.fluoride.BluetoothAdapter.xml"; -const char kDBusIntrospectMethod[] = "Introspect"; - -} // namespace - -namespace ipc { -namespace dbus { - -#if defined(BASE_VER) && BASE_VER > 780000 -// New libchrome treats ResponseSender as base::OnceCallback so we need to move -// ownership before calling ::Run() -inline void RunResponse(std::unique_ptr<Response> response, - ExportedObject::ResponseSender& response_sender) { - std::move(response_sender).Run(std::move(response)); -} -#else -inline void RunResponse(std::unique_ptr<Response> response, - ExportedObject::ResponseSender& response_sender) { - response_sender.Run(std::move(response)); -} -#endif - -BluetoothAdapter::BluetoothAdapter(scoped_refptr<Bus> bus, - bluetooth::Adapter* adapter) - : adapter_(adapter) { - exported_object_ = bus->GetExportedObject(ObjectPath(kBluetoothAdapterPath)); - - CHECK(exported_object_->ExportMethodAndBlock( - kBluetoothAdapterInterface, kEnable, - base::Bind(&BluetoothAdapter::Enable, base::Unretained(this)))); - - CHECK(exported_object_->ExportMethodAndBlock( - kBluetoothAdapterInterface, kDisable, - base::Bind(&BluetoothAdapter::Disable, base::Unretained(this)))); - - CHECK(exported_object_->ExportMethodAndBlock( - DBUS_INTERFACE_INTROSPECTABLE, kDBusIntrospectMethod, - base::Bind(&BluetoothAdapter::Introspect, base::Unretained(this)))); - - CHECK(bus->RequestOwnershipAndBlock(kBluetoothAdapter, Bus::REQUIRE_PRIMARY)) - << "Unable to take ownership of " << kBluetoothAdapter - << ". Make sure you have proper busconfig file " - "/etc/dbus-1/system.d/org.fluoride.conf"; -} - -void BluetoothAdapter::Enable(MethodCall* method_call, - ExportedObject::ResponseSender response_sender) { - VLOG(1) << __func__; - adapter_->Enable(); - RunResponse(Response::FromMethodCall(method_call), response_sender); -} - -void BluetoothAdapter::Disable(MethodCall* method_call, - ExportedObject::ResponseSender response_sender) { - VLOG(1) << __func__; - adapter_->Disable(); - RunResponse(Response::FromMethodCall(method_call), response_sender); -} - -void BluetoothAdapter::Introspect( - MethodCall* method_call, ExportedObject::ResponseSender response_sender) { - VLOG(1) << __func__; - - std::string output; - if (!base::ReadFileToString(base::FilePath(kBindingsPath), &output)) { - PLOG(ERROR) << "Can't read XML bindings from disk:"; - RunResponse(ErrorResponse::FromMethodCall( - method_call, "Can't read XML bindings from disk.", ""), - response_sender); - } - - std::unique_ptr<Response> response(Response::FromMethodCall(method_call)); - MessageWriter writer(response.get()); - writer.AppendString(output); - - RunResponse(std::move(response), response_sender); -} - -BluetoothAdapter::~BluetoothAdapter() {} - -} // namespace dbus -} // namespace ipc diff --git a/system/service/ipc/dbus/bluetooth_adapter.h b/system/service/ipc/dbus/bluetooth_adapter.h deleted file mode 100644 index 484ac1172c..0000000000 --- a/system/service/ipc/dbus/bluetooth_adapter.h +++ /dev/null @@ -1,56 +0,0 @@ -// -// Copyright 2016 The Android Open Source Project -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include "service/adapter.h" - -#include <base/memory/ref_counted.h> -#include <dbus/bus.h> -#include <dbus/exported_object.h> -#include <dbus/message.h> -#include <dbus/object_path.h> -#include <dbus/property.h> - -using ::dbus::Bus; -using ::dbus::ExportedObject; -using ::dbus::MethodCall; - -namespace ipc { -namespace dbus { - -class BluetoothAdapter { - public: - explicit BluetoothAdapter(scoped_refptr<Bus> bus, - bluetooth::Adapter* adapter); - virtual ~BluetoothAdapter(); - - void Enable(MethodCall* method_call, - ExportedObject::ResponseSender response_sender); - - void Disable(MethodCall* method_call, - ExportedObject::ResponseSender response_sender); - - void Introspect(MethodCall* method_call, - ExportedObject::ResponseSender response_sender); - - private: - ExportedObject* exported_object_; - bluetooth::Adapter* adapter_; -}; - -} // namespace dbus -} // namespace ipc diff --git a/system/service/ipc/dbus/ipc_handler_dbus.cc b/system/service/ipc/dbus/ipc_handler_dbus.cc deleted file mode 100644 index 52af25af30..0000000000 --- a/system/service/ipc/dbus/ipc_handler_dbus.cc +++ /dev/null @@ -1,67 +0,0 @@ -// -// Copyright 2016 The Android Open Source Project -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/ipc/dbus/ipc_handler_dbus.h" - -#include <base/functional/bind.h> -#include <base/threading/thread_task_runner_handle.h> -#include <dbus/bus.h> -#include "service/daemon.h" -#include "service/ipc/dbus/bluetooth_adapter.h" - -using dbus::Bus; - -namespace ipc { - -IPCHandlerDBus::IPCHandlerDBus(bluetooth::Adapter* adapter, - IPCManager::Delegate* delegate) - : IPCHandler(adapter, delegate) {} - -IPCHandlerDBus::~IPCHandlerDBus() {} - -bool IPCHandlerDBus::Run() { - LOG(INFO) << __func__; - - dbus_thread_ = new base::Thread("D-Bus Thread"); - base::Thread::Options thread_options; - btbase::set_message_loop_type_IO(thread_options); - dbus_thread_->StartWithOptions(thread_options); - - dbus_thread_->task_runner()->PostTask( - FROM_HERE, base::Bind(&IPCHandlerDBus::InitDbus, base::Unretained(this))); - - return true; -} - -void IPCHandlerDBus::InitDbus() { - LOG(INFO) << __func__; - - Bus::Options bus_options; - bus_options.bus_type = Bus::SYSTEM; - bus_options.connection_type = Bus::PRIVATE; - bus_options.dbus_task_runner = base::ThreadTaskRunnerHandle::Get(); - - scoped_refptr<Bus> bus_ = new Bus(bus_options); - - ipc::dbus::BluetoothAdapter* bluetooth_adapter = - new ipc::dbus::BluetoothAdapter(bus_, adapter()); - - LOG(INFO) << __func__ << ": all services added"; -} - -void IPCHandlerDBus::Stop() { dbus_thread_->Stop(); } - -} // namespace ipc diff --git a/system/service/ipc/dbus/ipc_handler_dbus.h b/system/service/ipc/dbus/ipc_handler_dbus.h deleted file mode 100644 index 6f51ffe213..0000000000 --- a/system/service/ipc/dbus/ipc_handler_dbus.h +++ /dev/null @@ -1,49 +0,0 @@ -// -// Copyright 2016 The Android Open Source Project -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#pragma once - -#include <base/threading/thread.h> -#include "service/ipc/ipc_handler.h" -#include "service/ipc/ipc_manager.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace ipc { - -// Implements a DBus based IPCHandler -class IPCHandlerDBus : public IPCHandler { - public: - IPCHandlerDBus(bluetooth::Adapter* adapter, IPCManager::Delegate* delegate); - - IPCHandlerDBus() = delete; - IPCHandlerDBus(const IPCHandlerDBus&) = delete; - IPCHandlerDBus& operator=(const IPCHandlerDBus&) = delete; - - ~IPCHandlerDBus() override; - - void InitDbus(); - - // IPCHandler overrides: - bool Run() override; - void Stop() override; - - private: - base::Thread* dbus_thread_; -}; - -} // namespace ipc diff --git a/system/service/ipc/dbus/org.fluoride.BluetoothAdapter.xml b/system/service/ipc/dbus/org.fluoride.BluetoothAdapter.xml deleted file mode 100644 index 4a718e6d6c..0000000000 --- a/system/service/ipc/dbus/org.fluoride.BluetoothAdapter.xml +++ /dev/null @@ -1,28 +0,0 @@ -<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" - "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"> -<node name="/org/chromium/SessionManager" - xmlns:doc="http://www.freedesktop.org/dbus/1.0/doc.dtd"> - - <!-- - org.fluoride.BluetoothAdapter: - @short_description: Bluetooth adapter manager. - - Interface for user bluetooth adapter. Right now allows only to enable - and disable the adapter. - --> - <interface name="org.fluoride.BluetoothAdapter"> - <!-- - Enable: - - Enable the bluetooth adapter. - --> - <method name="Enable"></method> - - <!-- - Disable: - - Disable the bluetooth adapter. - --> - <method name="Disable"></method> - </interface> -</node>
\ No newline at end of file diff --git a/system/service/ipc/ipc_handler.cc b/system/service/ipc/ipc_handler.cc deleted file mode 100644 index 11c1a50171..0000000000 --- a/system/service/ipc/ipc_handler.cc +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/ipc/ipc_handler.h" - -#include <base/logging.h> - -namespace ipc { - -IPCHandler::IPCHandler(bluetooth::Adapter* adapter, - IPCManager::Delegate* delegate) - : adapter_(adapter), delegate_(delegate) { - CHECK(adapter_); -} - -IPCHandler::~IPCHandler() {} - -} // namespace ipc diff --git a/system/service/ipc/ipc_handler.h b/system/service/ipc/ipc_handler.h deleted file mode 100644 index 473d6e0f31..0000000000 --- a/system/service/ipc/ipc_handler.h +++ /dev/null @@ -1,63 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <base/memory/ref_counted.h> - -#include "service/ipc/ipc_manager.h" - -namespace bluetooth { -class Adapter; -} // namespace bluetooth - -namespace ipc { - -// IPCHandler is an interface that classes implementing different IPC mechanisms -// must conform to. -class IPCHandler : public base::RefCountedThreadSafe<IPCHandler> { - public: - IPCHandler(bluetooth::Adapter* adapter, IPCManager::Delegate* delegate); - - IPCHandler(const IPCHandler&) = delete; - IPCHandler& operator=(const IPCHandler&) = delete; - - virtual ~IPCHandler(); - - // Initializes and runs the IPC mechanism. Returns true on success, false - // otherwise. - virtual bool Run() = 0; - - // Stops the IPC mechanism. - virtual void Stop() = 0; - - protected: - // Getters for private members to allow subclasses to access them in read-only - // fashion. - bluetooth::Adapter* adapter() const { return adapter_; } - IPCManager::Delegate* delegate() const { return delegate_; } - - private: - IPCHandler() = default; - - // Weak reference to the global Adapter instance. - bluetooth::Adapter* adapter_; - - // The delegate that is interested in notifications from us. - IPCManager::Delegate* delegate_; -}; - -} // namespace ipc diff --git a/system/service/ipc/ipc_handler_linux.cc b/system/service/ipc/ipc_handler_linux.cc deleted file mode 100644 index 43940bebb7..0000000000 --- a/system/service/ipc/ipc_handler_linux.cc +++ /dev/null @@ -1,210 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/ipc/ipc_handler_linux.h" - -#include <sys/socket.h> -#include <sys/un.h> - -#include <base/functional/bind.h> - -#include "abstract_message_loop.h" -#include "osi/include/socket_utils/sockets.h" -#include "service/daemon.h" -#include "service/ipc/linux_ipc_host.h" -#include "service/settings.h" - -namespace ipc { - -IPCHandlerLinux::IPCHandlerLinux(bluetooth::Adapter* adapter, - IPCManager::Delegate* delegate) - : IPCHandler(adapter, delegate), - running_(false), - thread_("IPCHandlerLinux"), - keep_running_(true) {} - -IPCHandlerLinux::~IPCHandlerLinux() { - // This will only be set if the Settings::create_ipc_socket_path() was - // originally provided. - if (!socket_path_.empty()) unlink(socket_path_.value().c_str()); -} - -bool IPCHandlerLinux::Run() { - CHECK(!running_); - - const std::string& android_suffix = - bluetooth::Daemon::Get()->GetSettings()->android_ipc_socket_suffix(); - const base::FilePath& path = - bluetooth::Daemon::Get()->GetSettings()->create_ipc_socket_path(); - - // Both flags cannot be set at the same time. - CHECK(android_suffix.empty() || path.empty()); - if (android_suffix.empty() && path.empty()) { - LOG(ERROR) << "No domain socket path provided"; - return false; - } - - // An origin event loop is required. - CHECK(btbase::AbstractMessageLoop::current_task_runner()); - origin_task_runner_ = btbase::AbstractMessageLoop::current_task_runner(); - - if (!android_suffix.empty()) { - int server_fd = osi_android_get_control_socket(android_suffix.c_str()); - if (server_fd == -1) { - LOG(ERROR) << "Unable to get Android socket from: " << android_suffix; - return false; - } - LOG(INFO) << "Binding to Android server socket:" << android_suffix; - socket_.reset(server_fd); - } else { - LOG(INFO) << "Creating a Unix domain socket:" << path.value(); - - // TODO(armansito): This is opens the door to potentially unlinking files in - // the current directory that we're not supposed to. For now we will have an - // assumption that the daemon runs in a sandbox but we should generally do - // this properly. - unlink(path.value().c_str()); - - base::ScopedFD server_socket(socket(PF_UNIX, SOCK_SEQPACKET, 0)); - if (!server_socket.is_valid()) { - LOG(ERROR) << "Failed to open domain socket for IPC"; - return false; - } - - struct sockaddr_un address; - memset(&address, 0, sizeof(address)); - address.sun_family = AF_UNIX; - strncpy(address.sun_path, path.value().c_str(), - sizeof(address.sun_path) - 1); - if (bind(server_socket.get(), (struct sockaddr*)&address, sizeof(address)) < - 0) { - PLOG(ERROR) << "Failed to bind IPC socket to address"; - return false; - } - - socket_.swap(server_socket); - socket_path_ = path; - } - - CHECK(socket_.is_valid()); - - running_ = true; // Set this here before launching the thread. - - // Start an IO thread and post the listening task. - base::Thread::Options options; - btbase::set_message_loop_type_IO(options); - if (!thread_.StartWithOptions(options)) { - LOG(ERROR) << "Failed to start IPCHandlerLinux thread"; - running_ = false; - return false; - } - - thread_.task_runner()->PostTask( - FROM_HERE, base::Bind(&IPCHandlerLinux::StartListeningOnThread, this)); - - return true; -} - -void IPCHandlerLinux::Stop() { - keep_running_ = false; - - // At this moment the listening thread might be blocking on the accept - // syscall. Shutdown and close the server socket before joining the thread to - // interrupt accept so that the main thread doesn't keep blocking. - shutdown(socket_.get(), SHUT_RDWR); - socket_.reset(); - - // Join and clean up the thread. - thread_.Stop(); - - // Thread exited. Notify the delegate. Post this on the event loop so that the - // callback isn't reentrant. - NotifyStoppedOnOriginThread(); -} - -void IPCHandlerLinux::StartListeningOnThread() { - CHECK(socket_.is_valid()); - CHECK(adapter()); - CHECK(running_); - - LOG(INFO) << "Listening to incoming connections"; - - int status = listen(socket_.get(), SOMAXCONN); - if (status < 0) { - PLOG(ERROR) << "Failed to listen on domain socket"; - origin_task_runner_->PostTask( - FROM_HERE, base::Bind(&IPCHandlerLinux::ShutDownOnOriginThread, this)); - return; - } - - NotifyStartedOnOriginThread(); - - // TODO(armansito): The code below can cause the daemon to run indefinitely if - // the thread is joined while it's in the middle of the EventLoop() call. The - // EventLoop() won't exit until a client terminates the connection, however - // this can be fixed by using the |thread_|'s MessageLoopForIO instead (since - // it gets stopped along with the thread). - // TODO(icoolidge): accept simultaneous clients - while (keep_running_.load()) { - int client_socket = accept4(socket_.get(), nullptr, nullptr, SOCK_NONBLOCK); - if (client_socket < 0) { - PLOG(ERROR) << "Failed to accept client connection"; - continue; - } - - LOG(INFO) << "Established client connection: fd=" << client_socket; - - LinuxIPCHost ipc_host(client_socket, adapter()); - - // TODO(armansito): Use |thread_|'s MessageLoopForIO instead of using a - // custom event loop to poll from the socket. - ipc_host.EventLoop(); - } -} - -void IPCHandlerLinux::ShutDownOnOriginThread() { - LOG(INFO) << "Shutting down IPCHandlerLinux thread"; - thread_.Stop(); - running_ = false; - - NotifyStoppedOnCurrentThread(); -} - -void IPCHandlerLinux::NotifyStartedOnOriginThread() { - if (!delegate()) return; - - origin_task_runner_->PostTask( - FROM_HERE, - base::Bind(&IPCHandlerLinux::NotifyStartedOnCurrentThread, this)); -} - -void IPCHandlerLinux::NotifyStartedOnCurrentThread() { - if (delegate()) delegate()->OnIPCHandlerStarted(IPCManager::TYPE_LINUX); -} - -void IPCHandlerLinux::NotifyStoppedOnOriginThread() { - if (!delegate()) return; - - origin_task_runner_->PostTask( - FROM_HERE, - base::Bind(&IPCHandlerLinux::NotifyStoppedOnCurrentThread, this)); -} - -void IPCHandlerLinux::NotifyStoppedOnCurrentThread() { - if (delegate()) delegate()->OnIPCHandlerStopped(IPCManager::TYPE_LINUX); -} - -} // namespace ipc diff --git a/system/service/ipc/ipc_handler_linux.h b/system/service/ipc/ipc_handler_linux.h deleted file mode 100644 index 743aab2cf4..0000000000 --- a/system/service/ipc/ipc_handler_linux.h +++ /dev/null @@ -1,87 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <atomic> -#include <base/files/file_path.h> -#include <base/files/scoped_file.h> -#include <base/threading/thread.h> - -#include "service/ipc/ipc_handler.h" -#include "service/ipc/ipc_manager.h" - -namespace base { -class SingleThreadTaskRunner; -} // namespace base - -namespace ipc { - -// Implements a Linux sequential packet domain-socket based IPCHandler -class IPCHandlerLinux : public IPCHandler { - public: - IPCHandlerLinux(bluetooth::Adapter* adapter, IPCManager::Delegate* delegate); - - IPCHandlerLinux(const IPCHandlerLinux&) = delete; - IPCHandlerLinux& operator=(const IPCHandlerLinux&) = delete; - - ~IPCHandlerLinux() override; - - // IPCHandler overrides: - bool Run() override; - void Stop() override; - - private: - // Starts listening for incoming connections. Posted on |thread_| by Run(). - void StartListeningOnThread(); - - // Stops the IPC thread. This helper is needed since base::Thread requires - // threads to be stopped on the thread that started them. - void ShutDownOnOriginThread(); - - // Notifies the delegate that we started or stoppedlistening for incoming - // connections. - void NotifyStartedOnOriginThread(); - void NotifyStartedOnCurrentThread(); - void NotifyStoppedOnOriginThread(); - void NotifyStoppedOnCurrentThread(); - -// True, if the IPC mechanism is running. -#if defined(__APPLE__) - bool running_ ATTRIBUTE_UNUSED; -#else - bool running_; -#endif - - // The server socket on which we listen to incoming connections. - base::ScopedFD socket_; - - // The file path to |socket_|. This is only set if we create and manage the - // life time of the socket. - base::FilePath socket_path_; - - // We use a dedicated thread for listening to incoming connections and - // polling from the socket to avoid blocking the main thread. - base::Thread thread_; - - // Whether or not the listening thread should continue to run. - std::atomic<bool> keep_running_; - - // The origin thread's task runner. - scoped_refptr<base::SingleThreadTaskRunner> origin_task_runner_; -}; - -} // namespace ipc diff --git a/system/service/ipc/ipc_manager.cc b/system/service/ipc/ipc_manager.cc deleted file mode 100644 index 04870b44e3..0000000000 --- a/system/service/ipc/ipc_manager.cc +++ /dev/null @@ -1,96 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/ipc/ipc_manager.h" - -#if !defined(OS_GENERIC) -#include "service/ipc/binder/ipc_handler_binder.h" -#else -#include "service/ipc/dbus/ipc_handler_dbus.h" -#endif // !defined(OS_GENERIC) -#include "service/ipc/ipc_handler_linux.h" - -namespace ipc { - -IPCManager::IPCManager(bluetooth::Adapter* adapter) : adapter_(adapter) { - CHECK(adapter_); -} - -IPCManager::~IPCManager() { - // Don't rely on the handlers getting destroyed since another thread might be - // holding a reference to them. Instead, explicitly stop them here. - if (BinderStarted()) binder_handler_->Stop(); - if (LinuxStarted()) linux_handler_->Stop(); - if (DBusStarted()) dbus_handler_->Stop(); -} - -bool IPCManager::Start(Type type, Delegate* delegate) { - switch (type) { - case TYPE_LINUX: - if (LinuxStarted()) { - LOG(ERROR) << "IPCManagerLinux already started."; - return false; - } - - linux_handler_ = new IPCHandlerLinux(adapter_, delegate); - if (!linux_handler_->Run()) { - linux_handler_ = nullptr; - return false; - } - return true; - -#if !defined(OS_GENERIC) - case TYPE_BINDER: - if (BinderStarted()) { - LOG(ERROR) << "IPCManagerBinder already started."; - return false; - } - - binder_handler_ = new IPCHandlerBinder(adapter_, delegate); - if (!binder_handler_->Run()) { - binder_handler_ = nullptr; - return false; - } - return true; -#else - case TYPE_DBUS: - if (DBusStarted()) { - LOG(ERROR) << "IPCManagerDBus already started."; - return false; - } - - dbus_handler_ = new IPCHandlerDBus(adapter_, delegate); - if (!dbus_handler_->Run()) { - dbus_handler_ = nullptr; - return false; - } - return true; -#endif // !defined(OS_GENERIC) - - default: - LOG(ERROR) << "Unsupported IPC type given: " << type; - } - - return false; -} - -bool IPCManager::BinderStarted() const { return binder_handler_.get(); } - -bool IPCManager::LinuxStarted() const { return linux_handler_.get(); } - -bool IPCManager::DBusStarted() const { return dbus_handler_.get(); } - -} // namespace ipc diff --git a/system/service/ipc/ipc_manager.h b/system/service/ipc/ipc_manager.h deleted file mode 100644 index bc5a104e3b..0000000000 --- a/system/service/ipc/ipc_manager.h +++ /dev/null @@ -1,103 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <memory> - -#include <base/memory/ref_counted.h> - -namespace bluetooth { -class Adapter; -} // namespace bluetooth - -namespace ipc { - -class IPCHandler; - -// IPCManager is a class for initializing and running supported IPC mechanisms. -// It manages the life-time of different IPC flavors that are available on the -// system. There are two flavors: a Linux sequential packet domain socket based -// system and one based on the Binder-based android.bluetooth framework. -class IPCManager { - public: - // Possible IPC types. - enum Type { - TYPE_LINUX, // IPC based on a Linux sequential packet domain socket - TYPE_BINDER, // IPC based on the Binder - TYPE_DBUS // IPC based on the DBus - }; - - // Interface for observing events from an IPC mechanism. These methods will be - // called on the thread that started the particular IPC type. - class Delegate { - public: - Delegate() = default; - Delegate(const Delegate&) = delete; - Delegate& operator=(const Delegate&) = delete; - - virtual ~Delegate() = default; - - // Called when an IPC mechanism has successfully started and is ready for - // client connections. - virtual void OnIPCHandlerStarted(Type type) = 0; - - // Called when an IPC mechanism has stopped. This may happen due to an error - // in initialization or due to a regular shut down routine. - virtual void OnIPCHandlerStopped(Type type) = 0; - }; - - explicit IPCManager(bluetooth::Adapter* adapter); - IPCManager(const IPCManager&) = delete; - IPCManager& operator=(const IPCManager&) = delete; - - ~IPCManager(); - - // Initialize the underlying IPC handler based on |type|, if that type has not - // yet been initialized and returns true on success. Returns false if that - // type has already been initialized or an error occurs. - // - // If TYPE_LINUX is given, the file path to use for the domain socket will be - // obtained from the global Settings object. Hence, the Settings object must - // have been initialized before calling this method. - // - // |delegate| must out-live the IPCManager and the underlying handler. Users - // can guarantee proper clean up by deallocating |delegate| when or after - // Delegate::OnIPCHandlerStopped is called. It is safe to destroy |delegate| - // after destroying the IPCManager instance, as the destructor will join and - // clean up all underlying threads. - bool Start(Type type, Delegate* delegate); - - // Returns true if an IPC type has been initialized. - bool BinderStarted() const; - bool LinuxStarted() const; - bool DBusStarted() const; - - private: - IPCManager() = default; - - // Pointers to the different IPC handler classes. These are initialized and - // owned by us. - scoped_refptr<IPCHandler> binder_handler_; - scoped_refptr<IPCHandler> linux_handler_; - scoped_refptr<IPCHandler> dbus_handler_; - - // The Bluetooth adapter instance. This is owned by Daemon so we keep a raw - // pointer to it. - bluetooth::Adapter* adapter_; -}; - -} // namespace ipc diff --git a/system/service/ipc/linux_ipc_host.cc b/system/service/ipc/linux_ipc_host.cc deleted file mode 100644 index ebd41f05a7..0000000000 --- a/system/service/ipc/linux_ipc_host.cc +++ /dev/null @@ -1,338 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#define LOG_TAG "bt_bluetooth_host" - -#include "service/ipc/linux_ipc_host.h" - -#include <errno.h> -#include <stdio.h> -#include <stdlib.h> -#include <sys/ioctl.h> -#include <sys/socket.h> -#include <sys/types.h> -#include <sys/un.h> -#include <unistd.h> - -#include <algorithm> - -#include <base/base64.h> -#include <base/strings/string_number_conversions.h> -#include <base/strings/string_split.h> - -#include "osi/include/log.h" -#include "osi/include/osi.h" -#include "service/adapter.h" - -using bluetooth::Adapter; -using bluetooth::Uuid; - -using namespace bluetooth::gatt; - -namespace { - -// IPC API is according to: -// https://docs.google.com/document/d/1eRnku-jAyVU1wGJsLT2CzWi0-8bs2g49s1b3FR_GApM -const char kSetAdapterNameCommand[] = "set-device-name"; -const char kCreateServiceCommand[] = "create-service"; -const char kDestroyServiceCommand[] = "destroy-service"; -const char kAddCharacteristicCommand[] = "add-characteristic"; -const char kSetCharacteristicValueCommand[] = "set-characteristic-value"; -const char kSetAdvertisementCommand[] = "set-advertisement"; -const char kSetScanResponseCommand[] = "set-scan-response"; -const char kStartServiceCommand[] = "start-service"; -const char kStopServiceCommand[] = "stop-service"; -const char kWriteCharacteristicCommand[] = "write-characteristic"; - -// Useful values for indexing LinuxIPCHost::pfds_ -// Not super general considering that we should be able to support -// many GATT FDs owned by one LinuxIPCHost. -enum { - kFdIpc = 0, - kFdGatt = 1, - kPossibleFds = 2, -}; - -bool TokenBool(const std::string& text) { return text == "true"; } - -} // namespace - -namespace ipc { - -LinuxIPCHost::LinuxIPCHost(int sockfd, Adapter* adapter) - : adapter_(adapter), pfds_(1, {sockfd, POLLIN, 0}) {} - -LinuxIPCHost::~LinuxIPCHost() { close(pfds_[0].fd); } - -bool LinuxIPCHost::EventLoop() { - while (true) { - int status = - TEMP_FAILURE_RETRY(ppoll(pfds_.data(), pfds_.size(), nullptr, nullptr)); - if (status < 1) { - LOG_ERROR("ppoll error"); - return false; - } - - if (pfds_[kFdIpc].revents && !OnMessage()) { - return false; - } - - if (pfds_.size() == kPossibleFds && pfds_[kFdGatt].revents && - !OnGattWrite()) { - return false; - } - } - return true; -} - -bool LinuxIPCHost::OnSetAdapterName(const std::string& name) { - std::string decoded_data; - base::Base64Decode(name, &decoded_data); - return adapter_->SetName(decoded_data); -} - -bool LinuxIPCHost::OnCreateService(const std::string& service_uuid) { - gatt_servers_[service_uuid] = std::unique_ptr<Server>(new Server); - - int gattfd; - bool status = gatt_servers_[service_uuid]->Initialize( - Uuid::FromString(service_uuid), &gattfd); - if (!status) { - LOG_ERROR("Failed to initialize bluetooth"); - return false; - } - pfds_.resize(kPossibleFds); - pfds_[kFdGatt] = {gattfd, POLLIN, 0}; - return true; -} - -bool LinuxIPCHost::OnDestroyService(const std::string& service_uuid) { - gatt_servers_.erase(service_uuid); - close(pfds_[1].fd); - pfds_.resize(1); - return true; -} - -bool LinuxIPCHost::OnAddCharacteristic(const std::string& service_uuid, - const std::string& characteristic_uuid, - const std::string& control_uuid, - const std::string& options) { - std::vector<std::string> option_tokens = base::SplitString( - options, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); - - int properties_mask = 0; - int permissions_mask = 0; - - if (std::find(option_tokens.begin(), option_tokens.end(), "notify") != - option_tokens.end()) { - permissions_mask |= kPermissionRead; - properties_mask |= kPropertyRead; - properties_mask |= kPropertyNotify; - } - if (std::find(option_tokens.begin(), option_tokens.end(), "read") != - option_tokens.end()) { - permissions_mask |= kPermissionRead; - properties_mask |= kPropertyRead; - } - if (std::find(option_tokens.begin(), option_tokens.end(), "write") != - option_tokens.end()) { - permissions_mask |= kPermissionWrite; - properties_mask |= kPropertyWrite; - } - - if (control_uuid.empty()) { - gatt_servers_[service_uuid]->AddCharacteristic( - Uuid::FromString(characteristic_uuid), properties_mask, - permissions_mask); - } else { - gatt_servers_[service_uuid]->AddBlob(Uuid::FromString(characteristic_uuid), - Uuid::FromString(control_uuid), - properties_mask, permissions_mask); - } - return true; -} - -bool LinuxIPCHost::OnSetCharacteristicValue( - const std::string& service_uuid, const std::string& characteristic_uuid, - const std::string& value) { - std::string decoded_data; - base::Base64Decode(value, &decoded_data); - std::vector<uint8_t> blob_data(decoded_data.begin(), decoded_data.end()); - gatt_servers_[service_uuid]->SetCharacteristicValue( - Uuid::FromString(characteristic_uuid), blob_data); - return true; -} - -bool LinuxIPCHost::OnSetAdvertisement(const std::string& service_uuid, - const std::string& advertise_uuids, - const std::string& advertise_data, - const std::string& manufacturer_data, - const std::string& transmit_name) { - LOG_INFO("%s: service:%s uuids:%s data:%s", __func__, service_uuid.c_str(), - advertise_uuids.c_str(), advertise_data.c_str()); - - std::vector<std::string> advertise_uuid_tokens = base::SplitString( - advertise_uuids, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); - - // string -> vector<Uuid> - std::vector<Uuid> ids; - for (const auto& uuid_token : advertise_uuid_tokens) - ids.emplace_back(Uuid::FromString(uuid_token)); - - std::string decoded_data; - base::Base64Decode(advertise_data, &decoded_data); - std::vector<uint8_t> decoded_advertise_data(decoded_data.begin(), - decoded_data.end()); - - base::Base64Decode(manufacturer_data, &decoded_data); - std::vector<uint8_t> decoded_manufacturer_data(decoded_data.begin(), - decoded_data.end()); - - gatt_servers_[service_uuid]->SetAdvertisement(ids, decoded_advertise_data, - decoded_manufacturer_data, - TokenBool(transmit_name)); - return true; -} - -bool LinuxIPCHost::OnSetScanResponse(const std::string& service_uuid, - const std::string& scan_response_uuids, - const std::string& scan_response_data, - const std::string& manufacturer_data, - const std::string& transmit_name) { - std::vector<std::string> scan_response_uuid_tokens = base::SplitString( - scan_response_uuids, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); - - // string -> vector<Uuid> - std::vector<Uuid> ids; - for (const auto& uuid_token : scan_response_uuid_tokens) - ids.emplace_back(Uuid::FromString(uuid_token)); - - std::string decoded_data; - base::Base64Decode(scan_response_data, &decoded_data); - std::vector<uint8_t> decoded_advertise_data(decoded_data.begin(), - decoded_data.end()); - - base::Base64Decode(manufacturer_data, &decoded_data); - std::vector<uint8_t> decoded_manufacturer_data(decoded_data.begin(), - decoded_data.end()); - - gatt_servers_[service_uuid]->SetScanResponse(ids, decoded_advertise_data, - decoded_manufacturer_data, - TokenBool(transmit_name)); - return true; -} - -bool LinuxIPCHost::OnStartService(const std::string& service_uuid) { - return gatt_servers_[service_uuid]->Start(); -} - -bool LinuxIPCHost::OnStopService(const std::string& service_uuid) { - return gatt_servers_[service_uuid]->Stop(); -} - -bool LinuxIPCHost::OnMessage() { - std::string ipc_msg; - ssize_t size; - - OSI_NO_INTR(size = - recv(pfds_[kFdIpc].fd, &ipc_msg[0], 0, MSG_PEEK | MSG_TRUNC)); - if (-1 == size) { - LOG_ERROR("Error reading datagram size: %s", strerror(errno)); - return false; - } else if (0 == size) { - LOG_INFO("%s:%d: Connection closed", __func__, __LINE__); - return false; - } - - ipc_msg.resize(size); - OSI_NO_INTR(size = read(pfds_[kFdIpc].fd, &ipc_msg[0], ipc_msg.size())); - if (-1 == size) { - LOG_ERROR("Error reading IPC: %s", strerror(errno)); - return false; - } else if (0 == size) { - LOG_INFO("%s:%d: Connection closed", __func__, __LINE__); - return false; - } - - std::vector<std::string> tokens = base::SplitString( - ipc_msg, "|", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); - switch (tokens.size()) { - case 2: - if (tokens[0] == kSetAdapterNameCommand) - return OnSetAdapterName(tokens[1]); - if (tokens[0] == kCreateServiceCommand) return OnCreateService(tokens[1]); - if (tokens[0] == kDestroyServiceCommand) - return OnDestroyService(tokens[1]); - if (tokens[0] == kStartServiceCommand) return OnStartService(tokens[1]); - if (tokens[0] == kStopServiceCommand) return OnStopService(tokens[1]); - break; - case 4: - if (tokens[0] == kSetCharacteristicValueCommand) - return OnSetCharacteristicValue(tokens[1], tokens[2], tokens[3]); - break; - case 5: - if (tokens[0] == kAddCharacteristicCommand) - return OnAddCharacteristic(tokens[1], tokens[2], tokens[3], tokens[4]); - break; - case 6: - if (tokens[0] == kSetAdvertisementCommand) - return OnSetAdvertisement(tokens[1], tokens[2], tokens[3], tokens[4], - tokens[5]); - if (tokens[0] == kSetScanResponseCommand) - return OnSetScanResponse(tokens[1], tokens[2], tokens[3], tokens[4], - tokens[5]); - break; - default: - break; - } - - LOG_ERROR("Malformed IPC message: %s", ipc_msg.c_str()); - return false; -} - -bool LinuxIPCHost::OnGattWrite() { - Uuid::UUID128Bit id; - ssize_t r; - - OSI_NO_INTR(r = read(pfds_[kFdGatt].fd, id.data(), id.size())); - if (r != id.size()) { - LOG_ERROR("Error reading GATT attribute ID"); - return false; - } - - std::vector<uint8_t> value; - // TODO(icoolidge): Generalize this for multiple clients. - auto server = gatt_servers_.begin(); - server->second->GetCharacteristicValue(Uuid::From128BitBE(id), &value); - const std::string value_string(value.begin(), value.end()); - std::string encoded_value; - base::Base64Encode(value_string, &encoded_value); - - std::string transmit(kWriteCharacteristicCommand); - transmit += "|" + server->first; - transmit += "|" + base::HexEncode(id.data(), id.size()); - transmit += "|" + encoded_value; - - OSI_NO_INTR(r = write(pfds_[kFdIpc].fd, transmit.data(), transmit.size())); - if (-1 == r) { - LOG_ERROR("Error replying to IPC: %s", strerror(errno)); - return false; - } - - return true; -} - -} // namespace ipc diff --git a/system/service/ipc/linux_ipc_host.h b/system/service/ipc/linux_ipc_host.h deleted file mode 100644 index 012f70ecd8..0000000000 --- a/system/service/ipc/linux_ipc_host.h +++ /dev/null @@ -1,107 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#pragma once - -#include <poll.h> - -#include <bluetooth/uuid.h> -#include <memory> -#include <string> -#include <unordered_map> - -#include "service/gatt_server_old.h" - -namespace bluetooth { -class Adapter; -} // namespace bluetooth - -namespace ipc { - -// This implements a single threaded event loop which dispatches -// reads from a set of FDs (pfds_) to a set of handlers. -// Reads from the GATT pipe read end will result in a write to -// to the IPC socket, and vise versa. -class LinuxIPCHost { - public: - // LinuxIPCHost owns the passed sockfd. - LinuxIPCHost(int sockfd, bluetooth::Adapter* adapter); - ~LinuxIPCHost(); - - // Synchronously handle all events on input FDs. - bool EventLoop(); - - private: - // Handler for IPC message receives. - // Decodes protocol and dispatches to another handler. - bool OnMessage(); - - // Handler for GATT characteristic writes. - // Encodes to protocol and transmits IPC. - bool OnGattWrite(); - - // Applies adapter name changes to stack. - bool OnSetAdapterName(const std::string& name); - - // Handles service creation. - bool OnCreateService(const std::string& service_uuid); - - // Handles service destruction. - bool OnDestroyService(const std::string& service_uuid); - - // Creates a characteristic for a service. - bool OnAddCharacteristic(const std::string& service_uuid, - const std::string& characteristic_uuid, - const std::string& control_uuid, - const std::string& options); - - // Sets the value of a characetistic. - bool OnSetCharacteristicValue(const std::string& service_uuid, - const std::string& characteristic_uuid, - const std::string& value); - - // Applies settings to service advertisement. - bool OnSetAdvertisement(const std::string& service_uuid, - const std::string& advertise_uuids, - const std::string& advertise_data, - const std::string& manufacturer_data, - const std::string& transmit_name); - - // Applies settings to scan response. - bool OnSetScanResponse(const std::string& service_uuid, - const std::string& advertise_uuids, - const std::string& advertise_data, - const std::string& manufacturer_data, - const std::string& transmit_name); - - // Starts service (advertisement and connections) - bool OnStartService(const std::string& service_uuid); - - // Stops service. - bool OnStopService(const std::string& service_uuid); - - // weak reference. - bluetooth::Adapter* adapter_; - - // File descripters that we will block against. - std::vector<struct pollfd> pfds_; - - // Container for multiple GATT servers. Currently only one is supported. - // TODO(icoolidge): support many to one for real. - std::unordered_map<std::string, std::unique_ptr<bluetooth::gatt::Server>> - gatt_servers_; -}; - -} // namespace ipc diff --git a/system/service/logging_helpers.cc b/system/service/logging_helpers.cc deleted file mode 100644 index 78a24e600f..0000000000 --- a/system/service/logging_helpers.cc +++ /dev/null @@ -1,150 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include "logging_helpers.h" - -#include <string> - -#include "types/bt_transport.h" -#include "types/raw_address.h" - -#define CASE_RETURN_TEXT(code) \ - case code: \ - return #code - -const char* BtAvConnectionStateText(const btav_connection_state_t state) { - switch (state) { - CASE_RETURN_TEXT(BTAV_CONNECTION_STATE_DISCONNECTED); - CASE_RETURN_TEXT(BTAV_CONNECTION_STATE_CONNECTING); - CASE_RETURN_TEXT(BTAV_CONNECTION_STATE_CONNECTED); - CASE_RETURN_TEXT(BTAV_CONNECTION_STATE_DISCONNECTING); - default: - return "Invalid AV connection state"; - } -} - -const char* BtAvAudioStateText(const btav_audio_state_t state) { - switch (state) { - CASE_RETURN_TEXT(BTAV_AUDIO_STATE_REMOTE_SUSPEND); - CASE_RETURN_TEXT(BTAV_AUDIO_STATE_STOPPED); - CASE_RETURN_TEXT(BTAV_AUDIO_STATE_STARTED); - default: - return "Invalid audio state"; - } -} - -const char* BtTransportText(const btgatt_transport_t t) { - switch (t) { - CASE_RETURN_TEXT(BT_TRANSPORT_AUTO); - CASE_RETURN_TEXT(BT_TRANSPORT_BR_EDR); - CASE_RETURN_TEXT(BT_TRANSPORT_LE); - default: - return "unknown transport"; - } -} - -const char* BtStateText(const bt_state_t state) { - switch (state) { - CASE_RETURN_TEXT(BT_STATE_OFF); - CASE_RETURN_TEXT(BT_STATE_ON); - default: - return "unknown state code"; - } -} - -const char* BtDiscoveryStateText(const bt_discovery_state_t state) { - switch (state) { - CASE_RETURN_TEXT(BT_DISCOVERY_STOPPED); - CASE_RETURN_TEXT(BT_DISCOVERY_STARTED); - default: - return "unknown discovery state code"; - } -} - -const char* BtScanModeText(const bt_scan_mode_t mode) { - switch (mode) { - CASE_RETURN_TEXT(BT_SCAN_MODE_NONE); - CASE_RETURN_TEXT(BT_SCAN_MODE_CONNECTABLE); - CASE_RETURN_TEXT(BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); - default: - return "unknown scan mode"; - } -} - -const char* BtStatusText(const bt_status_t status) { - switch (status) { - CASE_RETURN_TEXT(BT_STATUS_SUCCESS); - CASE_RETURN_TEXT(BT_STATUS_FAIL); - CASE_RETURN_TEXT(BT_STATUS_NOT_READY); - CASE_RETURN_TEXT(BT_STATUS_NOMEM); - CASE_RETURN_TEXT(BT_STATUS_DONE); - CASE_RETURN_TEXT(BT_STATUS_BUSY); - CASE_RETURN_TEXT(BT_STATUS_UNSUPPORTED); - CASE_RETURN_TEXT(BT_STATUS_PARM_INVALID); - CASE_RETURN_TEXT(BT_STATUS_UNHANDLED); - CASE_RETURN_TEXT(BT_STATUS_AUTH_FAILURE); - CASE_RETURN_TEXT(BT_STATUS_RMT_DEV_DOWN); - CASE_RETURN_TEXT(BT_STATUS_AUTH_REJECTED); - default: - return "unknown status code"; - } -} - -const char* BtPropertyText(const bt_property_type_t prop) { - switch (prop) { - CASE_RETURN_TEXT(BT_PROPERTY_BDNAME); - CASE_RETURN_TEXT(BT_PROPERTY_BDADDR); - CASE_RETURN_TEXT(BT_PROPERTY_UUIDS); - CASE_RETURN_TEXT(BT_PROPERTY_CLASS_OF_DEVICE); - CASE_RETURN_TEXT(BT_PROPERTY_TYPE_OF_DEVICE); - CASE_RETURN_TEXT(BT_PROPERTY_SERVICE_RECORD); - CASE_RETURN_TEXT(BT_PROPERTY_ADAPTER_SCAN_MODE); - CASE_RETURN_TEXT(BT_PROPERTY_ADAPTER_BONDED_DEVICES); - CASE_RETURN_TEXT(BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT); - CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_FRIENDLY_NAME); - CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_RSSI); - CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_VERSION_INFO); - CASE_RETURN_TEXT(BT_PROPERTY_LOCAL_LE_FEATURES); - CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP); - default: - return "Invalid property"; - } -} - -const char* BtEventText(const bt_cb_thread_evt evt) { - switch (evt) { - CASE_RETURN_TEXT(ASSOCIATE_JVM); - CASE_RETURN_TEXT(DISASSOCIATE_JVM); - default: - return "unknown state code"; - } -} - -const char* BtAclText(const bt_acl_state_t code) { - switch (code) { - CASE_RETURN_TEXT(BT_ACL_STATE_CONNECTED); - CASE_RETURN_TEXT(BT_ACL_STATE_DISCONNECTED); - default: - return "unknown ACL code"; - } -} - -std::string BtAddrString(const RawAddress* addr) { - char buffer[20]; - snprintf(buffer, sizeof(buffer), "%02X:%02X:%02X:%02X:%02X:%02X", - addr->address[0], addr->address[1], addr->address[2], - addr->address[3], addr->address[4], addr->address[5]); - return std::string(buffer); -} diff --git a/system/service/logging_helpers.h b/system/service/logging_helpers.h deleted file mode 100644 index 69124300ff..0000000000 --- a/system/service/logging_helpers.h +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#pragma once - -#include <string.h> - -#include <string> - -#include "hardware/bluetooth.h" -#include "hardware/bt_av.h" -#include "hardware/bt_gatt_types.h" -#include "types/raw_address.h" - -const char* BtAvConnectionStateText(const btav_connection_state_t state); - -const char* BtAvAudioStateText(const btav_audio_state_t state); - -const char* BtTransportText(const btgatt_transport_t t); - -const char* BtStateText(const bt_state_t state); - -const char* BtDiscoveryStateText(const bt_discovery_state_t); - -const char* BtScanModeText(const bt_scan_mode_t mode); - -const char* BtStatusText(const bt_status_t status); - -const char* BtPropertyText(const bt_property_type_t prop); - -const char* BtEventText(const bt_cb_thread_evt evt); - -const char* BtAclText(const bt_acl_state_t state); - -// TODO(icoolidge): Address object. -std::string BtAddrString(const RawAddress* addr); diff --git a/system/service/low_energy_advertiser.cc b/system/service/low_energy_advertiser.cc deleted file mode 100644 index e34adb9e75..0000000000 --- a/system/service/low_energy_advertiser.cc +++ /dev/null @@ -1,345 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/low_energy_advertiser.h" - -#include "service/adapter.h" -#include "service/logging_helpers.h" -#include "stack/include/bt_types.h" - -#include <base/functional/bind.h> -#include <base/functional/callback.h> -#include <base/logging.h> - -#include "bind_helpers.h" - -using std::lock_guard; -using std::mutex; - -namespace bluetooth { - -namespace { - -BLEStatus GetBLEStatus(int status) { - if (status == BT_STATUS_FAIL) return BLE_STATUS_FAILURE; - - return static_cast<BLEStatus>(status); -} - -// The Bluetooth Core Specification defines time interval (e.g. Page Scan -// Interval, Advertising Interval, etc) units as 0.625 milliseconds (or 1 -// Baseband slot). The HAL advertising functions expect the interval in this -// unit. This function maps an AdvertiseSettings::Mode value to the -// corresponding time unit. -int GetAdvertisingIntervalUnit(AdvertiseSettings::Mode mode) { - int ms; - - switch (mode) { - case AdvertiseSettings::MODE_BALANCED: - ms = kAdvertisingIntervalMediumMs; - break; - case AdvertiseSettings::MODE_LOW_LATENCY: - ms = kAdvertisingIntervalLowMs; - break; - case AdvertiseSettings::MODE_LOW_POWER: - FALLTHROUGH_INTENDED; /* FALLTHROUGH */ - default: - ms = kAdvertisingIntervalHighMs; - break; - } - - // Convert milliseconds to Bluetooth units. - return (ms * 1000) / 625; -} - -int8_t GetAdvertisingTxPower(AdvertiseSettings::TxPowerLevel tx_power) { - int8_t power; - - switch (tx_power) { - case AdvertiseSettings::TX_POWER_LEVEL_ULTRA_LOW: - power = -21; - break; - case AdvertiseSettings::TX_POWER_LEVEL_LOW: - power = -15; - break; - case AdvertiseSettings::TX_POWER_LEVEL_MEDIUM: - power = -7; - break; - case AdvertiseSettings::TX_POWER_LEVEL_HIGH: - FALLTHROUGH_INTENDED; /* FALLTHROUGH */ - default: - power = 1; - break; - } - - return power; -} - -void GetAdvertiseParams(const AdvertiseSettings& settings, bool has_scan_rsp, - AdvertiseParameters* out_params) { - CHECK(out_params); - - out_params->min_interval = GetAdvertisingIntervalUnit(settings.mode()); - out_params->max_interval = - out_params->min_interval + kAdvertisingIntervalDeltaUnit; - - if (settings.connectable()) - out_params->advertising_event_properties = - kAdvertisingEventTypeLegacyConnectable; - else if (has_scan_rsp) - out_params->advertising_event_properties = - kAdvertisingEventTypeLegacyScannable; - else - out_params->advertising_event_properties = - kAdvertisingEventTypeLegacyNonConnectable; - - out_params->channel_map = kAdvertisingChannelAll; - out_params->tx_power = GetAdvertisingTxPower(settings.tx_power_level()); - - // TODO: expose those new setting through AdvertiseSettings - out_params->primary_advertising_phy = 0x01; - out_params->secondary_advertising_phy = 0x01; - out_params->scan_request_notification_enable = 0; -} - -} // namespace - -// LowEnergyAdvertiser implementation - -LowEnergyAdvertiser::LowEnergyAdvertiser(const Uuid& uuid, int advertiser_id) - : app_identifier_(uuid), - advertiser_id_(advertiser_id), - adv_started_(false), - adv_start_callback_(nullptr), - adv_stop_callback_(nullptr) {} - -LowEnergyAdvertiser::~LowEnergyAdvertiser() { - // Automatically unregister the advertiser. - VLOG(1) << "LowEnergyAdvertiser unregistering advertiser: " << advertiser_id_; - - // Stop advertising and ignore the result. - hal::BluetoothGattInterface::Get()->GetAdvertiserHALInterface()->Enable( - advertiser_id_, false, base::DoNothing(), 0, 0, base::DoNothing()); - hal::BluetoothGattInterface::Get()->GetAdvertiserHALInterface()->Unregister( - advertiser_id_); -} - -bool LowEnergyAdvertiser::StartAdvertising(const AdvertiseSettings& settings, - const AdvertiseData& advertise_data, - const AdvertiseData& scan_response, - const StatusCallback& callback) { - VLOG(2) << __func__; - lock_guard<mutex> lock(adv_fields_lock_); - - if (IsAdvertisingStarted()) { - LOG(WARNING) << "Already advertising"; - return false; - } - - if (IsStartingAdvertising()) { - LOG(WARNING) << "StartAdvertising already pending"; - return false; - } - - if (!advertise_data.IsValid()) { - LOG(ERROR) << "Invalid advertising data"; - return false; - } - - if (!scan_response.IsValid()) { - LOG(ERROR) << "Invalid scan response data"; - return false; - } - - advertise_settings_ = settings; - - AdvertiseParameters params; - GetAdvertiseParams(settings, !scan_response.data().empty(), ¶ms); - - hal::BluetoothGattInterface::Get() - ->GetAdvertiserHALInterface() - ->StartAdvertising( - advertiser_id_, - base::Bind(&LowEnergyAdvertiser::EnableCallback, - base::Unretained(this), true, advertiser_id_), - params, advertise_data.data(), scan_response.data(), - settings.timeout().InSeconds(), - base::Bind(&LowEnergyAdvertiser::EnableCallback, - base::Unretained(this), false, advertiser_id_)); - ; - - adv_start_callback_.reset(new StatusCallback(callback)); - return true; -} - -bool LowEnergyAdvertiser::StopAdvertising(const StatusCallback& callback) { - VLOG(2) << __func__; - lock_guard<mutex> lock(adv_fields_lock_); - - if (!IsAdvertisingStarted()) { - LOG(ERROR) << "Not advertising"; - return false; - } - - if (IsStoppingAdvertising()) { - LOG(ERROR) << "StopAdvertising already pending"; - return false; - } - - hal::BluetoothGattInterface::Get()->GetAdvertiserHALInterface()->Enable( - advertiser_id_, false, - base::Bind(&LowEnergyAdvertiser::EnableCallback, base::Unretained(this), - false, advertiser_id_), - 0, 0, base::Bind(&LowEnergyAdvertiser::EnableCallback, - base::Unretained(this), false, advertiser_id_)); - - // OK to set this at the end since we're still holding |adv_fields_lock_|. - adv_stop_callback_.reset(new StatusCallback(callback)); - - return true; -} - -bool LowEnergyAdvertiser::IsAdvertisingStarted() const { - return adv_started_.load(); -} - -bool LowEnergyAdvertiser::IsStartingAdvertising() const { - return !IsAdvertisingStarted() && adv_start_callback_; -} - -bool LowEnergyAdvertiser::IsStoppingAdvertising() const { - return IsAdvertisingStarted() && adv_stop_callback_; -} - -const Uuid& LowEnergyAdvertiser::GetAppIdentifier() const { - return app_identifier_; -} - -int LowEnergyAdvertiser::GetInstanceId() const { return advertiser_id_; } - -void LowEnergyAdvertiser::EnableCallback(bool enable, uint8_t advertiser_id, - uint8_t status) { - if (advertiser_id != advertiser_id_) return; - - lock_guard<mutex> lock(adv_fields_lock_); - - VLOG(1) << __func__ << "advertiser_id: " << advertiser_id - << " status: " << status << " enable: " << enable; - - if (enable) { - CHECK(adv_start_callback_); - CHECK(!adv_stop_callback_); - - // Terminate operation in case of error. - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to enable multi-advertising"; - InvokeAndClearStartCallback(GetBLEStatus(status)); - return; - } - - // All pending tasks are complete. Report success. - adv_started_ = true; - InvokeAndClearStartCallback(BLE_STATUS_SUCCESS); - - } else { - CHECK(!adv_start_callback_); - CHECK(adv_stop_callback_); - - if (status == BT_STATUS_SUCCESS) { - VLOG(1) << "Multi-advertising stopped for advertiser_id: " - << advertiser_id; - adv_started_ = false; - } else { - LOG(ERROR) << "Failed to stop multi-advertising"; - } - - InvokeAndClearStopCallback(GetBLEStatus(status)); - } -} - -void LowEnergyAdvertiser::InvokeAndClearStartCallback(BLEStatus status) { - // We allow NULL callbacks. - if (*adv_start_callback_) (*adv_start_callback_)(status); - - adv_start_callback_ = nullptr; -} - -void LowEnergyAdvertiser::InvokeAndClearStopCallback(BLEStatus status) { - // We allow NULL callbacks. - if (*adv_stop_callback_) (*adv_stop_callback_)(status); - - adv_stop_callback_ = nullptr; -} - -// LowEnergyAdvertiserFactory implementation - -LowEnergyAdvertiserFactory::LowEnergyAdvertiserFactory() {} - -LowEnergyAdvertiserFactory::~LowEnergyAdvertiserFactory() {} - -bool LowEnergyAdvertiserFactory::RegisterInstance( - const Uuid& app_uuid, const RegisterCallback& callback) { - VLOG(1) << __func__; - lock_guard<mutex> lock(pending_calls_lock_); - - if (pending_calls_.find(app_uuid) != pending_calls_.end()) { - LOG(ERROR) << "Low-Energy advertiser with given Uuid already registered - " - << "Uuid: " << app_uuid.ToString(); - return false; - } - - BleAdvertiserInterface* hal_iface = - hal::BluetoothGattInterface::Get()->GetAdvertiserHALInterface(); - - VLOG(1) << __func__ << " calling register!"; - hal_iface->RegisterAdvertiser( - base::Bind(&LowEnergyAdvertiserFactory::RegisterAdvertiserCallback, - base::Unretained(this), callback, app_uuid)); - VLOG(1) << __func__ << " call finished!"; - - pending_calls_.insert(app_uuid); - - return true; -} - -void LowEnergyAdvertiserFactory::RegisterAdvertiserCallback( - const RegisterCallback& callback, const Uuid& app_uuid, - uint8_t advertiser_id, uint8_t status) { - VLOG(1) << __func__; - lock_guard<mutex> lock(pending_calls_lock_); - - auto iter = pending_calls_.find(app_uuid); - if (iter == pending_calls_.end()) { - VLOG(1) << "Ignoring callback for unknown app_id: " << app_uuid.ToString(); - return; - } - - // No need to construct a advertiser if the call wasn't successful. - std::unique_ptr<LowEnergyAdvertiser> advertiser; - BLEStatus result = BLE_STATUS_FAILURE; - if (status == BT_STATUS_SUCCESS) { - advertiser.reset(new LowEnergyAdvertiser(app_uuid, advertiser_id)); - - result = BLE_STATUS_SUCCESS; - } - - // Notify the result via the result callback. - callback(result, app_uuid, std::move(advertiser)); - - pending_calls_.erase(iter); -} - -} // namespace bluetooth diff --git a/system/service/low_energy_advertiser.h b/system/service/low_energy_advertiser.h deleted file mode 100644 index 46d5316965..0000000000 --- a/system/service/low_energy_advertiser.h +++ /dev/null @@ -1,147 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <atomic> -#include <functional> -#include <map> -#include <mutex> - -#include <bluetooth/uuid.h> - -#include "service/bluetooth_instance.h" -#include "service/common/bluetooth/advertise_data.h" -#include "service/common/bluetooth/advertise_settings.h" -#include "service/common/bluetooth/low_energy_constants.h" -#include "service/common/bluetooth/scan_filter.h" -#include "service/common/bluetooth/scan_result.h" -#include "service/common/bluetooth/scan_settings.h" -#include "service/hal/bluetooth_gatt_interface.h" - -namespace bluetooth { - -class Adapter; - -// A LowEnergyAdvertiser represents an application's handle to perform various -// Bluetooth Low Energy GAP operations. Instances cannot be created directly and -// should be obtained through the factory. -class LowEnergyAdvertiser : public BluetoothInstance { - public: - LowEnergyAdvertiser(const LowEnergyAdvertiser&) = delete; - LowEnergyAdvertiser& operator=(const LowEnergyAdvertiser&) = delete; - - // The destructor automatically unregisters this client instance from the - // stack. - ~LowEnergyAdvertiser() override; - - // Callback type used to return the result of asynchronous operations below. - using StatusCallback = std::function<void(BLEStatus)>; - - // Starts advertising based on the given advertising and scan response - // data and the provided |settings|. Reports the result of the operation in - // |callback|. Return true on success, false otherwise. Please see logs for - // details in case of error. - bool StartAdvertising(const AdvertiseSettings& settings, - const AdvertiseData& advertise_data, - const AdvertiseData& scan_response, - const StatusCallback& callback); - - // Stops advertising if it was already started. Reports the result of the - // operation in |callback|. - bool StopAdvertising(const StatusCallback& callback); - - // Returns true if advertising has been started. - bool IsAdvertisingStarted() const; - - // Returns the state of pending advertising operations. - bool IsStartingAdvertising() const; - bool IsStoppingAdvertising() const; - - // Returns the current advertising settings. - const AdvertiseSettings& advertise_settings() const { - return advertise_settings_; - } - - // BluetoothClientInstace overrides: - const Uuid& GetAppIdentifier() const override; - int GetInstanceId() const override; - - private: - friend class LowEnergyAdvertiserFactory; - - // Constructor shouldn't be called directly as instances are meant to be - // obtained from the factory. - LowEnergyAdvertiser(const Uuid& uuid, int advertiser_id); - - // BluetoothGattInterface::AdvertiserObserver overrides: - void SetDataCallback(uint8_t advertiser_id, uint8_t status); - void SetParamsCallback(uint8_t advertiser_id, uint8_t status); - void EnableCallback(bool enable, uint8_t advertiser_id, uint8_t status); - - // Calls and clears the pending callbacks. - void InvokeAndClearStartCallback(BLEStatus status); - void InvokeAndClearStopCallback(BLEStatus status); - - // See getters above for documentation. - Uuid app_identifier_; - int advertiser_id_; - - // Protects advertising-related members below. - std::mutex adv_fields_lock_; - - // Latest advertising settings. - AdvertiseSettings advertise_settings_; - - std::atomic_bool adv_started_; - std::unique_ptr<StatusCallback> adv_start_callback_; - std::unique_ptr<StatusCallback> adv_stop_callback_; -}; - -// LowEnergyAdvertiserFactory is used to register and obtain a per-application -// LowEnergyAdvertiser instance. Users should call RegisterInstance to obtain -// their -// own unique LowEnergyAdvertiser instance that has been registered with the -// Bluetooth stack. -class LowEnergyAdvertiserFactory : public BluetoothInstanceFactory { - public: - // Don't construct/destruct directly except in tests. Instead, obtain a handle - // from an Adapter instance. - explicit LowEnergyAdvertiserFactory(); - LowEnergyAdvertiserFactory(const LowEnergyAdvertiserFactory&) = delete; - LowEnergyAdvertiserFactory& operator=(const LowEnergyAdvertiserFactory&) = - delete; - - ~LowEnergyAdvertiserFactory() override; - - // BluetoothInstanceFactory override: - bool RegisterInstance(const Uuid& app_uuid, - const RegisterCallback& callback) override; - - private: - friend class LowEnergyAdvertiser; - - // BluetoothGattInterface::AdvertiserObserver overrides: - void RegisterAdvertiserCallback(const RegisterCallback& callback, - const Uuid& app_uuid, uint8_t advertiser_id, - uint8_t status); - - // Map of pending calls to register. - std::mutex pending_calls_lock_; - std::unordered_set<Uuid> pending_calls_; -}; - -} // namespace bluetooth diff --git a/system/service/low_energy_client.cc b/system/service/low_energy_client.cc deleted file mode 100644 index 98a76f97e5..0000000000 --- a/system/service/low_energy_client.cc +++ /dev/null @@ -1,261 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/low_energy_client.h" - -#include <base/logging.h> - -#include "service/adapter.h" -#include "service/logging_helpers.h" -#include "stack/include/bt_types.h" -#include "types/bt_transport.h" -#include "types/raw_address.h" - -using std::lock_guard; -using std::mutex; - -constexpr int kPhyLe1MbMask = 1; - -namespace bluetooth { - -// LowEnergyClient implementation - -LowEnergyClient::LowEnergyClient(Adapter& adapter, const Uuid& uuid, - int client_id) - : adapter_(adapter), - app_identifier_(uuid), - client_id_(client_id), - delegate_(nullptr) {} - -LowEnergyClient::~LowEnergyClient() { - // Automatically unregister the client. - VLOG(1) << "LowEnergyClient unregistering client: " << client_id_; - - // Unregister as observer so we no longer receive any callbacks. - hal::BluetoothGattInterface::Get()->RemoveClientObserver(this); - - hal::BluetoothGattInterface::Get() - ->GetClientHALInterface() - ->unregister_client(client_id_); -} - -bool LowEnergyClient::Connect(const std::string& address, bool is_direct) { - VLOG(2) << __func__ << "Address: " << address << " is_direct: " << is_direct; - - RawAddress bda; - RawAddress::FromString(address, bda); - - bt_status_t status = - hal::BluetoothGattInterface::Get()->GetClientHALInterface()->connect( - client_id_, bda, is_direct, BT_TRANSPORT_LE, false, kPhyLe1MbMask); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "HAL call to connect failed"; - return false; - } - - return true; -} - -bool LowEnergyClient::Disconnect(const std::string& address) { - VLOG(2) << __func__ << "Address: " << address; - - RawAddress bda; - RawAddress::FromString(address, bda); - - std::map<const RawAddress, int>::iterator conn_id; - { - lock_guard<mutex> lock(connection_fields_lock_); - conn_id = connection_ids_.find(bda); - if (conn_id == connection_ids_.end()) { - LOG(WARNING) << "Can't disconnect, no existing connection to " << address; - return false; - } - } - - bt_status_t status = - hal::BluetoothGattInterface::Get()->GetClientHALInterface()->disconnect( - client_id_, bda, conn_id->second); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "HAL call to disconnect failed"; - return false; - } - - return true; -} - -bool LowEnergyClient::SetMtu(const std::string& address, int mtu) { - VLOG(2) << __func__ << "Address: " << address << " MTU: " << mtu; - - RawAddress bda; - RawAddress::FromString(address, bda); - - std::map<const RawAddress, int>::iterator conn_id; - { - lock_guard<mutex> lock(connection_fields_lock_); - conn_id = connection_ids_.find(bda); - if (conn_id == connection_ids_.end()) { - LOG(WARNING) << "Can't set MTU, no existing connection to " << address; - return false; - } - } - - bt_status_t status = hal::BluetoothGattInterface::Get() - ->GetClientHALInterface() - ->configure_mtu(conn_id->second, mtu); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "HAL call to set MTU failed"; - return false; - } - - return true; -} - -void LowEnergyClient::SetDelegate(Delegate* delegate) { - lock_guard<mutex> lock(delegate_mutex_); - delegate_ = delegate; -} - -const Uuid& LowEnergyClient::GetAppIdentifier() const { - return app_identifier_; -} - -int LowEnergyClient::GetInstanceId() const { return client_id_; } - -void LowEnergyClient::ConnectCallback(hal::BluetoothGattInterface* gatt_iface, - int conn_id, int status, int client_id, - const RawAddress& bda) { - if (client_id != client_id_) return; - - VLOG(1) << __func__ << "client_id: " << client_id << " status: " << status; - - { - lock_guard<mutex> lock(connection_fields_lock_); - auto success = connection_ids_.emplace(bda, conn_id); - if (!success.second) { - LOG(ERROR) << __func__ << " Insertion into connection_ids_ failed!"; - } - } - - if (delegate_) - delegate_->OnConnectionState(this, status, BtAddrString(&bda).c_str(), - true); -} - -void LowEnergyClient::DisconnectCallback( - hal::BluetoothGattInterface* gatt_iface, int conn_id, int status, - int client_id, const RawAddress& bda) { - if (client_id != client_id_) return; - - VLOG(1) << __func__ << " client_id: " << client_id << " status: " << status; - { - lock_guard<mutex> lock(connection_fields_lock_); - if (!connection_ids_.erase(bda)) { - LOG(ERROR) << __func__ << " Erasing from connection_ids_ failed!"; - } - } - - if (delegate_) - delegate_->OnConnectionState(this, status, BtAddrString(&bda).c_str(), - false); -} - -void LowEnergyClient::MtuChangedCallback( - hal::BluetoothGattInterface* gatt_iface, int conn_id, int status, int mtu) { - VLOG(1) << __func__ << " conn_id: " << conn_id << " status: " << status - << " mtu: " << mtu; - - const RawAddress* bda = nullptr; - { - lock_guard<mutex> lock(connection_fields_lock_); - for (auto& connection : connection_ids_) { - if (connection.second == conn_id) { - bda = &connection.first; - break; - } - } - } - - if (!bda) return; - - std::string addr = BtAddrString(bda); - if (delegate_) delegate_->OnMtuChanged(this, status, addr.c_str(), mtu); -} - -// LowEnergyClientFactory implementation - -LowEnergyClientFactory::LowEnergyClientFactory(Adapter& adapter) - : adapter_(adapter) { - hal::BluetoothGattInterface::Get()->AddClientObserver(this); -} - -LowEnergyClientFactory::~LowEnergyClientFactory() { - hal::BluetoothGattInterface::Get()->RemoveClientObserver(this); -} - -bool LowEnergyClientFactory::RegisterInstance( - const Uuid& uuid, const RegisterCallback& callback) { - VLOG(1) << __func__ << " - Uuid: " << uuid.ToString(); - lock_guard<mutex> lock(pending_calls_lock_); - - if (pending_calls_.find(uuid) != pending_calls_.end()) { - LOG(ERROR) << "Low-Energy client with given Uuid already registered - " - << "Uuid: " << uuid.ToString(); - return false; - } - - const btgatt_client_interface_t* hal_iface = - hal::BluetoothGattInterface::Get()->GetClientHALInterface(); - - if (hal_iface->register_client(uuid, false) != BT_STATUS_SUCCESS) - return false; - - pending_calls_[uuid] = callback; - - return true; -} - -void LowEnergyClientFactory::RegisterClientCallback( - hal::BluetoothGattInterface* gatt_iface, int status, int client_id, - const bluetooth::Uuid& app_uuid) { - Uuid uuid(app_uuid); - - VLOG(1) << __func__ << " - Uuid: " << uuid.ToString(); - lock_guard<mutex> lock(pending_calls_lock_); - - auto iter = pending_calls_.find(uuid); - if (iter == pending_calls_.end()) { - VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString(); - return; - } - - // No need to construct a client if the call wasn't successful. - std::unique_ptr<LowEnergyClient> client; - BLEStatus result = BLE_STATUS_FAILURE; - if (status == BT_STATUS_SUCCESS) { - client.reset(new LowEnergyClient(adapter_, uuid, client_id)); - - gatt_iface->AddClientObserver(client.get()); - - result = BLE_STATUS_SUCCESS; - } - - // Notify the result via the result callback. - iter->second(result, uuid, std::move(client)); - - pending_calls_.erase(iter); -} - -} // namespace bluetooth diff --git a/system/service/low_energy_client.h b/system/service/low_energy_client.h deleted file mode 100644 index ba39357fe7..0000000000 --- a/system/service/low_energy_client.h +++ /dev/null @@ -1,177 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <bluetooth/uuid.h> - -#include <atomic> -#include <functional> -#include <map> -#include <mutex> - -#include "service/bluetooth_instance.h" -#include "service/common/bluetooth/low_energy_constants.h" -#include "service/common/bluetooth/scan_filter.h" -#include "service/common/bluetooth/scan_result.h" -#include "service/common/bluetooth/scan_settings.h" -#include "service/hal/bluetooth_gatt_interface.h" -#include "types/raw_address.h" - -namespace bluetooth { - -struct ConnComparator { - bool operator()(const RawAddress& a, const RawAddress& b) const { - return memcmp(a.address, b.address, RawAddress::kLength) < 0; - } -}; - -class Adapter; - -// A LowEnergyClient represents an application's handle to perform various -// Bluetooth Low Energy GAP operations. Instances cannot be created directly and -// should be obtained through the factory. -class LowEnergyClient : private hal::BluetoothGattInterface::ClientObserver, - public BluetoothInstance { - public: - // The Delegate interface is used to notify asynchronous events related to BLE - // GAP operations. - class Delegate { - public: - Delegate() = default; - Delegate(const Delegate&) = delete; - Delegate& operator=(const Delegate&) = delete; - - virtual ~Delegate() = default; - - // Called asynchronously to notify the delegate of connection state change - virtual void OnConnectionState(LowEnergyClient* client, int status, - const char* address, bool connected) = 0; - - // Called asynchronously to notify the delegate of mtu change - virtual void OnMtuChanged(LowEnergyClient* client, int status, - const char* address, int mtu) = 0; - }; - - LowEnergyClient(const LowEnergyClient&) = delete; - LowEnergyClient& operator=(const LowEnergyClient&) = delete; - - // The destructor automatically unregisters this client instance from the - // stack. - ~LowEnergyClient() override; - - // Assigns a delegate to this instance. |delegate| must out-live this - // LowEnergyClient instance. - void SetDelegate(Delegate* delegate); - - // Callback type used to return the result of asynchronous operations below. - using StatusCallback = std::function<void(BLEStatus)>; - - // Initiates a BLE connection do device with address |address|. If - // |is_direct| is set, use direct connect procedure. Return true on success - //, false otherwise. - bool Connect(const std::string& address, bool is_direct); - - // Disconnect from previously connected BLE device with address |address|. - // Return true on success, false otherwise. - bool Disconnect(const std::string& address); - - // Sends request to set MTU to |mtu| for device with address |address|. - // Return true on success, false otherwise. - bool SetMtu(const std::string& address, int mtu); - - // BluetoothClientInstace overrides: - const Uuid& GetAppIdentifier() const override; - int GetInstanceId() const override; - - private: - friend class LowEnergyClientFactory; - - // Constructor shouldn't be called directly as instances are meant to be - // obtained from the factory. - LowEnergyClient(Adapter& adapter, const Uuid& uuid, int client_id); - - // BluetoothGattInterface::ClientObserver overrides: - void ConnectCallback(hal::BluetoothGattInterface* gatt_iface, int conn_id, - int status, int client_id, - const RawAddress& bda) override; - void DisconnectCallback(hal::BluetoothGattInterface* gatt_iface, int conn_id, - int status, int client_id, - const RawAddress& bda) override; - void MtuChangedCallback(hal::BluetoothGattInterface* gatt_iface, int conn_id, - int status, int mtu) override; - - // Calls and clears the pending callbacks. - void InvokeAndClearStartCallback(BLEStatus status); - void InvokeAndClearStopCallback(BLEStatus status); - - // Raw pointer to the Bluetooth Adapter. - Adapter& adapter_; - - // See getters above for documentation. - Uuid app_identifier_; - int client_id_; - - // Raw handle to the Delegate, which must outlive this LowEnergyClient - // instance. - std::mutex delegate_mutex_; - Delegate* delegate_; - - // Protects device connection related members below. - std::mutex connection_fields_lock_; - - // Maps bluetooth address to connection id - // TODO(jpawlowski): change type to bimap - std::map<const RawAddress, int, ConnComparator> connection_ids_; -}; - -// LowEnergyClientFactory is used to register and obtain a per-application -// LowEnergyClient instance. Users should call RegisterInstance to obtain their -// own unique LowEnergyClient instance that has been registered with the -// Bluetooth stack. -class LowEnergyClientFactory - : private hal::BluetoothGattInterface::ClientObserver, - public BluetoothInstanceFactory { - public: - // Don't construct/destruct directly except in tests. Instead, obtain a handle - // from an Adapter instance. - explicit LowEnergyClientFactory(Adapter& adapter); - LowEnergyClientFactory(const LowEnergyClientFactory&) = delete; - LowEnergyClientFactory& operator=(const LowEnergyClientFactory&) = delete; - - ~LowEnergyClientFactory() override; - - // BluetoothInstanceFactory override: - bool RegisterInstance(const Uuid& uuid, - const RegisterCallback& callback) override; - - private: - friend class LowEnergyClient; - - // BluetoothGattInterface::ClientObserver overrides: - void RegisterClientCallback(hal::BluetoothGattInterface* gatt_iface, - int status, int client_id, - const bluetooth::Uuid& app_uuid) override; - - // Map of pending calls to register. - std::mutex pending_calls_lock_; - std::map<Uuid, RegisterCallback> pending_calls_; - - // Raw pointer to the Adapter that owns this factory. - Adapter& adapter_; -}; - -} // namespace bluetooth diff --git a/system/service/low_energy_scanner.cc b/system/service/low_energy_scanner.cc deleted file mode 100644 index 599fa181da..0000000000 --- a/system/service/low_energy_scanner.cc +++ /dev/null @@ -1,227 +0,0 @@ -// -// Copyright 2016 The Android Open Source Project -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/low_energy_scanner.h" - -#include <base/functional/bind.h> -#include <base/functional/callback.h> -#include <base/logging.h> - -#include "service/adapter.h" -#include "service/logging_helpers.h" -#include "stack/include/bt_types.h" -#include "types/raw_address.h" - -using std::lock_guard; -using std::mutex; - -namespace bluetooth { - -namespace { - -// 31 + 31 for advertising data and scan response. This is the maximum length -// TODO(armansito): Fix the HAL to return a concatenated blob that contains the -// true length of each field and also provide a length parameter so that we -// can support advertising length extensions in the future. -const size_t kScanRecordLength = 62; - -// Returns the length of the given scan record array. We have to calculate this -// based on the maximum possible data length and the TLV data. See TODO above -// |kScanRecordLength|. -size_t GetScanRecordLength(std::vector<uint8_t> bytes) { - for (size_t i = 0, field_len = 0; i < kScanRecordLength; - i += (field_len + 1)) { - field_len = bytes[i]; - - // Assert here that the data returned from the stack is correctly formatted - // in TLV form and that the length of the current field won't exceed the - // total data length. - CHECK(i + field_len < kScanRecordLength); - - // If the field length is zero and we haven't reached the maximum length, - // then we have found the length, as the stack will pad the data with zeros - // accordingly. - if (field_len == 0) return i; - } - - // We have reached the end. - return kScanRecordLength; -} - -} // namespace - -// LowEnergyScanner implementation - -LowEnergyScanner::LowEnergyScanner(Adapter& adapter, const Uuid& uuid, - int scanner_id) - : adapter_(adapter), - app_identifier_(uuid), - scanner_id_(scanner_id), - scan_started_(false), - delegate_(nullptr) {} - -LowEnergyScanner::~LowEnergyScanner() { - // Automatically unregister the scanner. - VLOG(1) << "LowEnergyScanner unregistering scanner: " << scanner_id_; - - // Unregister as observer so we no longer receive any callbacks. - hal::BluetoothGattInterface::Get()->RemoveScannerObserver(this); - - hal::BluetoothGattInterface::Get()->GetScannerHALInterface()->Unregister( - scanner_id_); - - // Stop any scans started by this client. - if (scan_started_.load()) StopScan(); -} - -void LowEnergyScanner::SetDelegate(Delegate* delegate) { - lock_guard<mutex> lock(delegate_mutex_); - delegate_ = delegate; -} - -bool LowEnergyScanner::StartScan(const ScanSettings& settings, - const std::vector<ScanFilter>& filters) { - VLOG(2) << __func__; - - // Cannot start a scan if the adapter is not enabled. - if (!adapter_.IsEnabled()) { - LOG(ERROR) << "Cannot scan while Bluetooth is disabled"; - return false; - } - - // TODO(jpawlowski): Push settings and filtering logic below the HAL. - bt_status_t status = - hal::BluetoothGattInterface::Get()->StartScan(scanner_id_); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to initiate scanning for client: " << scanner_id_; - return false; - } - - scan_started_ = true; - return true; -} - -bool LowEnergyScanner::StopScan() { - VLOG(2) << __func__; - - // TODO(armansito): We don't support batch scanning yet so call - // StopRegularScanForClient directly. In the future we will need to - // conditionally call a batch scan API here. - bt_status_t status = - hal::BluetoothGattInterface::Get()->StopScan(scanner_id_); - if (status != BT_STATUS_SUCCESS) { - LOG(ERROR) << "Failed to stop scan for client: " << scanner_id_; - return false; - } - - scan_started_ = false; - return true; -} - -const Uuid& LowEnergyScanner::GetAppIdentifier() const { - return app_identifier_; -} - -int LowEnergyScanner::GetInstanceId() const { return scanner_id_; } - -void LowEnergyScanner::ScanResultCallback( - hal::BluetoothGattInterface* gatt_iface, const RawAddress& bda, int rssi, - std::vector<uint8_t> adv_data) { - // Ignore scan results if this client didn't start a scan. - if (!scan_started_.load()) return; - - lock_guard<mutex> lock(delegate_mutex_); - if (!delegate_) return; - - // TODO(armansito): Apply software filters here. - - size_t record_len = GetScanRecordLength(adv_data); - std::vector<uint8_t> scan_record(adv_data.begin(), - adv_data.begin() + record_len); - - ScanResult result(BtAddrString(&bda), scan_record, rssi); - - delegate_->OnScanResult(this, result); -} - -// LowEnergyScannerFactory implementation - -LowEnergyScannerFactory::LowEnergyScannerFactory(Adapter& adapter) - : adapter_(adapter) { - hal::BluetoothGattInterface::Get()->AddScannerObserver(this); -} - -LowEnergyScannerFactory::~LowEnergyScannerFactory() { - hal::BluetoothGattInterface::Get()->RemoveScannerObserver(this); -} - -bool LowEnergyScannerFactory::RegisterInstance( - const Uuid& uuid, const RegisterCallback& callback) { - VLOG(1) << __func__ << " - Uuid: " << uuid.ToString(); - lock_guard<mutex> lock(pending_calls_lock_); - - if (pending_calls_.find(uuid) != pending_calls_.end()) { - LOG(ERROR) << "Low-Energy scanner with given Uuid already registered - " - << "Uuid: " << uuid.ToString(); - return false; - } - - BleScannerInterface* hal_iface = - hal::BluetoothGattInterface::Get()->GetScannerHALInterface(); - - Uuid uuid_empty = Uuid::kEmpty; - - hal_iface->RegisterScanner( - uuid_empty, base::Bind(&LowEnergyScannerFactory::RegisterScannerCallback, - base::Unretained(this), callback, uuid)); - - pending_calls_.insert(uuid); - - return true; -} - -void LowEnergyScannerFactory::RegisterScannerCallback( - const RegisterCallback& callback, const Uuid& app_uuid, uint8_t scanner_id, - uint8_t status) { - Uuid uuid(app_uuid); - - VLOG(1) << __func__ << " - Uuid: " << uuid.ToString(); - lock_guard<mutex> lock(pending_calls_lock_); - - auto iter = pending_calls_.find(uuid); - if (iter == pending_calls_.end()) { - VLOG(1) << "Ignoring callback for unknown app_id: " << uuid.ToString(); - return; - } - - // No need to construct a scanner if the call wasn't successful. - std::unique_ptr<LowEnergyScanner> scanner; - BLEStatus result = BLE_STATUS_FAILURE; - if (status == BT_STATUS_SUCCESS) { - scanner.reset(new LowEnergyScanner(adapter_, uuid, scanner_id)); - - hal::BluetoothGattInterface::Get()->AddScannerObserver(scanner.get()); - - result = BLE_STATUS_SUCCESS; - } - - // Notify the result via the result callback. - callback(result, app_uuid, std::move(scanner)); - - pending_calls_.erase(iter); -} - -} // namespace bluetooth diff --git a/system/service/low_energy_scanner.h b/system/service/low_energy_scanner.h deleted file mode 100644 index 627f287f83..0000000000 --- a/system/service/low_energy_scanner.h +++ /dev/null @@ -1,163 +0,0 @@ -// -// Copyright 2016 The Android Open Source Project -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <bluetooth/uuid.h> - -#include <atomic> -#include <functional> -#include <map> -#include <mutex> - -#include "service/bluetooth_instance.h" -#include "service/common/bluetooth/advertise_data.h" -#include "service/common/bluetooth/advertise_settings.h" -#include "service/common/bluetooth/low_energy_constants.h" -#include "service/common/bluetooth/scan_filter.h" -#include "service/common/bluetooth/scan_result.h" -#include "service/common/bluetooth/scan_settings.h" -#include "service/hal/bluetooth_gatt_interface.h" -#include "types/raw_address.h" - -namespace bluetooth { - -class Adapter; - -// A LowEnergyScanner represents an application's handle to perform various -// Bluetooth Low Energy GAP operations. Instances cannot be created directly and -// should be obtained through the factory. -class LowEnergyScanner : private hal::BluetoothGattInterface::ScannerObserver, - public BluetoothInstance { - public: - // The Delegate interface is used to notify asynchronous events related to LE - // scan. - class Delegate { - public: - Delegate() = default; - Delegate(const Delegate&) = delete; - Delegate& operator=(const Delegate&) = delete; - - virtual ~Delegate() = default; - - // Called asynchronously to notify the delegate of nearby BLE advertisers - // found during a device scan. - virtual void OnScanResult(LowEnergyScanner* client, - const ScanResult& scan_result) = 0; - }; - - LowEnergyScanner(const LowEnergyScanner&) = delete; - LowEnergyScanner& operator=(const LowEnergyScanner&) = delete; - - // The destructor automatically unregisters this client instance from the - // stack. - ~LowEnergyScanner() override; - - // Assigns a delegate to this instance. |delegate| must out-live this - // LowEnergyClient instance. - void SetDelegate(Delegate* delegate); - - // Initiates a BLE device scan for this client using the given |settings| and - // |filters|. See the documentation for ScanSettings and ScanFilter for how - // these parameters can be configured. Return true on success, false - // otherwise. Please see logs for details in case of error. - bool StartScan(const ScanSettings& settings, - const std::vector<ScanFilter>& filters); - - // Stops an ongoing BLE device scan for this client. - bool StopScan(); - - // Returns the current scan settings. - const ScanSettings& scan_settings() const { return scan_settings_; } - - // BluetoothInstace overrides: - const Uuid& GetAppIdentifier() const override; - int GetInstanceId() const override; - - void ScanResultCallback(hal::BluetoothGattInterface* gatt_iface, - const RawAddress& bda, int rssi, - std::vector<uint8_t> adv_data) override; - - private: - friend class LowEnergyScannerFactory; - - // Constructor shouldn't be called directly as instances are meant to be - // obtained from the factory. - LowEnergyScanner(Adapter& adapter, const Uuid& uuid, int scanner_id); - - // Calls and clears the pending callbacks. - void InvokeAndClearStartCallback(BLEStatus status); - void InvokeAndClearStopCallback(BLEStatus status); - - // Raw pointer to the Bluetooth Adapter. - Adapter& adapter_; - - // See getters above for documentation. - Uuid app_identifier_; - int scanner_id_; - - // Protects device scan related members below. - std::mutex scan_fields_lock_; - - // Current scan settings. - ScanSettings scan_settings_; - - // If true, then this client have a BLE device scan in progress. - std::atomic_bool scan_started_; - - // Raw handle to the Delegate, which must outlive this LowEnergyScanner - // instance. - std::mutex delegate_mutex_; - Delegate* delegate_; -}; - -// LowEnergyScannerFactory is used to register and obtain a per-application -// LowEnergyScanner instance. Users should call RegisterInstance to obtain their -// own unique LowEnergyScanner instance that has been registered with the -// Bluetooth stack. -class LowEnergyScannerFactory - : private hal::BluetoothGattInterface::ScannerObserver, - public BluetoothInstanceFactory { - public: - // Don't construct/destruct directly except in tests. Instead, obtain a handle - // from an Adapter instance. - explicit LowEnergyScannerFactory(Adapter& adapter); - LowEnergyScannerFactory(const LowEnergyScannerFactory&) = delete; - LowEnergyScannerFactory& operator=(const LowEnergyScannerFactory&) = delete; - - ~LowEnergyScannerFactory() override; - - // BluetoothInstanceFactory override: - bool RegisterInstance(const Uuid& app_uuid, - const RegisterCallback& callback) override; - - private: - friend class LowEnergyScanner; - - // BluetoothGattInterface::ScannerObserver overrides: - void RegisterScannerCallback(const RegisterCallback& callback, - const Uuid& app_uuid, uint8_t scanner_id, - uint8_t status); - - // Map of pending calls to register. - std::mutex pending_calls_lock_; - std::unordered_set<Uuid> pending_calls_; - - // Raw pointer to the Adapter that owns this factory. - Adapter& adapter_; -}; - -} // namespace bluetooth diff --git a/system/service/main.cc b/system/service/main.cc deleted file mode 100644 index 019098e9fc..0000000000 --- a/system/service/main.cc +++ /dev/null @@ -1,79 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include <base/at_exit.h> -#include <base/command_line.h> -#include <base/files/scoped_file.h> -#include <base/logging.h> - -#include "osi/include/properties.h" -#include "service/daemon.h" -#include "service/switches.h" - -namespace { - -// TODO(armansito): None of these should be hardcoded here. Instead, pass these -// via commandline. -const char kDisableProperty[] = "persist.bluetooth.disable"; - -} // namespace - -int main(int argc, char* argv[]) { - base::AtExitManager exit_manager; - base::CommandLine::Init(argc, argv); - - logging::LoggingSettings log_settings; - if (!logging::InitLogging(log_settings)) { - LOG(ERROR) << "Failed to set up logging"; - return EXIT_FAILURE; - } - - // TODO(armansito): Initialize base/logging. By default it will dump to stdout - // but we might want to change that based on a command-line switch. Figure out - // how to route the logging to Android's syslog. Once that's done, we won't - // need to use osi/include/log.h anymore. - - // TODO(armansito): Register exit-time clean-up handlers for the IPC sockets. - // Register signal handlers. - auto command_line = base::CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(bluetooth::switches::kHelpLong) || - command_line->HasSwitch(bluetooth::switches::kHelpShort)) { - LOG(INFO) << bluetooth::switches::kHelpMessage; - return EXIT_SUCCESS; - } - - // TODO(armansito): Remove Chromecast specific property out of here. This - // should just be obtained from global config. - char disable_value[PROPERTY_VALUE_MAX]; - int status = osi_property_get(kDisableProperty, disable_value, nullptr); - if (status && !strcmp(disable_value, "1")) { - LOG(INFO) << "service disabled"; - return EXIT_SUCCESS; - } - - if (!bluetooth::Daemon::Initialize()) { - LOG(ERROR) << "Failed to initialize Daemon"; - return EXIT_FAILURE; - } - - // Start the main event loop. - bluetooth::Daemon::Get()->StartMainLoop(); - - // The main message loop has exited; clean up the Daemon. - bluetooth::Daemon::Get()->ShutDown(); - - return EXIT_SUCCESS; -} diff --git a/system/service/settings.cc b/system/service/settings.cc deleted file mode 100644 index b3dc201431..0000000000 --- a/system/service/settings.cc +++ /dev/null @@ -1,97 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/settings.h" - -#include <base/command_line.h> -#include <base/logging.h> - -#include "service/switches.h" - -namespace bluetooth { - -namespace switches { -// Verbose switch that should be part of base_switches but doesn't seem to be -// exported as part of libbase. -const char kV[] = "v"; -}; // namespace switches - -Settings::Settings() : initialized_(false), enable_on_start_(false) {} - -Settings::~Settings() {} - -bool Settings::Init() { - CHECK(!initialized_); - auto command_line = base::CommandLine::ForCurrentProcess(); - const auto& switches = command_line->GetSwitches(); - - for (const auto& iter : switches) { - if (iter.first == switches::kCreateIPCSocketPath) { - // kCreateIPCSocketPath: An optional argument that initializes an IPC - // socket path for IPC. - base::FilePath path(iter.second); - if (path.empty() || path.EndsWithSeparator()) { - LOG(ERROR) << "Invalid IPC create socket path"; - return false; - } - - create_ipc_socket_path_ = path; - } else if (iter.first == switches::kAndroidIPCSocketSuffix) { - // kAndroidIPCSocketSuffix: An optional argument used to express - // a socket that Android init created for us. We bind to this. - const std::string& suffix = iter.second; - if (suffix.empty()) { - LOG(ERROR) << "Invalid Android socket suffix"; - return false; - } - - android_ipc_socket_suffix_ = suffix; - } else if (iter.first == switches::kEnableOnStart) { - if (iter.second == "true") { - enable_on_start_ = true; - } else if (iter.second == "false") { - enable_on_start_ = false; - } else { - LOG(ERROR) << "Invalid value for " << switches::kEnableOnStart << ": " - << iter.second << ". Expect 'true' or 'false'"; - return false; - } - } - // Check for libbase logging switches. These get processed by - // logging::InitLogging directly. - else if (iter.first != switches::kV) { - LOG(ERROR) << "Unexpected command-line switches found: " << iter.first; - return false; - } - } - - // Two IPC methods/paths were provided. - if (!android_ipc_socket_suffix_.empty() && !create_ipc_socket_path_.empty()) { - LOG(ERROR) << "Too many IPC methods provided"; - return false; - } - - // The daemon has no arguments - if (command_line->GetArgs().size()) { - LOG(ERROR) << "Unexpected command-line arguments found"; - return false; - } - - initialized_ = true; - return true; -} - -} // namespace bluetooth diff --git a/system/service/settings.h b/system/service/settings.h deleted file mode 100644 index 38e5ca98b2..0000000000 --- a/system/service/settings.h +++ /dev/null @@ -1,74 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <string> - -#include <base/files/file_path.h> - -namespace bluetooth { - -// The Settings class stores global runtime configurations, such as IPC domain -// namespace, configuration file locations, and other system properties and -// flags. -class Settings { - public: - // Constant for the "--help" command-line switches. - static const char kHelp[]; - - Settings(); - Settings(const Settings&) = delete; - Settings& operator=(const Settings&) = delete; - - ~Settings(); - - // TODO(armansito): Write an instance method for storing things into a file. - - // Initializes the Settings object. This reads the command-line options for - // the current process (which must have been initialized using - // base::CommandLine) and sets up the initial global settings. Returns false - // if there is an error, e.g. if the parameters/switches are malformed. - bool Init(); - - // If Android init created a server socket for the daemon, - // we can retrieve it through this suffix. - const std::string& android_ipc_socket_suffix() const { - return android_ipc_socket_suffix_; - } - - // Path to create a Unix domain socket server for Bluetooth IPC. - const base::FilePath& create_ipc_socket_path() const { - return create_ipc_socket_path_; - } - - // Returns true if domain-socket based IPC should be used. If false, then - // Binder IPC must be used. - inline bool UseSocketIPC() const { - return !android_ipc_socket_suffix().empty() || - !create_ipc_socket_path().empty(); - } - - bool EnableOnStart() const { return enable_on_start_; } - - private: - bool initialized_; - bool enable_on_start_; - std::string android_ipc_socket_suffix_; - base::FilePath create_ipc_socket_path_; -}; - -} // namespace bluetooth diff --git a/system/service/switches.h b/system/service/switches.h deleted file mode 100644 index aa1658c326..0000000000 --- a/system/service/switches.h +++ /dev/null @@ -1,45 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <string> - -namespace bluetooth { -namespace switches { - -// List of command-line switches used by the daemon. -const char kHelpLong[] = "help"; -const char kHelpShort[] = "h"; -const char kAndroidIPCSocketSuffix[] = "android-ipc-socket-suffix"; -const char kCreateIPCSocketPath[] = "create-ipc-socket"; -const char kEnableOnStart[] = "enable-on-start"; - -const char kHelpMessage[] = - "\nBluetooth System Service\n" - "\n" - "Usage:\n" - "\t--help,-h\t\t\tShow this help message\n" - "\t--android-ipc-socket-suffix\tSuffix of socket created by Android init. " - "Mutually exclusive with --create-ipc-socket.\n" - "\t--create-ipc-socket\t\tSocket path created for Unix domain socket based " - "IPC. Mutually exclusive with --android-ipc-socket-suffix.\n" - "\t--enable-on-start (true|false)\tIf true, enable adapter as soon as the " - "daemon starts.\n" - "\t--v\t\t\t\tLog verbosity level (e.g. -v=1)\n"; - -} // namespace switches -} // namespace bluetooth diff --git a/system/service/test/ParcelableTest.aidl b/system/service/test/ParcelableTest.aidl deleted file mode 100644 index b69aadfdd2..0000000000 --- a/system/service/test/ParcelableTest.aidl +++ /dev/null @@ -1,30 +0,0 @@ -package test; - -/* This file is just a test to make sure all parcelables - * are correct. It will be removed once they're used in - * real AIDL files. - */ - -import android.bluetooth.AdvertiseData; -import android.bluetooth.AdvertiseSettings; -import android.bluetooth.BluetoothGattCharacteristic; -import android.bluetooth.BluetoothGattDescriptor; -import android.bluetooth.BluetoothGattIncludedService; -import android.bluetooth.BluetoothGattService; -import android.bluetooth.ScanFilter; -import android.bluetooth.ScanResult; -import android.bluetooth.ScanSettings; -import android.bluetooth.UUID; - -interface ParcelableTest { - void OnAdvertiseData(in AdvertiseData advertise_data); - void OnAdvertiseSettings(in AdvertiseSettings advertise_settings); - void OnScanFilter(in ScanFilter scan_filter); - void OnScanResult(in ScanResult scan_result); - void OnScanSettings(in ScanSettings scan_settings); - void OnUUID(in UUID uuid); - void OnDescripor(in BluetoothGattDescriptor descriptor); - void OnCharacteristic(in BluetoothGattCharacteristic characteristic); - void OnIncludedService(in BluetoothGattIncludedService service); - void OnService(in BluetoothGattService service); -} diff --git a/system/service/test/a2dp_sink_unittest.cc b/system/service/test/a2dp_sink_unittest.cc deleted file mode 100644 index 69545c29c8..0000000000 --- a/system/service/test/a2dp_sink_unittest.cc +++ /dev/null @@ -1,273 +0,0 @@ -// -// Copyright 2017 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/a2dp_sink.h" - -#include <gmock/gmock.h> -#include <gtest/gtest.h> - -#include "service/hal/fake_bluetooth_av_interface.h" -#include "types/raw_address.h" - -using ::testing::_; -using ::testing::Return; - -namespace bluetooth { -namespace { - -class MockA2dpSinkHandler - : public hal::FakeBluetoothAvInterface::TestA2dpSinkHandler { - public: - MockA2dpSinkHandler() = default; - MockA2dpSinkHandler(const MockA2dpSinkHandler&) = delete; - MockA2dpSinkHandler& operator=(const MockA2dpSinkHandler&) = delete; - - ~MockA2dpSinkHandler() override = default; - - MOCK_METHOD1(Connect, bt_status_t(RawAddress)); - MOCK_METHOD1(Disconnect, bt_status_t(RawAddress)); - MOCK_METHOD1(SetAudioFocusState, void(int)); - MOCK_METHOD1(SetAudioTrackGain, void(float)); -}; - -class TestDelegate : public A2dpSink::Delegate { - public: - TestDelegate() = default; - ~TestDelegate() override = default; - - struct RequestData { - std::string device_address; - int state = -1; - uint32_t sample_rate = 0; - uint8_t channel_count = 0; - int count = 0; - }; - - // A2dpSink::Delegate implementation: - void OnConnectionState(const std::string& device_address, - int state) override { - ++connection_state_.count; - connection_state_.device_address = device_address; - connection_state_.state = state; - } - void OnAudioState(const std::string& device_address, int state) override { - ++audio_state_.count; - audio_state_.device_address = device_address; - audio_state_.state = state; - } - void OnAudioConfig(const std::string& device_address, uint32_t sample_rate, - uint8_t channel_count) override { - ++audio_config_.count; - audio_config_.device_address = device_address; - audio_config_.sample_rate = sample_rate; - audio_config_.channel_count = channel_count; - } - - const RequestData& connection_state() const { return connection_state_; } - const RequestData& audio_state() const { return audio_state_; } - const RequestData& audio_config() const { return audio_config_; } - - private: - RequestData connection_state_; - RequestData audio_state_; - RequestData audio_config_; -}; - -class A2dpSinkTest : public ::testing::Test { - public: - A2dpSinkTest() = default; - A2dpSinkTest(const A2dpSinkTest&) = delete; - A2dpSinkTest& operator=(const A2dpSinkTest&) = delete; - - ~A2dpSinkTest() override = default; - - void SetUp() override { - mock_handler_.reset(new MockA2dpSinkHandler()); - fake_hal_av_iface_ = new hal::FakeBluetoothAvInterface(mock_handler_); - hal::BluetoothAvInterface::InitializeForTesting(fake_hal_av_iface_); - factory_.reset(new A2dpSinkFactory()); - } - - void TearDown() override { - factory_.reset(); - hal::BluetoothAvInterface::CleanUp(); - } - - protected: - hal::FakeBluetoothAvInterface* fake_hal_av_iface_; - std::shared_ptr<MockA2dpSinkHandler> mock_handler_; - std::unique_ptr<A2dpSinkFactory> factory_; -}; - -class A2dpSinkPostRegisterTest : public A2dpSinkTest { - public: - A2dpSinkPostRegisterTest() = default; - A2dpSinkPostRegisterTest(const A2dpSinkPostRegisterTest&) = delete; - A2dpSinkPostRegisterTest& operator=(const A2dpSinkPostRegisterTest&) = delete; - - ~A2dpSinkPostRegisterTest() override = default; - - void SetUp() override { - A2dpSinkTest::SetUp(); - Uuid uuid = Uuid::GetRandom(); - auto callback = [&](BLEStatus status, const Uuid& in_uuid, - std::unique_ptr<BluetoothInstance> in_client) { - CHECK(in_uuid == uuid); - CHECK(in_client.get()); - CHECK(status == BLE_STATUS_SUCCESS); - - a2dp_sink_ = std::unique_ptr<A2dpSink>( - static_cast<A2dpSink*>(in_client.release())); - }; - - factory_->RegisterInstance(uuid, callback); - } - - void TearDown() override { - a2dp_sink_ = nullptr; - A2dpSinkTest::TearDown(); - } - - protected: - void Connect(const std::string& addr) { - RawAddress hal_addr; - ASSERT_TRUE(RawAddress::FromString(addr, hal_addr)); - - EXPECT_CALL(*mock_handler_, Connect(hal_addr)) - .WillOnce(Return(BT_STATUS_SUCCESS)); - - EXPECT_TRUE(a2dp_sink_->Connect(addr)); - } - - void Disconnect(const std::string& addr) { - RawAddress hal_addr; - ASSERT_TRUE(RawAddress::FromString(addr, hal_addr)); - - EXPECT_CALL(*mock_handler_, Disconnect(hal_addr)) - .WillOnce(Return(BT_STATUS_SUCCESS)); - - EXPECT_TRUE(a2dp_sink_->Disconnect(addr)); - } - - std::unique_ptr<A2dpSink> a2dp_sink_; -}; - -TEST_F(A2dpSinkTest, RegisterA2dpSink) { - // These will be asynchronously populate with a result when the callback - // executes. - BLEStatus status = BLE_STATUS_SUCCESS; - Uuid cb_uuid; - std::unique_ptr<A2dpSink> a2dp_sink; - int callback_count = 0; - - auto callback = [&](BLEStatus in_status, const Uuid& uuid, - std::unique_ptr<BluetoothInstance> in_a2dp_sink) { - status = in_status; - cb_uuid = uuid; - a2dp_sink = std::unique_ptr<A2dpSink>( - static_cast<A2dpSink*>(in_a2dp_sink.release())); - callback_count++; - }; - - Uuid uuid0 = Uuid::GetRandom(); - - // This should always succeed. - EXPECT_TRUE(factory_->RegisterInstance(uuid0, callback)); - EXPECT_EQ(1, callback_count); - - testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - ASSERT_TRUE(a2dp_sink.get() != - nullptr); // Assert to terminate in case of error - EXPECT_EQ(BLE_STATUS_SUCCESS, status); - EXPECT_EQ(bluetooth::A2dpSink::kSingletonInstanceId, - a2dp_sink->GetInstanceId()); - EXPECT_EQ(uuid0, a2dp_sink->GetAppIdentifier()); - EXPECT_EQ(uuid0, cb_uuid); - - testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); -} - -TEST_F(A2dpSinkPostRegisterTest, Connect) { - static const char kTestAddr[] = "AA:BB:CC:DD:EE:FF"; - Connect(kTestAddr); - Disconnect(kTestAddr); -} - -TEST_F(A2dpSinkPostRegisterTest, SetAudioFocusState) { - static const char kTestAddr[] = "AA:BB:CC:DD:EE:FF"; - static const int kFocusState = 2; - Connect(kTestAddr); - - EXPECT_CALL(*mock_handler_, SetAudioFocusState(kFocusState)); - a2dp_sink_->SetAudioFocusState(kFocusState); - - Disconnect(kTestAddr); -} - -TEST_F(A2dpSinkPostRegisterTest, SetAudioTrackGain) { - static const char kTestAddr[] = "AA:BB:CC:DD:EE:FF"; - static const float kTrackGain = 0.5; - Connect(kTestAddr); - - EXPECT_CALL(*mock_handler_, SetAudioTrackGain(kTrackGain)); - a2dp_sink_->SetAudioTrackGain(kTrackGain); - - Disconnect(kTestAddr); -} - -TEST_F(A2dpSinkPostRegisterTest, CallbackTest) { - static const char kTestAddr[] = "AA:BB:CC:DD:EE:FF"; - RawAddress hal_addr; - ASSERT_TRUE(RawAddress::FromString(kTestAddr, hal_addr)); - - TestDelegate delegate; - a2dp_sink_->SetDelegate(&delegate); - Connect(kTestAddr); - - // OnConnectionState - const int kConnectionState = 2; - EXPECT_EQ(0, delegate.connection_state().count); - fake_hal_av_iface_->NotifyConnectionState( - hal_addr, static_cast<btav_connection_state_t>(kConnectionState)); - EXPECT_EQ(1, delegate.connection_state().count); - EXPECT_EQ(kTestAddr, delegate.connection_state().device_address); - EXPECT_EQ(kConnectionState, delegate.connection_state().state); - - // OnAudioState - const int kAudioState = 1; - EXPECT_EQ(0, delegate.audio_state().count); - fake_hal_av_iface_->NotifyAudioState( - hal_addr, static_cast<btav_audio_state_t>(kAudioState)); - EXPECT_EQ(1, delegate.audio_state().count); - EXPECT_EQ(kTestAddr, delegate.audio_state().device_address); - EXPECT_EQ(kAudioState, delegate.audio_state().state); - - // OnAudioConfig - const uint32_t kSampleRate = 44100; - const uint32_t kChannelCount = 2; - EXPECT_EQ(0, delegate.audio_config().count); - fake_hal_av_iface_->NotifyAudioConfig(hal_addr, kSampleRate, kChannelCount); - EXPECT_EQ(1, delegate.audio_config().count); - EXPECT_EQ(kTestAddr, delegate.audio_config().device_address); - EXPECT_EQ(kSampleRate, delegate.audio_config().sample_rate); - EXPECT_EQ(kChannelCount, delegate.audio_config().channel_count); - - Disconnect(kTestAddr); -} - -} // namespace -} // namespace bluetooth diff --git a/system/service/test/a2dp_source_unittest.cc b/system/service/test/a2dp_source_unittest.cc deleted file mode 100644 index b29172754c..0000000000 --- a/system/service/test/a2dp_source_unittest.cc +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "service/a2dp_source.h" - -#include <gmock/gmock.h> -#include <gtest/gtest.h> - -#include "service/hal/fake_bluetooth_av_interface.h" -#include "types/raw_address.h" - -using ::testing::_; -using ::testing::Return; - -namespace bluetooth { -namespace { - -class MockA2dpSourceHandler - : public hal::FakeBluetoothAvInterface::TestA2dpSourceHandler { - public: - MockA2dpSourceHandler() = default; - MockA2dpSourceHandler(const MockA2dpSourceHandler&) = delete; - MockA2dpSourceHandler& operator=(const MockA2dpSourceHandler&) = delete; - - ~MockA2dpSourceHandler() override = default; - - MOCK_METHOD1(Connect, bt_status_t(RawAddress)); - MOCK_METHOD1(Disconnect, bt_status_t(RawAddress)); -}; - -class TestDelegate : public A2dpSource::Delegate { - public: - TestDelegate() = default; - ~TestDelegate() override = default; - - struct RequestData { - std::string device_address; - int state = -1; - int count = 0; - }; - - // A2dpSource::Delegate implementation: - void OnConnectionState(const std::string& device_address, - int state) override { - ++connection_state_.count; - connection_state_.device_address = device_address; - connection_state_.state = state; - } - void OnAudioState(const std::string& device_address, int state) override { - ++audio_state_.count; - audio_state_.device_address = device_address; - audio_state_.state = state; - } - void OnAudioConfig( - const std::string& device_address, A2dpCodecConfig codec_config, - const std::vector<A2dpCodecConfig>& codecs_local_capabilities, - const std::vector<A2dpCodecConfig>& codecs_selectable_capabilities) - override { - ++audio_config_.count; - audio_config_.device_address = device_address; - } - - const RequestData& connection_state() const { return connection_state_; } - const RequestData& audio_state() const { return audio_state_; } - const RequestData& audio_config() const { return audio_config_; } - - private: - RequestData connection_state_; - RequestData audio_state_; - RequestData audio_config_; -}; - -class A2dpSourceTest : public ::testing::Test { - public: - A2dpSourceTest() = default; - A2dpSourceTest(const A2dpSourceTest&) = delete; - A2dpSourceTest& operator=(const A2dpSourceTest&) = delete; - - ~A2dpSourceTest() override = default; - - void SetUp() override { - mock_handler_.reset(new MockA2dpSourceHandler()); - fake_hal_av_iface_ = new hal::FakeBluetoothAvInterface(mock_handler_); - hal::BluetoothAvInterface::InitializeForTesting(fake_hal_av_iface_); - factory_.reset(new A2dpSourceFactory()); - } - - void TearDown() override { - factory_.reset(); - hal::BluetoothAvInterface::CleanUp(); - } - - protected: - hal::FakeBluetoothAvInterface* fake_hal_av_iface_; - std::shared_ptr<MockA2dpSourceHandler> mock_handler_; - std::unique_ptr<A2dpSourceFactory> factory_; -}; - -class A2dpSourcePostRegisterTest : public A2dpSourceTest { - public: - A2dpSourcePostRegisterTest() = default; - A2dpSourcePostRegisterTest(const A2dpSourcePostRegisterTest&) = delete; - A2dpSourcePostRegisterTest& operator=(const A2dpSourcePostRegisterTest&) = - delete; - - ~A2dpSourcePostRegisterTest() override = default; - - void SetUp() override { - A2dpSourceTest::SetUp(); - Uuid uuid = Uuid::GetRandom(); - auto callback = [&](BLEStatus status, const Uuid& in_uuid, - std::unique_ptr<BluetoothInstance> in_client) { - CHECK(in_uuid == uuid); - CHECK(in_client.get()); - CHECK(status == BLE_STATUS_SUCCESS); - - a2dp_source_ = std::unique_ptr<A2dpSource>( - static_cast<A2dpSource*>(in_client.release())); - }; - - factory_->RegisterInstance(uuid, callback); - } - - void TearDown() override { - a2dp_source_ = nullptr; - A2dpSourceTest::TearDown(); - } - - protected: - void Connect(const std::string& addr) { - RawAddress hal_addr; - ASSERT_TRUE(RawAddress::FromString(addr, hal_addr)); - - EXPECT_CALL(*mock_handler_, Connect(hal_addr)) - .WillOnce(Return(BT_STATUS_SUCCESS)); - - EXPECT_TRUE(a2dp_source_->Connect(addr)); - } - - void Disconnect(const std::string& addr) { - RawAddress hal_addr; - ASSERT_TRUE(RawAddress::FromString(addr, hal_addr)); - - EXPECT_CALL(*mock_handler_, Disconnect(hal_addr)) - .WillOnce(Return(BT_STATUS_SUCCESS)); - - EXPECT_TRUE(a2dp_source_->Disconnect(addr)); - } - - std::unique_ptr<A2dpSource> a2dp_source_; -}; - -TEST_F(A2dpSourceTest, RegisterA2dpSource) { - // These will be asynchronously populate with a result when the callback - // executes. - BLEStatus status = BLE_STATUS_SUCCESS; - Uuid cb_uuid; - std::unique_ptr<A2dpSource> a2dp_source; - int callback_count = 0; - - auto callback = [&](BLEStatus in_status, const Uuid& uuid, - std::unique_ptr<BluetoothInstance> in_a2dp_source) { - status = in_status; - cb_uuid = uuid; - a2dp_source = std::unique_ptr<A2dpSource>( - static_cast<A2dpSource*>(in_a2dp_source.release())); - callback_count++; - }; - - Uuid uuid0 = Uuid::GetRandom(); - - // This should always succeed. - EXPECT_TRUE(factory_->RegisterInstance(uuid0, callback)); - EXPECT_EQ(1, callback_count); - - testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - ASSERT_TRUE(a2dp_source.get() != - nullptr); // Assert to terminate in case of error - EXPECT_EQ(BLE_STATUS_SUCCESS, status); - EXPECT_EQ(bluetooth::A2dpSource::kSingletonInstanceId, - a2dp_source->GetInstanceId()); - EXPECT_EQ(uuid0, a2dp_source->GetAppIdentifier()); - EXPECT_EQ(uuid0, cb_uuid); - - testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); -} - -TEST_F(A2dpSourcePostRegisterTest, Connect) { - static const char kTestAddr[] = "AA:BB:CC:DD:EE:FF"; - Connect(kTestAddr); - Disconnect(kTestAddr); -} - -TEST_F(A2dpSourcePostRegisterTest, CallbackTest) { - static const char kTestAddr[] = "AA:BB:CC:DD:EE:FF"; - RawAddress hal_addr; - ASSERT_TRUE(RawAddress::FromString(kTestAddr, hal_addr)); - - TestDelegate delegate; - a2dp_source_->SetDelegate(&delegate); - Connect(kTestAddr); - - // OnConnectionState - const int kConnectionState = 2; - EXPECT_EQ(0, delegate.connection_state().count); - fake_hal_av_iface_->NotifyConnectionState( - hal_addr, static_cast<btav_connection_state_t>(kConnectionState)); - EXPECT_EQ(1, delegate.connection_state().count); - EXPECT_EQ(kTestAddr, delegate.connection_state().device_address); - EXPECT_EQ(kConnectionState, delegate.connection_state().state); - - // OnAudioState - const int kAudioState = 1; - EXPECT_EQ(0, delegate.audio_state().count); - fake_hal_av_iface_->NotifyAudioState( - hal_addr, static_cast<btav_audio_state_t>(kAudioState)); - EXPECT_EQ(1, delegate.audio_state().count); - EXPECT_EQ(kTestAddr, delegate.audio_state().device_address); - EXPECT_EQ(kAudioState, delegate.audio_state().state); - - // OnAudioConfig - const btav_a2dp_codec_config_t codec_config{}; - const std::vector<btav_a2dp_codec_config_t> codecs_local_capabilities(0); - const std::vector<btav_a2dp_codec_config_t> codecs_selectable_capabilities(0); - EXPECT_EQ(0, delegate.audio_config().count); - fake_hal_av_iface_->NotifyAudioConfig(hal_addr, codec_config, - codecs_local_capabilities, - codecs_selectable_capabilities); - EXPECT_EQ(1, delegate.audio_config().count); - EXPECT_EQ(kTestAddr, delegate.audio_config().device_address); - - fake_hal_av_iface_->QueryMandatoryCodecPreferred(hal_addr); - - Disconnect(kTestAddr); -} - -} // namespace -} // namespace bluetooth diff --git a/system/service/test/adapter_unittest.cc b/system/service/test/adapter_unittest.cc deleted file mode 100644 index fb6a9a2263..0000000000 --- a/system/service/test/adapter_unittest.cc +++ /dev/null @@ -1,289 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/adapter.h" - -#include <gtest/gtest.h> - -#include "service/hal/fake_bluetooth_gatt_interface.h" -#include "service/hal/fake_bluetooth_interface.h" -#include "types/bt_transport.h" -#include "types/raw_address.h" - -namespace bluetooth { -namespace { - -class AdapterTest : public ::testing::Test { - public: - AdapterTest() = default; - AdapterTest(const AdapterTest&) = delete; - AdapterTest& operator=(const AdapterTest&) = delete; - - ~AdapterTest() override = default; - - void SetUp() override { - fake_hal_manager_ = hal::FakeBluetoothInterface::GetManager(); - fake_hal_iface_ = new hal::FakeBluetoothInterface(); - hal::BluetoothInterface::InitializeForTesting(fake_hal_iface_); - - // Initialize GATT interface with default handlers. - hal::BluetoothGattInterface::InitializeForTesting( - new hal::FakeBluetoothGattInterface(nullptr, nullptr, nullptr, - nullptr)); - - adapter_ = Adapter::Create(); - } - - void TearDown() override { - adapter_.reset(); - hal::BluetoothGattInterface::CleanUp(); - hal::BluetoothInterface::CleanUp(); - } - - protected: - hal::FakeBluetoothInterface* fake_hal_iface_; - hal::FakeBluetoothInterface::Manager* fake_hal_manager_; - std::unique_ptr<Adapter> adapter_; -}; - -class TestObserver final : public bluetooth::Adapter::Observer { - public: - explicit TestObserver(bluetooth::Adapter* adapter) - : adapter_(adapter), - prev_state_(bluetooth::ADAPTER_STATE_INVALID), - cur_state_(bluetooth::ADAPTER_STATE_INVALID), - last_device_connected_state_(false) { - CHECK(adapter_); - adapter_->AddObserver(this); - } - - TestObserver(const TestObserver&) = delete; - TestObserver& operator=(const TestObserver&) = delete; - - ~TestObserver() override { adapter_->RemoveObserver(this); } - - bluetooth::AdapterState prev_state() const { return prev_state_; } - bluetooth::AdapterState cur_state() const { return cur_state_; } - - std::string last_connection_state_address() const { - return last_connection_state_address_; - } - - bool last_device_connected_state() const { - return last_device_connected_state_; - } - - // bluetooth::Adapter::Observer override: - void OnAdapterStateChanged(bluetooth::Adapter* adapter, - bluetooth::AdapterState prev_state, - bluetooth::AdapterState new_state) override { - ASSERT_EQ(adapter_, adapter); - prev_state_ = prev_state; - cur_state_ = new_state; - } - - void OnDeviceConnectionStateChanged(Adapter* adapter, - const std::string& device_address, - bool connected) override { - ASSERT_EQ(adapter_, adapter); - last_connection_state_address_ = device_address; - last_device_connected_state_ = connected; - } - - private: - bluetooth::Adapter* adapter_; - bluetooth::AdapterState prev_state_, cur_state_; - std::string last_connection_state_address_; - bool last_device_connected_state_; -}; - -TEST_F(AdapterTest, IsEnabled) { - EXPECT_FALSE(adapter_->IsEnabled()); - - fake_hal_iface_->NotifyAdapterStateChanged(BT_STATE_ON); - EXPECT_TRUE(adapter_->IsEnabled()); - - fake_hal_iface_->NotifyAdapterStateChanged(BT_STATE_OFF); - EXPECT_FALSE(adapter_->IsEnabled()); -} - -TEST_F(AdapterTest, Enable) { - TestObserver observer(adapter_.get()); - - EXPECT_FALSE(adapter_->IsEnabled()); - EXPECT_EQ(bluetooth::ADAPTER_STATE_OFF, adapter_->GetState()); - - // Enable fails at HAL level - EXPECT_FALSE(adapter_->Enable()); - EXPECT_EQ(bluetooth::ADAPTER_STATE_OFF, adapter_->GetState()); - - // Enable success - fake_hal_manager_->enable_succeed = true; - EXPECT_TRUE(adapter_->Enable()); - - // Should have received a state update. - EXPECT_EQ(bluetooth::ADAPTER_STATE_OFF, observer.prev_state()); - EXPECT_EQ(bluetooth::ADAPTER_STATE_TURNING_ON, observer.cur_state()); - - // Enable fails because not disabled - EXPECT_EQ(bluetooth::ADAPTER_STATE_TURNING_ON, adapter_->GetState()); - EXPECT_FALSE(adapter_->Enable()); - - // Adapter state updates properly - fake_hal_iface_->NotifyAdapterStateChanged(BT_STATE_ON); - EXPECT_EQ(bluetooth::ADAPTER_STATE_ON, adapter_->GetState()); - - // Should have received a state update. - EXPECT_EQ(bluetooth::ADAPTER_STATE_TURNING_ON, observer.prev_state()); - EXPECT_EQ(bluetooth::ADAPTER_STATE_ON, observer.cur_state()); - - // Enable fails because already enabled - EXPECT_FALSE(adapter_->Enable()); -} - -TEST_F(AdapterTest, Disable) { - TestObserver observer(adapter_.get()); - - fake_hal_manager_->disable_succeed = true; - EXPECT_FALSE(adapter_->IsEnabled()); - EXPECT_EQ(bluetooth::ADAPTER_STATE_OFF, adapter_->GetState()); - - // Disable fails because already disabled - EXPECT_FALSE(adapter_->Disable()); - EXPECT_EQ(bluetooth::ADAPTER_STATE_OFF, adapter_->GetState()); - - // Disable success - fake_hal_iface_->NotifyAdapterStateChanged(BT_STATE_ON); - - // Should have received a state update. - EXPECT_EQ(bluetooth::ADAPTER_STATE_OFF, observer.prev_state()); - EXPECT_EQ(bluetooth::ADAPTER_STATE_ON, observer.cur_state()); - - EXPECT_TRUE(adapter_->Disable()); - - // Should have received a state update. - EXPECT_EQ(bluetooth::ADAPTER_STATE_ON, observer.prev_state()); - EXPECT_EQ(bluetooth::ADAPTER_STATE_TURNING_OFF, observer.cur_state()); - - // Disable fails because not enabled - EXPECT_EQ(bluetooth::ADAPTER_STATE_TURNING_OFF, adapter_->GetState()); - EXPECT_FALSE(adapter_->Disable()); - - fake_hal_iface_->NotifyAdapterStateChanged(BT_STATE_ON); - EXPECT_EQ(bluetooth::ADAPTER_STATE_ON, adapter_->GetState()); - - // Should have received a state update. - EXPECT_EQ(bluetooth::ADAPTER_STATE_TURNING_OFF, observer.prev_state()); - EXPECT_EQ(bluetooth::ADAPTER_STATE_ON, observer.cur_state()); - - // Disable fails at HAL level - fake_hal_manager_->disable_succeed = false; - EXPECT_FALSE(adapter_->Disable()); - - // Should have received a state update. In this case we will receive two - // updates: one going from OFF to TURNING_OFF, and one going from TURNING_OFF - // back to ON since we failed to initiate the disable operation. - EXPECT_EQ(bluetooth::ADAPTER_STATE_TURNING_OFF, observer.prev_state()); - EXPECT_EQ(bluetooth::ADAPTER_STATE_ON, observer.cur_state()); - - // Update state to OFF. Should receive a state update. - fake_hal_iface_->NotifyAdapterStateChanged(BT_STATE_OFF); - EXPECT_EQ(bluetooth::ADAPTER_STATE_ON, observer.prev_state()); - EXPECT_EQ(bluetooth::ADAPTER_STATE_OFF, observer.cur_state()); -} - -TEST_F(AdapterTest, GetName) { - EXPECT_EQ(bluetooth::Adapter::kDefaultName, adapter_->GetName()); - - const char kTestAdapterName[] = "Test Adapter Name"; - - fake_hal_iface_->NotifyAdapterNamePropertyChanged(kTestAdapterName); - EXPECT_EQ(kTestAdapterName, adapter_->GetName()); -} - -TEST_F(AdapterTest, SetName) { - bt_bdname_t hal_name; - - // Name too large. - EXPECT_FALSE(adapter_->SetName(std::string(sizeof(hal_name.name), 'a'))); - - // Valid length. - EXPECT_FALSE(adapter_->SetName("Test Name")); - fake_hal_manager_->set_property_succeed = true; - EXPECT_TRUE(adapter_->SetName("Test Name")); -} - -TEST_F(AdapterTest, GetAddress) { - EXPECT_EQ(bluetooth::Adapter::kDefaultAddress, adapter_->GetAddress()); - - const RawAddress kTestAdapterInput = {{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc}}; - const char kTestAdapterAddressOutput[] = "12:34:56:78:9A:BC"; - - fake_hal_iface_->NotifyAdapterAddressPropertyChanged(&kTestAdapterInput); - EXPECT_EQ(kTestAdapterAddressOutput, adapter_->GetAddress()); -} - -TEST_F(AdapterTest, IsMultiAdvertisementSupported) { - EXPECT_FALSE(adapter_->IsMultiAdvertisementSupported()); - - bt_local_le_features_t features; - memset(&features, 0, sizeof(features)); - - features.max_adv_instance = 10; // Some high number. - fake_hal_iface_->NotifyAdapterLocalLeFeaturesPropertyChanged(&features); - EXPECT_TRUE(adapter_->IsMultiAdvertisementSupported()); - - features.max_adv_instance = 0; // Low number. - fake_hal_iface_->NotifyAdapterLocalLeFeaturesPropertyChanged(&features); - EXPECT_FALSE(adapter_->IsMultiAdvertisementSupported()); -} - -TEST_F(AdapterTest, IsDeviceConnected) { - const char kDeviceAddr[] = "12:34:56:78:9A:BC"; - TestObserver observer(adapter_.get()); - - EXPECT_FALSE(adapter_->IsDeviceConnected(kDeviceAddr)); - - RawAddress hal_addr; - ASSERT_TRUE(RawAddress::FromString(kDeviceAddr, hal_addr)); - - // status != BT_STATUS_SUCCESS should be ignored - fake_hal_iface_->NotifyAclStateChangedCallback( - BT_STATUS_FAIL, hal_addr, BT_ACL_STATE_CONNECTED, BT_TRANSPORT_LE, 0xff, - BT_CONN_DIRECTION_OUTGOING, 1); // HCI_ERR_UNDEFINED - EXPECT_FALSE(adapter_->IsDeviceConnected(kDeviceAddr)); - EXPECT_TRUE(observer.last_connection_state_address().empty()); - EXPECT_FALSE(observer.last_device_connected_state()); - - // Connected - fake_hal_iface_->NotifyAclStateChangedCallback( - BT_STATUS_SUCCESS, hal_addr, BT_ACL_STATE_CONNECTED, BT_TRANSPORT_LE, - 0x00, BT_CONN_DIRECTION_OUTGOING, 1); // HCI_SUCCESS - EXPECT_TRUE(adapter_->IsDeviceConnected(kDeviceAddr)); - EXPECT_EQ(kDeviceAddr, observer.last_connection_state_address()); - EXPECT_TRUE(observer.last_device_connected_state()); - - // Disconnected - fake_hal_iface_->NotifyAclStateChangedCallback( - BT_STATUS_SUCCESS, hal_addr, BT_ACL_STATE_DISCONNECTED, BT_TRANSPORT_LE, - 0x16, BT_CONN_DIRECTION_OUTGOING, 1); // HCI_ERR_CONN_CAUSE_LOCAL_HOST - EXPECT_FALSE(adapter_->IsDeviceConnected(kDeviceAddr)); - EXPECT_EQ(kDeviceAddr, observer.last_connection_state_address()); - EXPECT_FALSE(observer.last_device_connected_state()); -} - -} // namespace -} // namespace bluetooth diff --git a/system/service/test/advertise_data_unittest.cc b/system/service/test/advertise_data_unittest.cc deleted file mode 100644 index a481c8ce33..0000000000 --- a/system/service/test/advertise_data_unittest.cc +++ /dev/null @@ -1,112 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include <gtest/gtest.h> - -#include "service/common/bluetooth/advertise_data.h" -#include "stack/include/bt_types.h" -#include "stack/include/hcidefs.h" - -namespace bluetooth { - -TEST(AdvertiseDataTest, EmptyData) { - const std::vector<uint8_t> data0; - AdvertiseData adv0(data0); - EXPECT_TRUE(adv0.IsValid()); - - // Single empty field not allowed. - const std::vector<uint8_t> data1{0x00}; - AdvertiseData adv1(data1); - EXPECT_FALSE(adv1.IsValid()); -} - -TEST(AdvertiseDataTest, BadTLV) { - // Single field, field empty. - const std::vector<uint8_t> data0{0x01}; - AdvertiseData adv0(data0); - EXPECT_FALSE(adv0.IsValid()); - - // Single field, first field length too long. - const std::vector<uint8_t> data1{0x05, 0x02, 0x00, 0x00, 0x00}; - AdvertiseData adv1(data1); - EXPECT_FALSE(adv1.IsValid()); - - // Two fields, second field length too long. - const std::vector<uint8_t> data2{0x02, 0x02, 0x00, 0x02, 0x00}; - AdvertiseData adv2(data2); - EXPECT_FALSE(adv2.IsValid()); - - // Two fields, second field empty. - const std::vector<uint8_t> data3{0x02, 0x02, 0x00, 0x01}; - AdvertiseData adv3(data3); - EXPECT_FALSE(adv3.IsValid()); -} - -TEST(AdvertiseDataTest, GoodTLV) { - // Singe field. - const std::vector<uint8_t> data0{0x03, 0x02, 0x01, 0x02}; - AdvertiseData adv0(data0); - EXPECT_TRUE(adv0.IsValid()); - - // Twi fields. - const std::vector<uint8_t> data1{0x03, 0x02, 0x01, 0x02, 0x02, 0x03, 0x01}; - AdvertiseData adv1(data1); - EXPECT_TRUE(adv0.IsValid()); -} - -TEST(AdvertiseDataTest, DisallowedFields) { - // Singe field. - const std::vector<uint8_t> data0{0x02, HCI_EIR_FLAGS_TYPE, 0x00}; - AdvertiseData adv0(data0); - EXPECT_FALSE(adv0.IsValid()); - - // Two fields, first invalid. - const std::vector<uint8_t> data1{ - 0x02, HCI_EIR_FLAGS_TYPE, 0x00, 0x03, 0x02, 0x01, 0x02}; - AdvertiseData adv1(data1); - EXPECT_FALSE(adv1.IsValid()); - - // Two fields, second invalid. - const std::vector<uint8_t> data2{ - 0x03, 0x02, 0x01, 0x02, 0x02, HCI_EIR_FLAGS_TYPE, 0x00}; - AdvertiseData adv2(data2); - EXPECT_FALSE(adv2.IsValid()); - - // Check all rejectlisted fields - uint8_t rejectlist[] = {HCI_EIR_FLAGS_TYPE, HCI_EIR_OOB_BD_ADDR_TYPE, - HCI_EIR_OOB_COD_TYPE, HCI_EIR_OOB_SSP_HASH_C_TYPE, - HCI_EIR_OOB_SSP_RAND_R_TYPE}; - for (size_t i = 0; i < sizeof(rejectlist); i++) { - const std::vector<uint8_t> data{0x02, rejectlist[i], 0x00}; - AdvertiseData adv(data); - EXPECT_FALSE(adv.IsValid()); - } -} - -TEST(AdvertiseDataTest, EqualsData) { - const std::vector<uint8_t> data0{0x02, 0x02, 0x00}; - const std::vector<uint8_t> data1{0x02, 0x03, 0x00}; - - AdvertiseData adv0(data0); - AdvertiseData adv1(data1); - - EXPECT_FALSE(adv0 == adv1); - - AdvertiseData adv2(data1); - EXPECT_TRUE(adv1 == adv2); -} - -} // namespace bluetooth diff --git a/system/service/test/fake_hal_util.cc b/system/service/test/fake_hal_util.cc deleted file mode 100644 index 263be64b70..0000000000 --- a/system/service/test/fake_hal_util.cc +++ /dev/null @@ -1,25 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "btcore/include/hal_util.h" - -// TODO(armansito): This provides a fake implementation of the function defined -// in btcore/include/hal_util.h. We have to provide this to prevent having to -// pull in libbtcore and transitively libhardware as dependencies for the unit -// tests. Instead of doing it this way, however, we should instead provide a C++ -// class abstraction for this (and all other btif interfaces) that we can mock -// for testing. -int hal_util_load_bt_library(const bt_interface_t** interface) { return -1; } diff --git a/system/service/test/gatt_client_unittest.cc b/system/service/test/gatt_client_unittest.cc deleted file mode 100644 index c7c02091a8..0000000000 --- a/system/service/test/gatt_client_unittest.cc +++ /dev/null @@ -1,162 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/gatt_client.h" - -#include <gmock/gmock.h> -#include <gtest/gtest.h> - -#include "service/hal/fake_bluetooth_gatt_interface.h" -#include "types/raw_address.h" - -using ::testing::_; -using ::testing::Return; - -namespace bluetooth { -namespace { - -class MockGattHandler - : public hal::FakeBluetoothGattInterface::TestClientHandler { - public: - MockGattHandler() = default; - MockGattHandler(const MockGattHandler&) = delete; - MockGattHandler& operator=(const MockGattHandler&) = delete; - - ~MockGattHandler() override = default; - - MOCK_METHOD2(RegisterClient, - bt_status_t(const bluetooth::Uuid&, bool eatt_support)); - MOCK_METHOD1(UnregisterClient, bt_status_t(int)); - MOCK_METHOD1(Scan, bt_status_t(bool)); - MOCK_METHOD4(Connect, bt_status_t(int, const RawAddress&, bool, int)); - MOCK_METHOD3(Disconnect, bt_status_t(int, const RawAddress&, int)); -}; - -class GattClientTest : public ::testing::Test { - public: - GattClientTest() = default; - GattClientTest(const GattClientTest&) = delete; - GattClientTest& operator=(const GattClientTest&) = delete; - - ~GattClientTest() override = default; - - void SetUp() override { - // Only set |mock_handler_| if a previous test case hasn't set it. - if (!mock_handler_) mock_handler_.reset(new MockGattHandler()); - - fake_hal_gatt_iface_ = new hal::FakeBluetoothGattInterface( - nullptr, nullptr, - std::static_pointer_cast< - hal::FakeBluetoothGattInterface::TestClientHandler>(mock_handler_), - nullptr); - hal::BluetoothGattInterface::InitializeForTesting(fake_hal_gatt_iface_); - - factory_.reset(new GattClientFactory()); - } - - void TearDown() override { - factory_.reset(); - hal::BluetoothGattInterface::CleanUp(); - } - - protected: - hal::FakeBluetoothGattInterface* fake_hal_gatt_iface_; - std::shared_ptr<MockGattHandler> mock_handler_; - std::unique_ptr<GattClientFactory> factory_; -}; - -TEST_F(GattClientTest, RegisterInstance) { - EXPECT_CALL(*mock_handler_, RegisterClient(_, _)) - .Times(2) - .WillOnce(Return(BT_STATUS_FAIL)) - .WillOnce(Return(BT_STATUS_SUCCESS)); - - // These will be asynchronously populated with a result when the callback - // executes. - BLEStatus status = BLE_STATUS_SUCCESS; - Uuid cb_uuid; - std::unique_ptr<GattClient> client; - int callback_count = 0; - - auto callback = [&](BLEStatus in_status, const Uuid& uuid, - std::unique_ptr<BluetoothInstance> in_client) { - status = in_status; - cb_uuid = uuid; - client = std::unique_ptr<GattClient>( - static_cast<GattClient*>(in_client.release())); - callback_count++; - }; - - Uuid uuid0 = Uuid::GetRandom(); - - // HAL returns failure. - EXPECT_FALSE(factory_->RegisterInstance(uuid0, callback)); - EXPECT_EQ(0, callback_count); - - // HAL returns success. - EXPECT_TRUE(factory_->RegisterInstance(uuid0, callback)); - EXPECT_EQ(0, callback_count); - - // Calling twice with the same Uuid should fail with no additional call into - // the stack. - EXPECT_FALSE(factory_->RegisterInstance(uuid0, callback)); - - testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // Call with a different Uuid while one is pending. - Uuid uuid1 = Uuid::GetRandom(); - EXPECT_CALL(*mock_handler_, RegisterClient(_, _)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - EXPECT_TRUE(factory_->RegisterInstance(uuid1, callback)); - - // Trigger callback with an unknown Uuid. This should get ignored. - Uuid uuid2 = Uuid::GetRandom(); - fake_hal_gatt_iface_->NotifyRegisterClientCallback(0, 0, uuid2); - EXPECT_EQ(0, callback_count); - - // |uuid0| succeeds. - int client_id0 = 2; // Pick something that's not 0. - fake_hal_gatt_iface_->NotifyRegisterClientCallback(BT_STATUS_SUCCESS, - client_id0, uuid0); - - EXPECT_EQ(1, callback_count); - ASSERT_TRUE(client.get() != nullptr); // Assert to terminate in case of error - EXPECT_EQ(BLE_STATUS_SUCCESS, status); - EXPECT_EQ(client_id0, client->GetInstanceId()); - EXPECT_EQ(uuid0, client->GetAppIdentifier()); - EXPECT_EQ(uuid0, cb_uuid); - - // The client should unregister itself when deleted. - EXPECT_CALL(*mock_handler_, UnregisterClient(client_id0)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - client.reset(); - testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // |uuid1| fails. - int client_id1 = 3; - fake_hal_gatt_iface_->NotifyRegisterClientCallback(BT_STATUS_FAIL, client_id1, - uuid1); - - EXPECT_EQ(2, callback_count); - ASSERT_TRUE(client.get() == nullptr); // Assert to terminate in case of error - EXPECT_EQ(BLE_STATUS_FAILURE, status); - EXPECT_EQ(uuid1, cb_uuid); -} - -} // namespace -} // namespace bluetooth diff --git a/system/service/test/gatt_server_unittest.cc b/system/service/test/gatt_server_unittest.cc deleted file mode 100644 index f0e6f98d33..0000000000 --- a/system/service/test/gatt_server_unittest.cc +++ /dev/null @@ -1,731 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/gatt_server.h" - -#include <gmock/gmock.h> -#include <gtest/gtest.h> - -#include "service/hal/fake_bluetooth_gatt_interface.h" -#include "types/raw_address.h" - -using ::testing::_; -using ::testing::Return; - -namespace bluetooth { -namespace { - -class MockGattHandler - : public hal::FakeBluetoothGattInterface::TestServerHandler { - public: - MockGattHandler() = default; - MockGattHandler(const MockGattHandler&) = delete; - MockGattHandler& operator=(const MockGattHandler&) = delete; - - ~MockGattHandler() override = default; - - MOCK_METHOD2(RegisterServer, - bt_status_t(const bluetooth::Uuid&, bool eatt_support)); - MOCK_METHOD1(UnregisterServer, bt_status_t(int)); - MOCK_METHOD2(AddService, bt_status_t(int, std::vector<btgatt_db_element_t>)); - MOCK_METHOD5(AddCharacteristic, - bt_status_t(int, int, bluetooth::Uuid*, int, int)); - MOCK_METHOD4(AddDescriptor, bt_status_t(int, int, bluetooth::Uuid*, int)); - MOCK_METHOD3(StartService, bt_status_t(int, int, int)); - MOCK_METHOD2(DeleteService, bt_status_t(int, int)); - MOCK_METHOD5(SendIndication, - bt_status_t(int, int, int, int, std::vector<uint8_t>)); - MOCK_METHOD4(SendResponse, - bt_status_t(int, int, int, const btgatt_response_t&)); -}; - -class TestDelegate : public GattServer::Delegate { - public: - TestDelegate() = default; - ~TestDelegate() override = default; - - struct RequestData { - RequestData() - : id(-1), - offset(-1), - is_long(false), - is_prep(false), - need_rsp(false), - is_exec(false), - count(0), - connected(false) {} - ~RequestData() = default; - - std::string device_address; - int id; - int offset; - bool is_long; - bool is_prep; - bool need_rsp; - bool is_exec; - uint16_t handle; - int count; - std::vector<uint8_t> write_value; - bool connected; - }; - - void OnCharacteristicReadRequest(GattServer* gatt_server, - const std::string& device_address, - int request_id, int offset, bool is_long, - uint16_t handle) override { - ASSERT_TRUE(gatt_server); - char_read_req_.device_address = device_address; - char_read_req_.id = request_id; - char_read_req_.offset = offset; - char_read_req_.is_long = is_long; - char_read_req_.handle = handle; - char_read_req_.count++; - } - - void OnDescriptorReadRequest(GattServer* gatt_server, - const std::string& device_address, - int request_id, int offset, bool is_long, - uint16_t handle) override { - ASSERT_TRUE(gatt_server); - desc_read_req_.device_address = device_address; - desc_read_req_.id = request_id; - desc_read_req_.offset = offset; - desc_read_req_.is_long = is_long; - desc_read_req_.handle = handle; - desc_read_req_.count++; - } - - void OnCharacteristicWriteRequest(GattServer* gatt_server, - const std::string& device_address, - int request_id, int offset, - bool is_prepare_write, bool need_response, - const std::vector<uint8_t>& value, - uint16_t handle) override { - ASSERT_TRUE(gatt_server); - char_write_req_.device_address = device_address; - char_write_req_.id = request_id; - char_write_req_.offset = offset; - char_write_req_.is_prep = is_prepare_write; - char_write_req_.need_rsp = need_response; - char_write_req_.handle = handle; - char_write_req_.count++; - char_write_req_.write_value = value; - } - - void OnDescriptorWriteRequest(GattServer* gatt_server, - const std::string& device_address, - int request_id, int offset, - bool is_prepare_write, bool need_response, - const std::vector<uint8_t>& value, - uint16_t handle) override { - ASSERT_TRUE(gatt_server); - desc_write_req_.device_address = device_address; - desc_write_req_.id = request_id; - desc_write_req_.offset = offset; - desc_write_req_.is_prep = is_prepare_write; - desc_write_req_.need_rsp = need_response; - desc_write_req_.handle = handle; - desc_write_req_.count++; - desc_write_req_.write_value = value; - } - - void OnExecuteWriteRequest(GattServer* gatt_server, - const std::string& device_address, int request_id, - bool is_execute) override { - ASSERT_TRUE(gatt_server); - exec_req_.device_address = device_address; - exec_req_.id = request_id; - exec_req_.is_exec = is_execute; - exec_req_.count++; - } - - void OnConnectionStateChanged(GattServer* gatt_server, - const std::string& device_address, - bool connected) override { - ASSERT_TRUE(gatt_server); - conn_state_changed_.device_address = device_address; - conn_state_changed_.connected = connected; - conn_state_changed_.count++; - } - - const RequestData& char_read_req() const { return char_read_req_; } - const RequestData& desc_read_req() const { return desc_read_req_; } - const RequestData& char_write_req() const { return char_write_req_; } - const RequestData& desc_write_req() const { return desc_write_req_; } - const RequestData& conn_state_changed() const { return conn_state_changed_; } - - private: - RequestData char_read_req_; - RequestData desc_read_req_; - RequestData char_write_req_; - RequestData desc_write_req_; - RequestData exec_req_; - RequestData conn_state_changed_; -}; - -class GattServerTest : public ::testing::Test { - public: - GattServerTest() = default; - GattServerTest(const GattServerTest&) = delete; - GattServerTest& operator=(const GattServerTest&) = delete; - - ~GattServerTest() override = default; - - void SetUp() override { - mock_handler_.reset(new MockGattHandler()); - fake_hal_gatt_iface_ = new hal::FakeBluetoothGattInterface( - nullptr, nullptr, nullptr, - std::static_pointer_cast< - hal::FakeBluetoothGattInterface::TestServerHandler>(mock_handler_)); - - hal::BluetoothGattInterface::InitializeForTesting(fake_hal_gatt_iface_); - factory_.reset(new GattServerFactory()); - } - - void TearDown() override { - factory_.reset(); - hal::BluetoothGattInterface::CleanUp(); - } - - protected: - hal::FakeBluetoothGattInterface* fake_hal_gatt_iface_; - std::shared_ptr<MockGattHandler> mock_handler_; - std::unique_ptr<GattServerFactory> factory_; -}; - -const int kDefaultServerId = 4; - -class GattServerPostRegisterTest : public GattServerTest { - public: - GattServerPostRegisterTest() = default; - GattServerPostRegisterTest(const GattServerPostRegisterTest&) = delete; - GattServerPostRegisterTest& operator=(const GattServerPostRegisterTest&) = - delete; - - ~GattServerPostRegisterTest() override = default; - - void SetUp() override { - GattServerTest::SetUp(); - Uuid uuid = Uuid::GetRandom(); - auto callback = [&](BLEStatus status, const Uuid& in_uuid, - std::unique_ptr<BluetoothInstance> in_client) { - CHECK(in_uuid == uuid); - CHECK(in_client.get()); - CHECK(status == BLE_STATUS_SUCCESS); - - gatt_server_ = std::unique_ptr<GattServer>( - static_cast<GattServer*>(in_client.release())); - }; - - EXPECT_CALL(*mock_handler_, RegisterServer(_, _)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - - factory_->RegisterInstance(uuid, callback); - - fake_hal_gatt_iface_->NotifyRegisterServerCallback(BT_STATUS_SUCCESS, - kDefaultServerId, uuid); - } - - void TearDown() override { - EXPECT_CALL(*mock_handler_, UnregisterServer(_)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - gatt_server_ = nullptr; - GattServerTest::TearDown(); - } - - void SetUpTestService() { - EXPECT_CALL(*mock_handler_, AddService(_, _)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - - Uuid uuid0 = Uuid::GetRandom(); - Uuid uuid1 = Uuid::GetRandom(); - Uuid uuid2 = Uuid::GetRandom(); - - bool register_success = false; - - Service service(0, true, uuid0, {}, {}); - - ASSERT_TRUE(gatt_server_->AddService( - service, [&](BLEStatus status, const Service& added_service) { - ASSERT_EQ(BLE_STATUS_SUCCESS, status); - ASSERT_TRUE(Uuid(added_service.uuid()) == Uuid(service.uuid())); - ASSERT_TRUE(added_service.handle() == 0x0001); - register_success = true; - })); - - srvc_handle_ = 0x0001; - char_handle_ = 0x0002; - desc_handle_ = 0x0004; - - std::vector<btgatt_db_element_t> service_with_handles = { - {.uuid = uuid0, - .type = BTGATT_DB_PRIMARY_SERVICE, - .attribute_handle = srvc_handle_}, - {.uuid = uuid1, - .type = BTGATT_DB_CHARACTERISTIC, - .attribute_handle = char_handle_}, - {.uuid = uuid2, - .type = BTGATT_DB_DESCRIPTOR, - .attribute_handle = desc_handle_}, - }; - - fake_hal_gatt_iface_->NotifyServiceAddedCallback( - BT_STATUS_SUCCESS, kDefaultServerId, service_with_handles); - - testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - ASSERT_TRUE(register_success); - } - - protected: - std::unique_ptr<GattServer> gatt_server_; - - uint16_t srvc_handle_; - uint16_t char_handle_; - uint16_t desc_handle_; -}; - -TEST_F(GattServerTest, RegisterServer) { - EXPECT_CALL(*mock_handler_, RegisterServer(_, _)) - .Times(2) - .WillOnce(Return(BT_STATUS_FAIL)) - .WillOnce(Return(BT_STATUS_SUCCESS)); - - // These will be asynchronously populate with a result when the callback - // executes. - BLEStatus status = BLE_STATUS_SUCCESS; - Uuid cb_uuid; - std::unique_ptr<GattServer> server; - int callback_count = 0; - - auto callback = [&](BLEStatus in_status, const Uuid& uuid, - std::unique_ptr<BluetoothInstance> in_server) { - status = in_status; - cb_uuid = uuid; - server = std::unique_ptr<GattServer>( - static_cast<GattServer*>(in_server.release())); - callback_count++; - }; - - Uuid uuid0 = Uuid::GetRandom(); - - // HAL returns failure. - EXPECT_FALSE(factory_->RegisterInstance(uuid0, callback)); - EXPECT_EQ(0, callback_count); - - // HAL returns success. - EXPECT_TRUE(factory_->RegisterInstance(uuid0, callback)); - EXPECT_EQ(0, callback_count); - - // Calling twice with the same Uuid should fail with no additional calls into - // the stack. - EXPECT_FALSE(factory_->RegisterInstance(uuid0, callback)); - - testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // Call with a different Uuid while one is pending. - Uuid uuid1 = Uuid::GetRandom(); - EXPECT_CALL(*mock_handler_, RegisterServer(_, _)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - EXPECT_TRUE(factory_->RegisterInstance(uuid1, callback)); - - // Trigger callback with an unknown Uuid. This should get ignored. - bluetooth::Uuid hal_uuid = bluetooth::Uuid::GetRandom(); - fake_hal_gatt_iface_->NotifyRegisterServerCallback(0, 0, hal_uuid); - EXPECT_EQ(0, callback_count); - - // |uuid0| succeeds. - int server_if0 = 2; // Pick something that's not 0. - fake_hal_gatt_iface_->NotifyRegisterServerCallback(BT_STATUS_SUCCESS, - server_if0, uuid0); - - EXPECT_EQ(1, callback_count); - ASSERT_TRUE(server.get() != nullptr); // Assert to terminate in case of error - EXPECT_EQ(BLE_STATUS_SUCCESS, status); - EXPECT_EQ(server_if0, server->GetInstanceId()); - EXPECT_EQ(uuid0, server->GetAppIdentifier()); - EXPECT_EQ(uuid0, cb_uuid); - - // The server should unregister itself when deleted. - EXPECT_CALL(*mock_handler_, UnregisterServer(server_if0)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - server.reset(); - - testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // |uuid1| fails. - int server_if1 = 3; - fake_hal_gatt_iface_->NotifyRegisterServerCallback(BT_STATUS_FAIL, server_if1, - uuid1); - - EXPECT_EQ(2, callback_count); - ASSERT_TRUE(server.get() == nullptr); // Assert to terminate in case of error - EXPECT_EQ(BLE_STATUS_FAILURE, status); - EXPECT_EQ(uuid1, cb_uuid); -} - -TEST_F(GattServerPostRegisterTest, RequestRead) { - SetUpTestService(); - - TestDelegate test_delegate; - gatt_server_->SetDelegate(&test_delegate); - - const std::vector<uint8_t> kTestValue = {0x01, 0x02, 0x03}; - const std::vector<uint8_t> kTestValueTooLarge(BTGATT_MAX_ATTR_LEN + 1, 0); - const std::string kTestAddress0 = "01:23:45:67:89:AB"; - const std::string kTestAddress1 = "CD:EF:01:23:45:67"; - const int kReqId0 = 0; - const int kReqId1 = 1; - const int kConnId0 = 1; - - // No pending request. - EXPECT_FALSE(gatt_server_->SendResponse(kTestAddress0, kReqId0, - GATT_ERROR_NONE, 0, kTestValue)); - - RawAddress hal_addr0, hal_addr1; - ASSERT_TRUE(RawAddress::FromString(kTestAddress0, hal_addr0)); - ASSERT_TRUE(RawAddress::FromString(kTestAddress1, hal_addr1)); - - // Send a connection callback. The GattServer should store the connection - // information and be able to process the incoming read requests for this - // connection. - fake_hal_gatt_iface_->NotifyServerConnectionCallback( - kConnId0, kDefaultServerId, true, hal_addr0); - - // Unknown connection ID shouldn't trigger anything. - fake_hal_gatt_iface_->NotifyRequestReadCharacteristicCallback( - kConnId0 + 1, kReqId0, hal_addr0, char_handle_, 0, false); - EXPECT_EQ(0, test_delegate.char_read_req().count); - EXPECT_EQ(0, test_delegate.desc_read_req().count); - - // Unknown device address shouldn't trigger anything. - fake_hal_gatt_iface_->NotifyRequestReadCharacteristicCallback( - kConnId0, kReqId0, hal_addr1, char_handle_, 0, false); - EXPECT_EQ(0, test_delegate.char_read_req().count); - EXPECT_EQ(0, test_delegate.desc_read_req().count); - - // Characteristic and descriptor handles should trigger correct callbacks. - fake_hal_gatt_iface_->NotifyRequestReadCharacteristicCallback( - kConnId0, kReqId0, hal_addr0, char_handle_, 0, false); - EXPECT_EQ(1, test_delegate.char_read_req().count); - EXPECT_EQ(kTestAddress0, test_delegate.char_read_req().device_address); - EXPECT_EQ(kReqId0, test_delegate.char_read_req().id); - EXPECT_EQ(0, test_delegate.char_read_req().offset); - EXPECT_FALSE(test_delegate.char_read_req().is_long); - EXPECT_TRUE(char_handle_ == test_delegate.char_read_req().handle); - EXPECT_EQ(0, test_delegate.desc_read_req().count); - - fake_hal_gatt_iface_->NotifyRequestReadDescriptorCallback( - kConnId0, kReqId1, hal_addr0, desc_handle_, 2, true); - EXPECT_EQ(1, test_delegate.char_read_req().count); - EXPECT_EQ(1, test_delegate.desc_read_req().count); - EXPECT_EQ(kTestAddress0, test_delegate.desc_read_req().device_address); - EXPECT_EQ(kReqId1, test_delegate.desc_read_req().id); - EXPECT_EQ(2, test_delegate.desc_read_req().offset); - EXPECT_TRUE(test_delegate.desc_read_req().is_long); - EXPECT_TRUE(desc_handle_ == test_delegate.desc_read_req().handle); - - // Callback with a pending request ID will be ignored. - fake_hal_gatt_iface_->NotifyRequestReadCharacteristicCallback( - kConnId0, kReqId0, hal_addr0, char_handle_, 0, false); - fake_hal_gatt_iface_->NotifyRequestReadCharacteristicCallback( - kConnId0, kReqId1, hal_addr0, char_handle_, 0, false); - EXPECT_EQ(1, test_delegate.char_read_req().count); - EXPECT_EQ(1, test_delegate.desc_read_req().count); - - // Send response for wrong device address. - EXPECT_FALSE(gatt_server_->SendResponse(kTestAddress1, kReqId0, - GATT_ERROR_NONE, 0, kTestValue)); - - // Send response for a value that's too large. - EXPECT_FALSE(gatt_server_->SendResponse( - kTestAddress0, kReqId0, GATT_ERROR_NONE, 0, kTestValueTooLarge)); - - EXPECT_CALL(*mock_handler_, - SendResponse(kConnId0, kReqId0, BT_STATUS_SUCCESS, _)) - .Times(2) - .WillOnce(Return(BT_STATUS_FAIL)) - .WillOnce(Return(BT_STATUS_SUCCESS)); - - // Stack call fails. - EXPECT_FALSE(gatt_server_->SendResponse(kTestAddress0, kReqId0, - GATT_ERROR_NONE, 0, kTestValue)); - - // Successful send response for characteristic. - EXPECT_TRUE(gatt_server_->SendResponse(kTestAddress0, kReqId0, - GATT_ERROR_NONE, 0, kTestValue)); - - // Characteristic request ID no longer pending. - EXPECT_FALSE(gatt_server_->SendResponse(kTestAddress0, kReqId0, - GATT_ERROR_NONE, 0, kTestValue)); - - EXPECT_CALL(*mock_handler_, - SendResponse(kConnId0, kReqId1, BT_STATUS_SUCCESS, _)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - - // Successful send response for descriptor. - EXPECT_TRUE(gatt_server_->SendResponse(kTestAddress0, kReqId1, - GATT_ERROR_NONE, 0, kTestValue)); - - // Descriptor request ID no longer pending. - EXPECT_FALSE(gatt_server_->SendResponse(kTestAddress0, kReqId1, - GATT_ERROR_NONE, 0, kTestValue)); - - gatt_server_->SetDelegate(nullptr); -} - -TEST_F(GattServerPostRegisterTest, RequestWrite) { - SetUpTestService(); - - TestDelegate test_delegate; - gatt_server_->SetDelegate(&test_delegate); - - const std::vector<uint8_t> kTestValue = {0x01, 0x02, 0x03}; - const std::string kTestAddress0 = "01:23:45:67:89:AB"; - const std::string kTestAddress1 = "CD:EF:01:23:45:67"; - const int kReqId0 = 0; - const int kReqId1 = 1; - const int kConnId0 = 1; - - // No pending request. - EXPECT_FALSE(gatt_server_->SendResponse(kTestAddress0, kReqId0, - GATT_ERROR_NONE, 0, kTestValue)); - - RawAddress hal_addr0, hal_addr1; - ASSERT_TRUE(RawAddress::FromString(kTestAddress0, hal_addr0)); - ASSERT_TRUE(RawAddress::FromString(kTestAddress1, hal_addr1)); - - // Send a connection callback. The GattServer should store the connection - // information and be able to process the incoming read requests for this - // connection. - fake_hal_gatt_iface_->NotifyServerConnectionCallback( - kConnId0, kDefaultServerId, true, hal_addr0); - - // Unknown connection ID shouldn't trigger anything. - fake_hal_gatt_iface_->NotifyRequestWriteCharacteristicCallback( - kConnId0 + 1, kReqId0, hal_addr0, char_handle_, 0, true, false, - kTestValue); - EXPECT_EQ(0, test_delegate.char_write_req().count); - EXPECT_EQ(0, test_delegate.desc_write_req().count); - - // Unknown device address shouldn't trigger anything. - fake_hal_gatt_iface_->NotifyRequestWriteCharacteristicCallback( - kConnId0, kReqId0, hal_addr1, char_handle_, 0, true, false, kTestValue); - EXPECT_EQ(0, test_delegate.char_write_req().count); - EXPECT_EQ(0, test_delegate.desc_write_req().count); - - // Characteristic and descriptor handles should trigger correct callbacks. - fake_hal_gatt_iface_->NotifyRequestWriteCharacteristicCallback( - kConnId0, kReqId0, hal_addr0, char_handle_, 0, true, false, kTestValue); - EXPECT_EQ(1, test_delegate.char_write_req().count); - EXPECT_EQ(kTestAddress0, test_delegate.char_write_req().device_address); - EXPECT_EQ(kReqId0, test_delegate.char_write_req().id); - EXPECT_EQ(0, test_delegate.char_write_req().offset); - EXPECT_EQ(true, test_delegate.char_write_req().need_rsp); - EXPECT_EQ(false, test_delegate.char_write_req().is_exec); - EXPECT_EQ(kTestValue, test_delegate.char_write_req().write_value); - EXPECT_TRUE(char_handle_ == test_delegate.char_write_req().handle); - EXPECT_EQ(0, test_delegate.desc_write_req().count); - - fake_hal_gatt_iface_->NotifyRequestWriteDescriptorCallback( - kConnId0, kReqId1, hal_addr0, desc_handle_, 2, true, false, kTestValue); - EXPECT_EQ(1, test_delegate.char_write_req().count); - EXPECT_EQ(1, test_delegate.desc_write_req().count); - EXPECT_EQ(kTestAddress0, test_delegate.desc_write_req().device_address); - EXPECT_EQ(kReqId1, test_delegate.desc_write_req().id); - EXPECT_EQ(2, test_delegate.desc_write_req().offset); - EXPECT_EQ(true, test_delegate.desc_write_req().need_rsp); - EXPECT_EQ(false, test_delegate.desc_write_req().is_exec); - EXPECT_EQ(kTestValue, test_delegate.desc_write_req().write_value); - EXPECT_TRUE(desc_handle_ == test_delegate.desc_write_req().handle); - - // Callback with a pending request ID will be ignored. - fake_hal_gatt_iface_->NotifyRequestWriteCharacteristicCallback( - kConnId0, kReqId0, hal_addr0, char_handle_, 0, true, false, kTestValue); - fake_hal_gatt_iface_->NotifyRequestWriteCharacteristicCallback( - kConnId0, kReqId1, hal_addr0, char_handle_, 0, true, false, kTestValue); - EXPECT_EQ(1, test_delegate.char_write_req().count); - EXPECT_EQ(1, test_delegate.desc_write_req().count); - - // Send response for wrong device address. - EXPECT_FALSE(gatt_server_->SendResponse(kTestAddress1, kReqId0, - GATT_ERROR_NONE, 0, kTestValue)); - - EXPECT_CALL(*mock_handler_, - SendResponse(kConnId0, kReqId0, BT_STATUS_SUCCESS, _)) - .Times(2) - .WillOnce(Return(BT_STATUS_FAIL)) - .WillOnce(Return(BT_STATUS_SUCCESS)); - - // Stack call fails. - EXPECT_FALSE(gatt_server_->SendResponse(kTestAddress0, kReqId0, - GATT_ERROR_NONE, 0, kTestValue)); - - // Successful send response for characteristic. - EXPECT_TRUE(gatt_server_->SendResponse(kTestAddress0, kReqId0, - GATT_ERROR_NONE, 0, kTestValue)); - - // Characteristic request ID no longer pending. - EXPECT_FALSE(gatt_server_->SendResponse(kTestAddress0, kReqId0, - GATT_ERROR_NONE, 0, kTestValue)); - - EXPECT_CALL(*mock_handler_, - SendResponse(kConnId0, kReqId1, BT_STATUS_SUCCESS, _)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - - // Successful send response for descriptor. - EXPECT_TRUE(gatt_server_->SendResponse(kTestAddress0, kReqId1, - GATT_ERROR_NONE, 0, kTestValue)); - - // Descriptor request ID no longer pending. - EXPECT_FALSE(gatt_server_->SendResponse(kTestAddress0, kReqId1, - GATT_ERROR_NONE, 0, kTestValue)); - - // SendResponse should fail for a "Write Without Response". - fake_hal_gatt_iface_->NotifyRequestWriteCharacteristicCallback( - kConnId0, kReqId0, hal_addr0, char_handle_, 0, false, false, kTestValue); - EXPECT_EQ(false, test_delegate.char_write_req().need_rsp); - EXPECT_FALSE(gatt_server_->SendResponse(kTestAddress0, kReqId0, - GATT_ERROR_NONE, 0, kTestValue)); - - gatt_server_->SetDelegate(nullptr); -} - -TEST_F(GattServerPostRegisterTest, SendNotification) { - SetUpTestService(); - - const std::string kTestAddress0 = "01:23:45:67:89:AB"; - const std::string kTestAddress1 = "cd:ef:01:23:45:67"; - const std::string kInvalidAddress = "thingamajig blabbidyboop"; - const int kConnId0 = 0; - const int kConnId1 = 1; - std::vector<uint8_t> value; - RawAddress hal_addr0; - ASSERT_TRUE(RawAddress::FromString(kTestAddress0, hal_addr0)); - - // Set up two connections with the same address. - fake_hal_gatt_iface_->NotifyServerConnectionCallback( - kConnId0, kDefaultServerId, true, hal_addr0); - fake_hal_gatt_iface_->NotifyServerConnectionCallback( - kConnId1, kDefaultServerId, true, hal_addr0); - - // Set up a test callback. - GATTError gatt_error; - int callback_count = 0; - auto callback = [&](GATTError in_error) { - gatt_error = in_error; - callback_count++; - }; - - // Bad device address. - EXPECT_FALSE(gatt_server_->SendNotification(kInvalidAddress, char_handle_, - false, value, callback)); - - // Bad connection. - EXPECT_FALSE(gatt_server_->SendNotification(kTestAddress1, char_handle_, - false, value, callback)); - - // We should get a HAL call for each connection for this address. The calls - // fail. - EXPECT_CALL(*mock_handler_, SendIndication(kDefaultServerId, char_handle_, - kConnId0, 0, value)) - .Times(1) - .WillOnce(Return(BT_STATUS_FAIL)); - EXPECT_CALL(*mock_handler_, SendIndication(kDefaultServerId, char_handle_, - kConnId1, 0, value)) - .Times(1) - .WillOnce(Return(BT_STATUS_FAIL)); - EXPECT_FALSE(gatt_server_->SendNotification(kTestAddress0, char_handle_, - false, value, callback)); - - // One of the calls succeeds. - EXPECT_CALL(*mock_handler_, SendIndication(kDefaultServerId, char_handle_, - kConnId0, 0, value)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - EXPECT_CALL(*mock_handler_, SendIndication(kDefaultServerId, char_handle_, - kConnId1, 0, value)) - .Times(1) - .WillOnce(Return(BT_STATUS_FAIL)); - EXPECT_TRUE(gatt_server_->SendNotification(kTestAddress0, char_handle_, false, - value, callback)); - - // One of the connections is already pending so there should be only one call. - // This one we send with confirm=true. - EXPECT_CALL(*mock_handler_, SendIndication(kDefaultServerId, char_handle_, - kConnId1, 1, value)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - EXPECT_TRUE(gatt_server_->SendNotification(kTestAddress0, char_handle_, true, - value, callback)); - - // Calls are already pending. - EXPECT_FALSE(gatt_server_->SendNotification(kTestAddress0, char_handle_, true, - value, callback)); - - // Trigger one confirmation callback. We should get calls for two callbacks - // since we have two separate calls pending. - fake_hal_gatt_iface_->NotifyIndicationSentCallback(kConnId0, - BT_STATUS_SUCCESS); - fake_hal_gatt_iface_->NotifyIndicationSentCallback(kConnId1, - BT_STATUS_SUCCESS); - EXPECT_EQ(2, callback_count); - EXPECT_EQ(GATT_ERROR_NONE, gatt_error); - - callback_count = 0; - - // Restart. Both calls succeed now. - EXPECT_CALL(*mock_handler_, SendIndication(kDefaultServerId, char_handle_, - kConnId0, 0, value)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - EXPECT_CALL(*mock_handler_, SendIndication(kDefaultServerId, char_handle_, - kConnId1, 0, value)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - EXPECT_TRUE(gatt_server_->SendNotification(kTestAddress0, char_handle_, false, - value, callback)); - - // Trigger one confirmation callback. The callback we passed should still be - // pending. The first callback is for the wrong connection ID. - fake_hal_gatt_iface_->NotifyIndicationSentCallback(kConnId0 + 50, - BT_STATUS_FAIL); - fake_hal_gatt_iface_->NotifyIndicationSentCallback(kConnId0, - BT_STATUS_SUCCESS); - EXPECT_EQ(0, callback_count); - - // This should be ignored since |kConnId0| was already processed. - fake_hal_gatt_iface_->NotifyIndicationSentCallback(kConnId0, - BT_STATUS_SUCCESS); - EXPECT_EQ(0, callback_count); - - // Run the callback with failure. Since the previous callback reported - // success, we should report success. - fake_hal_gatt_iface_->NotifyIndicationSentCallback(kConnId1, - BT_STATUS_SUCCESS); - EXPECT_EQ(1, callback_count); - EXPECT_EQ(GATT_ERROR_NONE, gatt_error); -} - -} // namespace -} // namespace bluetooth diff --git a/system/service/test/ipc_linux_unittest.cc b/system/service/test/ipc_linux_unittest.cc deleted file mode 100644 index 0c3ab31b7d..0000000000 --- a/system/service/test/ipc_linux_unittest.cc +++ /dev/null @@ -1,209 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include <memory> - -#include <sys/socket.h> -#include <sys/un.h> - -#include <base/at_exit.h> -#include <base/command_line.h> -#include <base/files/scoped_file.h> -#include <base/run_loop.h> -#include <base/strings/stringprintf.h> -#include <gtest/gtest.h> - -#include "abstract_message_loop" -#include "array_utils.h" -#include "service/adapter.h" -#include "service/hal/fake_bluetooth_gatt_interface.h" -#include "service/hal/fake_bluetooth_interface.h" -#include "service/ipc/ipc_manager.h" -#include "service/settings.h" -#include "service/test/mock_daemon.h" - -namespace { - -using testing::Return; - -const char kTestSocketPath[] = "test_socket_path"; - -class IPCLinuxTest : public ::testing::Test { - public: - IPCLinuxTest() = default; - IPCLinuxTest(const IPCLinuxTest&) = delete; - IPCLinuxTest& operator=(const IPCLinuxTest&) = delete; - - ~IPCLinuxTest() override = default; - - void SetUp() override { - SetUpCommandLine(); - ASSERT_TRUE(settings_.Init()); - - auto mock_daemon = new bluetooth::testing::MockDaemon(); - - ON_CALL(*mock_daemon, GetSettings()).WillByDefault(Return(&settings_)); - ON_CALL(*mock_daemon, GetMessageLoop()) - .WillByDefault(Return(&message_loop_)); - - bluetooth::Daemon::InitializeForTesting(mock_daemon); - bluetooth::hal::BluetoothInterface::InitializeForTesting( - new bluetooth::hal::FakeBluetoothInterface()); - bluetooth::hal::BluetoothGattInterface::InitializeForTesting( - new bluetooth::hal::FakeBluetoothGattInterface(nullptr, nullptr, - nullptr, nullptr)); - - adapter_ = bluetooth::Adapter::Create(); - ipc_manager_.reset(new ipc::IPCManager(adapter_.get())); - } - - void TearDown() override { - client_fd_.reset(); - ipc_manager_.reset(); - adapter_.reset(); - bluetooth::hal::BluetoothGattInterface::CleanUp(); - bluetooth::hal::BluetoothInterface::CleanUp(); - bluetooth::Daemon::ShutDown(); - base::CommandLine::Reset(); - } - - virtual void SetUpCommandLine() { - std::string ipc_socket_arg = - base::StringPrintf("--create-ipc-socket=%s", kTestSocketPath); - const base::CommandLine::CharType* argv[] = { - "program", ipc_socket_arg.c_str(), - }; - base::CommandLine::Init(ARRAY_SIZE(argv), argv); - } - - void ConnectToTestSocket() { - client_fd_.reset(socket(PF_UNIX, SOCK_SEQPACKET, 0)); - ASSERT_TRUE(client_fd_.is_valid()); - - struct sockaddr_un address; - memset(&address, 0, sizeof(address)); - address.sun_family = AF_UNIX; - strncpy(address.sun_path, kTestSocketPath, sizeof(address.sun_path) - 1); - - int status = - connect(client_fd_.get(), (struct sockaddr*)&address, sizeof(address)); - EXPECT_EQ(0, status); - } - - protected: - base::AtExitManager exit_manager_; - DEFINE_TEST_TASK_ENV(message_loop_); - bluetooth::Settings settings_; - - std::unique_ptr<bluetooth::Adapter> adapter_; - std::unique_ptr<ipc::IPCManager> ipc_manager_; - base::ScopedFD client_fd_; -}; - -class IPCLinuxTestDisabled : public IPCLinuxTest { - public: - IPCLinuxTestDisabled() = default; - IPCLinuxTestDisabled(const IPCLinuxTestDisabled&) = delete; - IPCLinuxTestDisabled& operator=(const IPCLinuxTestDisabled&) = delete; - - ~IPCLinuxTestDisabled() override = default; - - void SetUpCommandLine() override { - // Set up with no --ipc-socket-path - const base::CommandLine::CharType* argv[] = {"program"}; - base::CommandLine::Init(ARRAY_SIZE(argv), argv); - } -}; - -class TestDelegate : public ipc::IPCManager::Delegate, - public base::SupportsWeakPtr<TestDelegate> { - public: - TestDelegate() : started_count_(0), stopped_count_(0) {} - - TestDelegate(const TestDelegate&) = delete; - TestDelegate& operator=(const TestDelegate&) = delete; - - void OnIPCHandlerStarted(ipc::IPCManager::Type type) override { - ASSERT_EQ(ipc::IPCManager::TYPE_LINUX, type); - started_count_++; - btbase::AbstractTestMessageLoop::currentIO()->QuitWhenIdle(); - } - - void OnIPCHandlerStopped(ipc::IPCManager::Type type) override { - ASSERT_EQ(ipc::IPCManager::TYPE_LINUX, type); - stopped_count_++; - btbase::AbstractTestMessageLoop::currentIO()->QuitWhenIdle(); - } - - int started_count() const { return started_count_; } - int stopped_count() const { return stopped_count_; } - - private: - int started_count_; - int stopped_count_; -}; - -TEST_F(IPCLinuxTestDisabled, StartWithNoSocketPath) { - TestDelegate delegate; - EXPECT_FALSE(ipc_manager_->Start(ipc::IPCManager::TYPE_LINUX, &delegate)); - EXPECT_FALSE(ipc_manager_->LinuxStarted()); - EXPECT_EQ(0, delegate.started_count()); - EXPECT_EQ(0, delegate.stopped_count()); -} - -TEST_F(IPCLinuxTest, BasicStartAndExit) { - TestDelegate delegate; - EXPECT_TRUE(ipc_manager_->Start(ipc::IPCManager::TYPE_LINUX, &delegate)); - EXPECT_TRUE(ipc_manager_->LinuxStarted()); - - // Run the message loop. We will stop the loop when we receive a delegate - // event. - base::RunLoop().Run(); - - // We should have received the started event. - EXPECT_EQ(1, delegate.started_count()); - EXPECT_EQ(0, delegate.stopped_count()); - - // At this point the thread is blocking on accept and listening for incoming - // connections. TearDown should gracefully clean up the thread and the test - // should succeed without hanging. - ipc_manager_.reset(); - base::RunLoop().Run(); - EXPECT_EQ(1, delegate.stopped_count()); -} - -TEST_F(IPCLinuxTest, BasicStartAndConnect) { - TestDelegate delegate; - EXPECT_TRUE(ipc_manager_->Start(ipc::IPCManager::TYPE_LINUX, &delegate)); - EXPECT_TRUE(ipc_manager_->LinuxStarted()); - - // Run the message loop. We will stop the loop when we receive a delegate - // event. - base::RunLoop().Run(); - - // We should have received the started event. - EXPECT_EQ(1, delegate.started_count()); - EXPECT_EQ(0, delegate.stopped_count()); - - // IPC successfully started. Now attempt to connect to the socket. - ConnectToTestSocket(); - - // TODO(armansito): Test that the IPC event loop shuts down cleanly while a - // client is connected. Currently this will fail and the fix is to use - // MessageLoopForIO rather than a custom event loop. -} - -} // namespace diff --git a/system/service/test/low_energy_advertiser_unittest.cc b/system/service/test/low_energy_advertiser_unittest.cc deleted file mode 100644 index 297d9d70ca..0000000000 --- a/system/service/test/low_energy_advertiser_unittest.cc +++ /dev/null @@ -1,644 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include <gmock/gmock.h> -#include <gtest/gtest.h> - -#include "service/adapter.h" -#include "service/hal/fake_bluetooth_gatt_interface.h" -#include "service/low_energy_advertiser.h" -#include "stack/include/bt_types.h" -#include "stack/include/hcidefs.h" -#include "test/mock_adapter.h" - -using ::testing::_; -using ::testing::DoAll; -using ::testing::Exactly; -using ::testing::Invoke; -using ::testing::Pointee; -using ::testing::Return; -using ::testing::SaveArg; -using ::testing::Matcher; -using status_cb = base::Callback<void(uint8_t)>; -using reg_cb = - base::Callback<void(uint8_t /* advertiser_id */, uint8_t /* status */)>; - -namespace bluetooth { -namespace { - -class MockAdvertiserHandler : public BleAdvertiserInterface { - public: - MockAdvertiserHandler() {} - MockAdvertiserHandler(const MockAdvertiserHandler&) = delete; - MockAdvertiserHandler& operator=(const MockAdvertiserHandler&) = delete; - - ~MockAdvertiserHandler() override = default; - - MOCK_METHOD1(RegisterAdvertiser, void(IdStatusCallback)); - MOCK_METHOD1(Unregister, void(uint8_t)); - MOCK_METHOD2(GetOwnAddress, void(uint8_t, GetAddressCallback)); - MOCK_METHOD3(SetParameters, - void(uint8_t, AdvertiseParameters, ParametersCallback)); - MOCK_METHOD4(SetData, void(int, bool, std::vector<uint8_t>, StatusCallback)); - MOCK_METHOD6(Enable, void(uint8_t, bool, StatusCallback, uint16_t, uint8_t, - StatusCallback)); - MOCK_METHOD7(StartAdvertising, - void(uint8_t advertiser_id, StatusCallback cb, - AdvertiseParameters, std::vector<uint8_t>, - std::vector<uint8_t>, int, StatusCallback)); - MOCK_METHOD10(StartAdvertisingSet, - uint8_t(int reg_id, IdTxPowerStatusCallback cb, - AdvertiseParameters params, - std::vector<uint8_t> advertise_data, - std::vector<uint8_t> scan_response_data, - PeriodicAdvertisingParameters periodic_params, - std::vector<uint8_t> periodic_data, uint16_t duration, - uint8_t maxExtAdvEvents, IdStatusCallback timeout_cb)); - MOCK_METHOD3(SetPeriodicAdvertisingParameters, - void(int, PeriodicAdvertisingParameters, StatusCallback)); - MOCK_METHOD3(SetPeriodicAdvertisingData, - void(int, std::vector<uint8_t>, StatusCallback)); - MOCK_METHOD4(SetPeriodicAdvertisingEnable, - void(int, bool, bool, StatusCallback)); - MOCK_METHOD1(RegisterCallbacks, void(AdvertisingCallbacks* callbacks)); -}; - -class LowEnergyAdvertiserTest : public ::testing::Test { - public: - LowEnergyAdvertiserTest() = default; - LowEnergyAdvertiserTest(const LowEnergyAdvertiserTest&) = delete; - LowEnergyAdvertiserTest& operator=(const LowEnergyAdvertiserTest&) = delete; - - ~LowEnergyAdvertiserTest() override = default; - - void SetUp() override { - // Only set |mock_handler_| if a test hasn't set it. - if (!mock_handler_) mock_handler_.reset(new MockAdvertiserHandler()); - hal::BluetoothGattInterface::InitializeForTesting( - new hal::FakeBluetoothGattInterface( - std::static_pointer_cast<BleAdvertiserInterface>(mock_handler_), - nullptr, nullptr, nullptr)); - ble_advertiser_factory_.reset(new LowEnergyAdvertiserFactory()); - } - - void TearDown() override { - ble_advertiser_factory_.reset(); - hal::BluetoothGattInterface::CleanUp(); - } - - protected: - std::shared_ptr<MockAdvertiserHandler> mock_handler_; - std::unique_ptr<LowEnergyAdvertiserFactory> ble_advertiser_factory_; -}; - -// Used for tests that operate on a pre-registered advertiser. -class LowEnergyAdvertiserPostRegisterTest : public LowEnergyAdvertiserTest { - public: - LowEnergyAdvertiserPostRegisterTest() : next_client_id_(0) {} - LowEnergyAdvertiserPostRegisterTest( - const LowEnergyAdvertiserPostRegisterTest&) = delete; - LowEnergyAdvertiserPostRegisterTest& operator=( - const LowEnergyAdvertiserPostRegisterTest&) = delete; - - ~LowEnergyAdvertiserPostRegisterTest() override = default; - - void SetUp() override { - LowEnergyAdvertiserTest::SetUp(); - auto callback = [&](std::unique_ptr<LowEnergyAdvertiser> advertiser) { - le_advertiser_ = std::move(advertiser); - }; - RegisterTestAdvertiser(callback); - } - - void TearDown() override { - EXPECT_CALL(*mock_handler_, Enable(_, false, _, _, _, _)).Times(1); - EXPECT_CALL(*mock_handler_, Unregister(_)).Times(1); - le_advertiser_.reset(); - LowEnergyAdvertiserTest::TearDown(); - } - - void RegisterTestAdvertiser( - const std::function<void(std::unique_ptr<LowEnergyAdvertiser> advertiser)> - callback) { - Uuid uuid = Uuid::GetRandom(); - auto api_callback = [&](BLEStatus status, const Uuid& in_uuid, - std::unique_ptr<BluetoothInstance> in_client) { - CHECK(in_uuid == uuid); - CHECK(in_client.get()); - CHECK(status == BLE_STATUS_SUCCESS); - - callback(std::unique_ptr<LowEnergyAdvertiser>( - static_cast<LowEnergyAdvertiser*>(in_client.release()))); - }; - - reg_cb reg_adv_cb; - EXPECT_CALL(*mock_handler_, RegisterAdvertiser(_)) - .Times(1) - .WillOnce(SaveArg<0>(®_adv_cb)); - - ble_advertiser_factory_->RegisterInstance(uuid, api_callback); - - reg_adv_cb.Run(next_client_id_++, BT_STATUS_SUCCESS); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - } - - void StartAdvertising() { - ASSERT_FALSE(le_advertiser_->IsAdvertisingStarted()); - ASSERT_FALSE(le_advertiser_->IsStartingAdvertising()); - ASSERT_FALSE(le_advertiser_->IsStoppingAdvertising()); - - status_cb start_advertising_cb; - EXPECT_CALL(*mock_handler_, StartAdvertising(_, _, _, _, _, _, _)) - .Times(1) - .WillOnce(SaveArg<1>(&start_advertising_cb)); - status_cb set_data_cb; - - AdvertiseSettings settings; - AdvertiseData adv, scan_rsp; - ASSERT_TRUE(le_advertiser_->StartAdvertising( - settings, adv, scan_rsp, LowEnergyAdvertiser::StatusCallback())); - ASSERT_TRUE(le_advertiser_->IsStartingAdvertising()); - - start_advertising_cb.Run(BT_STATUS_SUCCESS); - - ASSERT_TRUE(le_advertiser_->IsAdvertisingStarted()); - ASSERT_FALSE(le_advertiser_->IsStartingAdvertising()); - ASSERT_FALSE(le_advertiser_->IsStoppingAdvertising()); - } - - void AdvertiseDataTestHelper(AdvertiseData data, - std::function<void(BLEStatus)> callback, - status_cb* set_data_cb) { - AdvertiseSettings settings; - - LOG_ASSERT(set_data_cb) << "set_data_cb must be set"; - - EXPECT_TRUE(le_advertiser_->StartAdvertising(settings, data, - AdvertiseData(), callback)); - - set_data_cb->Run(BT_STATUS_SUCCESS); - - status_cb disable_cb; - EXPECT_CALL(*mock_handler_, Enable(_, false, _, _, _, _)) - .Times(1) - .WillOnce(SaveArg<2>(&disable_cb)); - - EXPECT_TRUE( - le_advertiser_->StopAdvertising(LowEnergyAdvertiser::StatusCallback())); - disable_cb.Run(BT_STATUS_SUCCESS); - } - - protected: - std::unique_ptr<LowEnergyAdvertiser> le_advertiser_; - - private: - int next_client_id_; -}; - -TEST_F(LowEnergyAdvertiserTest, RegisterInstance) { - // These will be asynchronously populated with a result when the callback - // executes. - BLEStatus status = BLE_STATUS_SUCCESS; - Uuid cb_uuid; - std::unique_ptr<LowEnergyAdvertiser> advertiser; - int callback_count = 0; - - auto callback = [&](BLEStatus in_status, const Uuid& uuid, - std::unique_ptr<BluetoothInstance> in_client) { - status = in_status; - cb_uuid = uuid; - advertiser = std::unique_ptr<LowEnergyAdvertiser>( - static_cast<LowEnergyAdvertiser*>(in_client.release())); - callback_count++; - }; - - Uuid uuid0 = Uuid::GetRandom(); - - reg_cb reg_adv1_cb; - EXPECT_CALL(*mock_handler_, RegisterAdvertiser(_)) - .Times(1) - .WillOnce(SaveArg<0>(®_adv1_cb)); - - // Success. - EXPECT_TRUE(ble_advertiser_factory_->RegisterInstance(uuid0, callback)); - EXPECT_EQ(0, callback_count); - - // Calling twice with the same Uuid should fail with no additional call into - // the stack. - EXPECT_FALSE(ble_advertiser_factory_->RegisterInstance(uuid0, callback)); - - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // Call with a different Uuid while one is pending. - Uuid uuid1 = Uuid::GetRandom(); - reg_cb reg_adv2_cb; - EXPECT_CALL(*mock_handler_, RegisterAdvertiser(_)) - .Times(1) - .WillOnce(SaveArg<0>(®_adv2_cb)); - EXPECT_TRUE(ble_advertiser_factory_->RegisterInstance(uuid1, callback)); - - // |uuid0| succeeds. - int client_if0 = 2; // Pick something that's not 0. - reg_adv1_cb.Run(client_if0, BT_STATUS_SUCCESS); - - EXPECT_EQ(1, callback_count); - ASSERT_TRUE(advertiser.get() != - nullptr); // Assert to terminate in case of error - EXPECT_EQ(BLE_STATUS_SUCCESS, status); - EXPECT_EQ(client_if0, advertiser->GetInstanceId()); - EXPECT_EQ(uuid0, advertiser->GetAppIdentifier()); - EXPECT_EQ(uuid0, cb_uuid); - - // The advertiser should unregister itself when deleted. - EXPECT_CALL(*mock_handler_, Enable(client_if0, false, _, _, _, _)).Times(1); - EXPECT_CALL(*mock_handler_, Unregister(client_if0)).Times(1); - advertiser.reset(); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // |uuid1| fails. - uint8_t client_if1 = 10; - reg_adv2_cb.Run(client_if1, BT_STATUS_FAIL); - - EXPECT_EQ(2, callback_count); - ASSERT_TRUE(advertiser.get() == - nullptr); // Assert to terminate in case of error - EXPECT_EQ(BLE_STATUS_FAILURE, status); - EXPECT_EQ(uuid1, cb_uuid); -} - -TEST_F(LowEnergyAdvertiserPostRegisterTest, StartAdvertisingBasic) { - EXPECT_FALSE(le_advertiser_->IsAdvertisingStarted()); - EXPECT_FALSE(le_advertiser_->IsStartingAdvertising()); - EXPECT_FALSE(le_advertiser_->IsStoppingAdvertising()); - - // Use default advertising settings and data. - AdvertiseSettings settings; - AdvertiseData adv_data, scan_rsp; - int callback_count = 0; - BLEStatus last_status = BLE_STATUS_FAILURE; - auto callback = [&](BLEStatus status) { - last_status = status; - callback_count++; - }; - - status_cb start_advertising_cb; - EXPECT_CALL(*mock_handler_, StartAdvertising(_, _, _, _, _, _, _)) - .Times(2) - .WillRepeatedly(SaveArg<1>(&start_advertising_cb)); - - // Stack call returns success. - EXPECT_TRUE( - le_advertiser_->StartAdvertising(settings, adv_data, scan_rsp, callback)); - - EXPECT_FALSE(le_advertiser_->IsAdvertisingStarted()); - EXPECT_TRUE(le_advertiser_->IsStartingAdvertising()); - EXPECT_FALSE(le_advertiser_->IsStoppingAdvertising()); - EXPECT_EQ(0, callback_count); - - // Already starting. - EXPECT_FALSE( - le_advertiser_->StartAdvertising(settings, adv_data, scan_rsp, callback)); - - // Notify failure. - start_advertising_cb.Run(BT_STATUS_FAIL); - - EXPECT_FALSE(le_advertiser_->IsAdvertisingStarted()); - EXPECT_FALSE(le_advertiser_->IsStartingAdvertising()); - EXPECT_FALSE(le_advertiser_->IsStoppingAdvertising()); - EXPECT_EQ(1, callback_count); - EXPECT_EQ(BLE_STATUS_FAILURE, last_status); - - // Try again. - EXPECT_TRUE( - le_advertiser_->StartAdvertising(settings, adv_data, scan_rsp, callback)); - EXPECT_FALSE(le_advertiser_->IsAdvertisingStarted()); - EXPECT_TRUE(le_advertiser_->IsStartingAdvertising()); - EXPECT_FALSE(le_advertiser_->IsStoppingAdvertising()); - EXPECT_EQ(1, callback_count); - - start_advertising_cb.Run(BT_STATUS_SUCCESS); - - EXPECT_TRUE(le_advertiser_->IsAdvertisingStarted()); - EXPECT_FALSE(le_advertiser_->IsStartingAdvertising()); - EXPECT_FALSE(le_advertiser_->IsStoppingAdvertising()); - EXPECT_EQ(2, callback_count); - EXPECT_EQ(BLE_STATUS_SUCCESS, last_status); - - // Already started. - EXPECT_FALSE( - le_advertiser_->StartAdvertising(settings, adv_data, scan_rsp, callback)); -} - -TEST_F(LowEnergyAdvertiserPostRegisterTest, StopAdvertisingBasic) { - AdvertiseSettings settings; - - // Not enabled. - EXPECT_FALSE(le_advertiser_->IsAdvertisingStarted()); - EXPECT_FALSE( - le_advertiser_->StopAdvertising(LowEnergyAdvertiser::StatusCallback())); - - // Start advertising for testing. - StartAdvertising(); - - int callback_count = 0; - BLEStatus last_status = BLE_STATUS_FAILURE; - auto callback = [&](BLEStatus status) { - last_status = status; - callback_count++; - }; - - status_cb enable_cb; - EXPECT_CALL(*mock_handler_, Enable(_, false, _, _, _, _)) - .Times(2) - .WillRepeatedly(SaveArg<2>(&enable_cb)); - - // Stack returns success. - EXPECT_TRUE(le_advertiser_->StopAdvertising(callback)); - EXPECT_TRUE(le_advertiser_->IsAdvertisingStarted()); - EXPECT_FALSE(le_advertiser_->IsStartingAdvertising()); - EXPECT_TRUE(le_advertiser_->IsStoppingAdvertising()); - EXPECT_EQ(0, callback_count); - - // Already disabling. - EXPECT_FALSE(le_advertiser_->StopAdvertising(callback)); - EXPECT_TRUE(le_advertiser_->IsAdvertisingStarted()); - EXPECT_FALSE(le_advertiser_->IsStartingAdvertising()); - EXPECT_TRUE(le_advertiser_->IsStoppingAdvertising()); - EXPECT_EQ(0, callback_count); - - // Notify failure. - enable_cb.Run(BT_STATUS_FAIL); - EXPECT_TRUE(le_advertiser_->IsAdvertisingStarted()); - EXPECT_FALSE(le_advertiser_->IsStartingAdvertising()); - EXPECT_FALSE(le_advertiser_->IsStoppingAdvertising()); - EXPECT_EQ(1, callback_count); - EXPECT_EQ(BLE_STATUS_FAILURE, last_status); - - // Try again. - EXPECT_TRUE(le_advertiser_->StopAdvertising(callback)); - EXPECT_TRUE(le_advertiser_->IsAdvertisingStarted()); - EXPECT_FALSE(le_advertiser_->IsStartingAdvertising()); - EXPECT_TRUE(le_advertiser_->IsStoppingAdvertising()); - EXPECT_EQ(1, callback_count); - - // Notify success. - enable_cb.Run(BT_STATUS_SUCCESS); - EXPECT_FALSE(le_advertiser_->IsAdvertisingStarted()); - EXPECT_FALSE(le_advertiser_->IsStartingAdvertising()); - EXPECT_FALSE(le_advertiser_->IsStoppingAdvertising()); - EXPECT_EQ(2, callback_count); - EXPECT_EQ(BLE_STATUS_SUCCESS, last_status); - - // Already stopped. - EXPECT_FALSE(le_advertiser_->StopAdvertising(callback)); -} - -TEST_F(LowEnergyAdvertiserPostRegisterTest, InvalidAdvertiseData) { - const std::vector<uint8_t> data0{0x02, HCI_EIR_FLAGS_TYPE, 0x00}; - const std::vector<uint8_t> data1{0x04, HCI_EIR_MANUFACTURER_SPECIFIC_TYPE, - 0x01, 0x02, 0x00}; - AdvertiseData invalid_adv(data0); - AdvertiseData valid_adv(data1); - - AdvertiseSettings settings; - - EXPECT_FALSE(le_advertiser_->StartAdvertising( - settings, valid_adv, invalid_adv, LowEnergyAdvertiser::StatusCallback())); - EXPECT_FALSE(le_advertiser_->StartAdvertising( - settings, invalid_adv, valid_adv, LowEnergyAdvertiser::StatusCallback())); - - // Manufacturer data not correctly formatted according to spec. We let the - // stack handle this case. - const std::vector<uint8_t> data2{0x01, HCI_EIR_MANUFACTURER_SPECIFIC_TYPE}; - AdvertiseData invalid_mfc(data2); - - EXPECT_CALL(*mock_handler_, StartAdvertising(_, _, _, _, _, _, _)).Times(1); - EXPECT_TRUE(le_advertiser_->StartAdvertising( - settings, invalid_mfc, valid_adv, LowEnergyAdvertiser::StatusCallback())); -} - -TEST_F(LowEnergyAdvertiserPostRegisterTest, AdvertiseDataParsing) { - const std::vector<uint8_t> kUuid16BitData{ - 0x03, HCI_EIR_COMPLETE_16BITS_UUID_TYPE, 0xDE, 0xAD, - }; - - const std::vector<uint8_t> kUuid32BitData{ - 0x05, HCI_EIR_COMPLETE_32BITS_UUID_TYPE, 0xDE, 0xAD, 0x01, 0x02}; - - const std::vector<uint8_t> kUUID128BitData{ - 0x11, HCI_EIR_COMPLETE_128BITS_UUID_TYPE, - 0xDE, 0xAD, - 0x01, 0x02, - 0x03, 0x04, - 0x05, 0x06, - 0x07, 0x08, - 0x09, 0x0A, - 0x0B, 0x0C, - 0x0D, 0x0E}; - - const std::vector<uint8_t> kMultiUuidData{ - 0x11, HCI_EIR_COMPLETE_128BITS_UUID_TYPE, - 0xDE, 0xAD, - 0x01, 0x02, - 0x03, 0x04, - 0x05, 0x06, - 0x07, 0x08, - 0x09, 0x0A, - 0x0B, 0x0C, - 0x0D, 0x0E, - 0x05, HCI_EIR_COMPLETE_32BITS_UUID_TYPE, - 0xDE, 0xAD, - 0xBE, 0xEF}; - - const std::vector<uint8_t> kServiceData16Bit{ - 0x05, HCI_EIR_SERVICE_DATA_16BITS_UUID_TYPE, 0xDE, 0xAD, 0xBE, 0xEF}; - - const std::vector<uint8_t> kServiceData32Bit{ - 0x07, HCI_EIR_SERVICE_DATA_32BITS_UUID_TYPE, 0xDE, 0xAD, 0x01, 0x02, 0xBE, - 0xEF}; - - const std::vector<uint8_t> kServiceData128Bit{ - 0x13, HCI_EIR_SERVICE_DATA_128BITS_UUID_TYPE, - 0xDE, 0xAD, - 0x01, 0x02, - 0x03, 0x04, - 0x05, 0x06, - 0x07, 0x08, - 0x09, 0x0A, - 0x0B, 0x0C, - 0x0D, 0x0E, - 0xBE, 0xEF}; - - const std::vector<uint8_t> kMultiServiceData{ - 0x13, HCI_EIR_SERVICE_DATA_128BITS_UUID_TYPE, - 0xDE, 0xAD, - 0x01, 0x02, - 0x03, 0x04, - 0x05, 0x06, - 0xBE, 0xEF, - 0xDE, 0xAD, - 0x01, 0x02, - 0x03, 0x04, - 0x05, 0x06, - 0x05, HCI_EIR_SERVICE_DATA_16BITS_UUID_TYPE, - 0xDE, 0xAD, - 0xBE, 0xEF}; - - const std::vector<uint8_t> kServiceUuidMatch{ - 0x05, HCI_EIR_COMPLETE_32BITS_UUID_TYPE, - 0xDE, 0xAD, - 0x01, 0x02, - 0x07, HCI_EIR_SERVICE_DATA_32BITS_UUID_TYPE, - 0xDE, 0xAD, - 0x01, 0x02, - 0xBE, 0xEF}; - - const std::vector<uint8_t> kServiceUuidMismatch{ - 0x05, HCI_EIR_COMPLETE_32BITS_UUID_TYPE, - 0xDE, 0xAD, - 0x01, 0x01, - 0x07, HCI_EIR_SERVICE_DATA_32BITS_UUID_TYPE, - 0xDE, 0xAD, - 0x01, 0x02, - 0xBE, 0xEF}; - - AdvertiseData uuid_16bit_adv(kUuid16BitData); - AdvertiseData uuid_32bit_adv(kUuid32BitData); - AdvertiseData uuid_128bit_adv(kUUID128BitData); - AdvertiseData multi_uuid_adv(kMultiUuidData); - - AdvertiseData service_16bit_adv(kServiceData16Bit); - AdvertiseData service_32bit_adv(kServiceData32Bit); - AdvertiseData service_128bit_adv(kServiceData128Bit); - AdvertiseData multi_service_adv(kMultiServiceData); - - AdvertiseData service_uuid_match(kServiceUuidMatch); - AdvertiseData service_uuid_mismatch(kServiceUuidMismatch); - - AdvertiseSettings settings; - - int callback_count = 0; - BLEStatus last_status = BLE_STATUS_FAILURE; - auto callback = [&](BLEStatus status) { - last_status = status; - callback_count++; - }; - - status_cb start_advertising_cb; - // Multiple Uuid test - EXPECT_CALL(*mock_handler_, StartAdvertising(_, _, _, _, _, _, _)) - .Times(1) - .WillOnce(SaveArg<1>(&start_advertising_cb)); - AdvertiseDataTestHelper(multi_uuid_adv, callback, &start_advertising_cb); - EXPECT_EQ(1, callback_count); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // Multiple Service Data test - EXPECT_CALL(*mock_handler_, StartAdvertising(_, _, _, _, _, _, _)) - .Times(1) - .WillOnce(SaveArg<1>(&start_advertising_cb)); - AdvertiseDataTestHelper(multi_service_adv, callback, &start_advertising_cb); - EXPECT_EQ(2, callback_count); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // 16bit uuid test, should succeed with correctly parsed uuid in little-endian - // 128-bit format. - const std::vector<uint8_t> uuid_16bit_canonical{ - 0xFB, 0x34, 0x9b, 0x5F, 0x80, 0x00, 0x00, 0x80, - 0x00, 0x10, 0x00, 0x00, 0xDE, 0xAD, 0x00, 0x00}; - EXPECT_CALL(*mock_handler_, StartAdvertising(_, _, _, _, _, _, _)) - .Times(1) - .WillOnce(SaveArg<1>(&start_advertising_cb)); - AdvertiseDataTestHelper(uuid_16bit_adv, callback, &start_advertising_cb); - EXPECT_EQ(3, callback_count); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // 32bit uuid test, should succeed with correctly parsed uuid - const std::vector<uint8_t> uuid_32bit_canonical{ - 0xFB, 0x34, 0x9b, 0x5F, 0x80, 0x00, 0x00, 0x80, - 0x00, 0x10, 0x00, 0x00, 0xDE, 0xAD, 0x01, 0x02}; - EXPECT_CALL(*mock_handler_, StartAdvertising(_, _, _, _, _, _, _)) - .Times(1) - .WillOnce(SaveArg<1>(&start_advertising_cb)); - AdvertiseDataTestHelper(uuid_32bit_adv, callback, &start_advertising_cb); - EXPECT_EQ(4, callback_count); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // 128bit uuid test, should succeed with correctly parsed uuid - const std::vector<uint8_t> uuid_128bit{0xDE, 0xAD, 0x01, 0x02, 0x03, 0x04, - 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, - 0x0B, 0x0C, 0x0D, 0x0E}; - EXPECT_CALL(*mock_handler_, StartAdvertising(_, _, _, _, _, _, _)) - .Times(1) - .WillOnce(SaveArg<1>(&start_advertising_cb)); - AdvertiseDataTestHelper(uuid_128bit_adv, callback, &start_advertising_cb); - EXPECT_EQ(5, callback_count); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - const std::vector<uint8_t> service_data{0xBE, 0xEF}; - - // Service data with 16bit uuid included, should succeed with - // uuid and service data parsed out - EXPECT_CALL(*mock_handler_, StartAdvertising(_, _, _, _, _, _, _)) - .Times(1) - .WillOnce(SaveArg<1>(&start_advertising_cb)); - AdvertiseDataTestHelper(service_16bit_adv, callback, &start_advertising_cb); - EXPECT_EQ(6, callback_count); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // Service data with 32bit uuid included, should succeed with - // uuid and service data parsed out - EXPECT_CALL(*mock_handler_, StartAdvertising(_, _, _, _, _, _, _)) - .Times(1) - .WillOnce(SaveArg<1>(&start_advertising_cb)); - AdvertiseDataTestHelper(service_32bit_adv, callback, &start_advertising_cb); - EXPECT_EQ(7, callback_count); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // Service data with 128bit uuid included, should succeed with - // uuid and service data parsed out - EXPECT_CALL(*mock_handler_, StartAdvertising(_, _, _, _, _, _, _)) - .Times(1) - .WillOnce(SaveArg<1>(&start_advertising_cb)); - AdvertiseDataTestHelper(service_128bit_adv, callback, &start_advertising_cb); - EXPECT_EQ(8, callback_count); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // Service data and Uuid where the Uuid for both match, should succeed. - EXPECT_CALL(*mock_handler_, StartAdvertising(_, _, _, _, _, _, _)) - .Times(1) - .WillOnce(SaveArg<1>(&start_advertising_cb)); - AdvertiseDataTestHelper(service_uuid_match, callback, &start_advertising_cb); - EXPECT_EQ(9, callback_count); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // Service data and Uuid where the Uuid for dont match, should fail - EXPECT_CALL(*mock_handler_, StartAdvertising(_, _, _, _, _, _, _)) - .Times(1) - .WillOnce(SaveArg<1>(&start_advertising_cb)); - AdvertiseDataTestHelper(service_uuid_match, callback, &start_advertising_cb); - EXPECT_EQ(10, callback_count); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); -} - -MATCHER_P(BitEq, x, std::string(negation ? "isn't" : "is") + - " bitwise equal to " + ::testing::PrintToString(x)) { - static_assert(sizeof(x) == sizeof(arg), "Size mismatch"); - return std::memcmp(&arg, &x, sizeof(x)) == 0; -} - -} // namespace -} // namespace bluetooth diff --git a/system/service/test/low_energy_client_unittest.cc b/system/service/test/low_energy_client_unittest.cc deleted file mode 100644 index f2669ba085..0000000000 --- a/system/service/test/low_energy_client_unittest.cc +++ /dev/null @@ -1,307 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/low_energy_client.h" - -#include <gmock/gmock.h> -#include <gtest/gtest.h> - -#include "service/adapter.h" -#include "service/hal/fake_bluetooth_gatt_interface.h" -#include "stack/include/bt_types.h" -#include "test/mock_adapter.h" -#include "types/bt_transport.h" -#include "types/raw_address.h" - -using ::testing::_; -using ::testing::Return; -using ::testing::Pointee; -using ::testing::DoAll; -using ::testing::Invoke; - -namespace bluetooth { -namespace { - -class MockGattHandler - : public hal::FakeBluetoothGattInterface::TestClientHandler { - public: - MockGattHandler(){}; - MockGattHandler(const MockGattHandler&) = delete; - MockGattHandler& operator=(const MockGattHandler&) = delete; - - ~MockGattHandler() override = default; - - MOCK_METHOD2(RegisterClient, - bt_status_t(const bluetooth::Uuid&, bool eatt_support)); - MOCK_METHOD1(UnregisterClient, bt_status_t(int)); - MOCK_METHOD4(Connect, bt_status_t(int, const RawAddress&, bool, int)); - MOCK_METHOD3(Disconnect, bt_status_t(int, const RawAddress&, int)); -}; - -class TestDelegate : public LowEnergyClient::Delegate { - public: - TestDelegate() : connection_state_count_(0), last_mtu_(0) {} - - TestDelegate(const TestDelegate&) = delete; - TestDelegate& operator=(const TestDelegate&) = delete; - - ~TestDelegate() override = default; - - int connection_state_count() const { return connection_state_count_; } - - void OnConnectionState(LowEnergyClient* client, int status, - const char* address, bool connected) override { - ASSERT_TRUE(client); - connection_state_count_++; - } - - void OnMtuChanged(LowEnergyClient* client, int status, const char* address, - int mtu) override { - ASSERT_TRUE(client); - last_mtu_ = mtu; - } - - private: - int connection_state_count_; - - int last_mtu_; -}; - -class LowEnergyClientTest : public ::testing::Test { - public: - LowEnergyClientTest() = default; - LowEnergyClientTest(const LowEnergyClientTest&) = delete; - LowEnergyClientTest& operator=(const LowEnergyClientTest&) = delete; - - ~LowEnergyClientTest() override = default; - - void SetUp() override { - // Only set |mock_handler_| if a test hasn't set it. - if (!mock_handler_) mock_handler_.reset(new MockGattHandler()); - fake_hal_gatt_iface_ = new hal::FakeBluetoothGattInterface( - nullptr, nullptr, - std::static_pointer_cast< - hal::FakeBluetoothGattInterface::TestClientHandler>(mock_handler_), - nullptr); - hal::BluetoothGattInterface::InitializeForTesting(fake_hal_gatt_iface_); - ble_factory_.reset(new LowEnergyClientFactory(mock_adapter_)); - } - - void TearDown() override { - ble_factory_.reset(); - hal::BluetoothGattInterface::CleanUp(); - } - - protected: - hal::FakeBluetoothGattInterface* fake_hal_gatt_iface_; - testing::MockAdapter mock_adapter_; - std::shared_ptr<MockGattHandler> mock_handler_; - std::unique_ptr<LowEnergyClientFactory> ble_factory_; -}; - -// Used for tests that operate on a pre-registered client. -class LowEnergyClientPostRegisterTest : public LowEnergyClientTest { - public: - LowEnergyClientPostRegisterTest() : next_client_id_(0) {} - - LowEnergyClientPostRegisterTest(const LowEnergyClientPostRegisterTest&) = - delete; - LowEnergyClientPostRegisterTest& operator=( - const LowEnergyClientPostRegisterTest&) = delete; - - ~LowEnergyClientPostRegisterTest() override = default; - - void SetUp() override { - LowEnergyClientTest::SetUp(); - auto callback = [&](std::unique_ptr<LowEnergyClient> client) { - le_client_ = std::move(client); - }; - RegisterTestClient(callback); - } - - void TearDown() override { - EXPECT_CALL(*mock_handler_, UnregisterClient(_)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - le_client_.reset(); - LowEnergyClientTest::TearDown(); - } - - void RegisterTestClient( - const std::function<void(std::unique_ptr<LowEnergyClient> client)> - callback) { - Uuid uuid = Uuid::GetRandom(); - auto api_callback = [&](BLEStatus status, const Uuid& in_uuid, - std::unique_ptr<BluetoothInstance> in_client) { - CHECK(in_uuid == uuid); - CHECK(in_client.get()); - CHECK(status == BLE_STATUS_SUCCESS); - - callback(std::unique_ptr<LowEnergyClient>( - static_cast<LowEnergyClient*>(in_client.release()))); - }; - - EXPECT_CALL(*mock_handler_, RegisterClient(_, _)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - - ble_factory_->RegisterInstance(uuid, api_callback); - - fake_hal_gatt_iface_->NotifyRegisterClientCallback(0, next_client_id_++, - uuid); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - } - - protected: - std::unique_ptr<LowEnergyClient> le_client_; - - private: - int next_client_id_; -}; - -TEST_F(LowEnergyClientTest, RegisterInstance) { - EXPECT_CALL(*mock_handler_, RegisterClient(_, _)) - .Times(2) - .WillOnce(Return(BT_STATUS_FAIL)) - .WillOnce(Return(BT_STATUS_SUCCESS)); - - // These will be asynchronously populated with a result when the callback - // executes. - BLEStatus status = BLE_STATUS_SUCCESS; - Uuid cb_uuid; - std::unique_ptr<LowEnergyClient> client; - int callback_count = 0; - - auto callback = [&](BLEStatus in_status, const Uuid& uuid, - std::unique_ptr<BluetoothInstance> in_client) { - status = in_status; - cb_uuid = uuid; - client = std::unique_ptr<LowEnergyClient>( - static_cast<LowEnergyClient*>(in_client.release())); - callback_count++; - }; - - Uuid uuid0 = Uuid::GetRandom(); - - // HAL returns failure. - EXPECT_FALSE(ble_factory_->RegisterInstance(uuid0, callback)); - EXPECT_EQ(0, callback_count); - - // HAL returns success. - EXPECT_TRUE(ble_factory_->RegisterInstance(uuid0, callback)); - EXPECT_EQ(0, callback_count); - - // Calling twice with the same Uuid should fail with no additional call into - // the stack. - EXPECT_FALSE(ble_factory_->RegisterInstance(uuid0, callback)); - - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // Call with a different Uuid while one is pending. - Uuid uuid1 = Uuid::GetRandom(); - EXPECT_CALL(*mock_handler_, RegisterClient(_, _)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - EXPECT_TRUE(ble_factory_->RegisterInstance(uuid1, callback)); - - // Trigger callback with an unknown Uuid. This should get ignored. - Uuid uuid2 = Uuid::GetRandom(); - fake_hal_gatt_iface_->NotifyRegisterClientCallback(0, 0, uuid2); - EXPECT_EQ(0, callback_count); - - // |uuid0| succeeds. - int client_if0 = 2; // Pick something that's not 0. - fake_hal_gatt_iface_->NotifyRegisterClientCallback(BT_STATUS_SUCCESS, - client_if0, uuid0); - - EXPECT_EQ(1, callback_count); - ASSERT_TRUE(client.get() != nullptr); // Assert to terminate in case of error - EXPECT_EQ(BLE_STATUS_SUCCESS, status); - EXPECT_EQ(client_if0, client->GetInstanceId()); - EXPECT_EQ(uuid0, client->GetAppIdentifier()); - EXPECT_EQ(uuid0, cb_uuid); - - // The client should unregister itself when deleted. - EXPECT_CALL(*mock_handler_, UnregisterClient(client_if0)) - .Times(1) - .WillOnce(Return(BT_STATUS_SUCCESS)); - client.reset(); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // |uuid1| fails. - int client_if1 = 3; - fake_hal_gatt_iface_->NotifyRegisterClientCallback(BT_STATUS_FAIL, client_if1, - uuid1); - - EXPECT_EQ(2, callback_count); - ASSERT_TRUE(client.get() == nullptr); // Assert to terminate in case of error - EXPECT_EQ(BLE_STATUS_FAILURE, status); - EXPECT_EQ(uuid1, cb_uuid); -} - -MATCHER_P(BitEq, x, std::string(negation ? "isn't" : "is") + - " bitwise equal to " + ::testing::PrintToString(x)) { - static_assert(sizeof(x) == sizeof(arg), "Size mismatch"); - return std::memcmp(&arg, &x, sizeof(x)) == 0; -} - -TEST_F(LowEnergyClientPostRegisterTest, Connect) { - const RawAddress kTestAddress = {{0x01, 0x02, 0x03, 0x0A, 0x0B, 0x0C}}; - const char kTestAddressStr[] = "01:02:03:0A:0B:0C"; - const bool kTestDirect = false; - const int connId = 12; - - TestDelegate delegate; - le_client_->SetDelegate(&delegate); - - // TODO(jpawlowski): NotifyConnectCallback should be called after returning - // success, fix it when it becomes important. - // These should succeed and result in a HAL call - EXPECT_CALL(*mock_handler_, - Connect(le_client_->GetInstanceId(), BitEq(kTestAddress), - kTestDirect, BT_TRANSPORT_LE)) - .Times(1) - .WillOnce(DoAll(Invoke([&](int client_id, const RawAddress& bd_addr, - bool is_direct, int transport) { - fake_hal_gatt_iface_->NotifyConnectCallback( - connId, BT_STATUS_SUCCESS, client_id, bd_addr); - }), - Return(BT_STATUS_SUCCESS))); - - EXPECT_TRUE(le_client_->Connect(kTestAddressStr, kTestDirect)); - EXPECT_EQ(1, delegate.connection_state_count()); - - // TODO(jpawlowski): same as above - // These should succeed and result in a HAL call - EXPECT_CALL(*mock_handler_, Disconnect(le_client_->GetInstanceId(), - BitEq(kTestAddress), connId)) - .Times(1) - .WillOnce(DoAll( - Invoke([&](int client_id, const RawAddress& bd_addr, int connId) { - fake_hal_gatt_iface_->NotifyDisconnectCallback( - connId, BT_STATUS_SUCCESS, client_id, bd_addr); - }), - Return(BT_STATUS_SUCCESS))); - - EXPECT_TRUE(le_client_->Disconnect(kTestAddressStr)); - EXPECT_EQ(2, delegate.connection_state_count()); - - le_client_->SetDelegate(nullptr); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); -} - -} // namespace -} // namespace bluetooth diff --git a/system/service/test/low_energy_scanner_unittest.cc b/system/service/test/low_energy_scanner_unittest.cc deleted file mode 100644 index 828e4449eb..0000000000 --- a/system/service/test/low_energy_scanner_unittest.cc +++ /dev/null @@ -1,380 +0,0 @@ -// -// Copyright 2016 The Android Open Source Project -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/low_energy_scanner.h" - -#include <gmock/gmock.h> -#include <gtest/gtest.h> - -#include <memory> - -#include "service/adapter.h" -#include "service/hal/fake_bluetooth_gatt_interface.h" -#include "stack/include/bt_types.h" -#include "test/mock_adapter.h" -#include "types/raw_address.h" - -using ::testing::_; -using ::testing::Return; -using ::testing::Pointee; -using ::testing::DoAll; -using ::testing::Invoke; -using ::testing::SaveArg; - -namespace bluetooth { -namespace { - -class MockScannerHandler : public BleScannerInterface { - public: - MockScannerHandler() {} - ~MockScannerHandler() override = default; - - MOCK_METHOD2(RegisterScanner, void(const bluetooth::Uuid& app_uuid, - BleScannerInterface::RegisterCallback)); - MOCK_METHOD1(Unregister, void(int)); - MOCK_METHOD1(Scan, void(bool)); - - MOCK_METHOD5(ScanFilterParamSetupImpl, - void(uint8_t client_if, uint8_t action, uint8_t filt_index, - btgatt_filt_param_setup_t* filt_param, - FilterParamSetupCallback cb)); - MOCK_METHOD2(ScanFilterClear, void(int filt_index, FilterConfigCallback cb)); - MOCK_METHOD2(ScanFilterEnable, void(bool enable, EnableCallback cb)); - MOCK_METHOD4(SetScanParameters, void(int scanner_id, int scan_interval, - int scan_window, Callback cb)); - - MOCK_METHOD5(BatchscanConfigStorage, - void(int client_if, int batch_scan_full_max, - int batch_scan_trunc_max, int batch_scan_notify_threshold, - Callback cb)); - - MOCK_METHOD6(BatchscanEnable, - void(int scan_mode, int scan_interval, int scan_window, - int addr_type, int discard_rule, Callback cb)); - - MOCK_METHOD1(BatchscanDisable, void(Callback cb)); - - MOCK_METHOD2(BatchscanReadReports, void(int client_if, int scan_mode)); - - MOCK_METHOD5(StartSync, void(uint8_t, RawAddress, uint16_t, uint16_t, int)); - MOCK_METHOD1(StopSync, void(uint16_t)); - - MOCK_METHOD1(RegisterCallbacks, void(ScanningCallbacks* callbacks)); - - MOCK_METHOD2(CancelCreateSync, void(uint8_t, RawAddress)); - - MOCK_METHOD4(TransferSync, void(RawAddress, uint16_t, uint16_t, int)); - - MOCK_METHOD4(TransferSetInfo, void(RawAddress, uint16_t, uint8_t, int)); - - MOCK_METHOD5(SyncTxParameters, - void(RawAddress, uint8_t, uint16_t, uint16_t, int)); - - void ScanFilterAdd(int filter_index, std::vector<ApcfCommand> filters, - FilterConfigCallback cb) override{}; - - void ScanFilterParamSetup( - uint8_t client_if, uint8_t action, uint8_t filt_index, - std::unique_ptr<btgatt_filt_param_setup_t> filt_param, - FilterParamSetupCallback cb) override { - ScanFilterParamSetupImpl(client_if, action, filt_index, filt_param.get(), - std::move(cb)); - } - - bool IsMsftSupported() { return false; } - - void MsftAdvMonitorAdd(MsftAdvMonitor monitor, - MsftAdvMonitorAddCallback cb) override{}; - - void MsftAdvMonitorRemove(uint8_t monitor_handle, - MsftAdvMonitorRemoveCallback cb) override{}; - - void MsftAdvMonitorEnable(bool enable, - MsftAdvMonitorEnableCallback cb) override{}; -}; - -class TestDelegate : public LowEnergyScanner::Delegate { - public: - TestDelegate() : scan_result_count_(0) {} - - TestDelegate(const TestDelegate&) = delete; - TestDelegate& operator=(const TestDelegate&) = delete; - - ~TestDelegate() override = default; - - int scan_result_count() const { return scan_result_count_; } - const ScanResult& last_scan_result() const { return last_scan_result_; } - - void OnScanResult(LowEnergyScanner* scanner, - const ScanResult& scan_result) override { - ASSERT_TRUE(scanner); - scan_result_count_++; - last_scan_result_ = scan_result; - } - - private: - int scan_result_count_; - ScanResult last_scan_result_; -}; - -class LowEnergyScannerTest : public ::testing::Test { - public: - LowEnergyScannerTest() = default; - LowEnergyScannerTest(const LowEnergyScannerTest&) = delete; - LowEnergyScannerTest& operator=(const LowEnergyScannerTest&) = delete; - - ~LowEnergyScannerTest() override = default; - - void SetUp() override { - // Only set |mock_handler_| if a test hasn't set it. - if (!mock_handler_) mock_handler_.reset(new MockScannerHandler()); - fake_hal_gatt_iface_ = new hal::FakeBluetoothGattInterface( - nullptr, std::static_pointer_cast<BleScannerInterface>(mock_handler_), - nullptr, nullptr); - hal::BluetoothGattInterface::InitializeForTesting(fake_hal_gatt_iface_); - ble_factory_.reset(new LowEnergyScannerFactory(mock_adapter_)); - } - - void TearDown() override { - ble_factory_.reset(); - hal::BluetoothGattInterface::CleanUp(); - } - - protected: - hal::FakeBluetoothGattInterface* fake_hal_gatt_iface_; - testing::MockAdapter mock_adapter_; - std::shared_ptr<MockScannerHandler> mock_handler_; - std::unique_ptr<LowEnergyScannerFactory> ble_factory_; -}; - -// Used for tests that operate on a pre-registered scanner. -class LowEnergyScannerPostRegisterTest : public LowEnergyScannerTest { - public: - LowEnergyScannerPostRegisterTest() : next_scanner_id_(0) {} - - LowEnergyScannerPostRegisterTest(const LowEnergyScannerPostRegisterTest&) = - delete; - LowEnergyScannerPostRegisterTest& operator=( - const LowEnergyScannerPostRegisterTest&) = delete; - - ~LowEnergyScannerPostRegisterTest() override = default; - - void SetUp() override { - LowEnergyScannerTest::SetUp(); - auto callback = [&](std::unique_ptr<LowEnergyScanner> scanner) { - le_scanner_ = std::move(scanner); - }; - RegisterTestScanner(callback); - } - - void TearDown() override { - EXPECT_CALL(*mock_handler_, Unregister(_)).Times(1).WillOnce(Return()); - le_scanner_.reset(); - LowEnergyScannerTest::TearDown(); - } - - void RegisterTestScanner( - const std::function<void(std::unique_ptr<LowEnergyScanner> scanner)> - callback) { - Uuid uuid = Uuid::GetRandom(); - auto api_callback = [&](BLEStatus status, const Uuid& in_uuid, - std::unique_ptr<BluetoothInstance> in_scanner) { - CHECK(in_uuid == uuid); - CHECK(in_scanner.get()); - CHECK(status == BLE_STATUS_SUCCESS); - - callback(std::unique_ptr<LowEnergyScanner>( - static_cast<LowEnergyScanner*>(in_scanner.release()))); - }; - - BleScannerInterface::RegisterCallback reg_scanner_cb; - Uuid uuid_empty; - EXPECT_CALL(*mock_handler_, RegisterScanner(_, _)) - .Times(1) - .WillOnce(DoAll(SaveArg<0>(&uuid_empty), SaveArg<1>(®_scanner_cb))); - - ble_factory_->RegisterInstance(uuid, api_callback); - - reg_scanner_cb.Run(next_scanner_id_++, BT_STATUS_SUCCESS); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - } - - protected: - std::unique_ptr<LowEnergyScanner> le_scanner_; - - private: - int next_scanner_id_; -}; - -TEST_F(LowEnergyScannerTest, RegisterInstance) { - BleScannerInterface::RegisterCallback reg_scanner_cb1; - Uuid uuid_empty1; - EXPECT_CALL(*mock_handler_, RegisterScanner(_, _)) - .Times(1) - .WillOnce(DoAll(SaveArg<0>(&uuid_empty1), SaveArg<1>(®_scanner_cb1))); - - // These will be asynchronously populated with a result when the callback - // executes. - BLEStatus status = BLE_STATUS_SUCCESS; - Uuid cb_uuid; - std::unique_ptr<LowEnergyScanner> scanner; - int callback_count = 0; - - auto callback = [&](BLEStatus in_status, const Uuid& uuid, - std::unique_ptr<BluetoothInstance> in_scanner) { - status = in_status; - cb_uuid = uuid; - scanner = std::unique_ptr<LowEnergyScanner>( - static_cast<LowEnergyScanner*>(in_scanner.release())); - callback_count++; - }; - - Uuid uuid0 = Uuid::GetRandom(); - - // HAL returns success. - EXPECT_TRUE(ble_factory_->RegisterInstance(uuid0, callback)); - EXPECT_EQ(0, callback_count); - - // Calling twice with the same Uuid should fail with no additional call into - // the stack. - EXPECT_FALSE(ble_factory_->RegisterInstance(uuid0, callback)); - - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // Call with a different Uuid while one is pending. - Uuid uuid1 = Uuid::GetRandom(); - BleScannerInterface::RegisterCallback reg_scanner_cb2; - Uuid uuid_empty2; - EXPECT_CALL(*mock_handler_, RegisterScanner(_, _)) - .Times(1) - .WillOnce(DoAll(SaveArg<0>(&uuid_empty2), SaveArg<1>(®_scanner_cb2))); - EXPECT_TRUE(ble_factory_->RegisterInstance(uuid1, callback)); - - // |uuid0| succeeds. - int scanner_if0 = 2; // Pick something that's not 0. - reg_scanner_cb1.Run(scanner_if0, BT_STATUS_SUCCESS); - - EXPECT_EQ(1, callback_count); - ASSERT_TRUE(scanner.get() != - nullptr); // Assert to terminate in case of error - EXPECT_EQ(BLE_STATUS_SUCCESS, status); - EXPECT_EQ(scanner_if0, scanner->GetInstanceId()); - EXPECT_EQ(uuid0, scanner->GetAppIdentifier()); - EXPECT_EQ(uuid0, cb_uuid); - - // The scanner should unregister itself when deleted. - EXPECT_CALL(*mock_handler_, Unregister(scanner_if0)) - .Times(1) - .WillOnce(Return()); - scanner.reset(); - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); - - // |uuid1| fails. - int scanner_if1 = 3; - reg_scanner_cb2.Run(scanner_if1, BT_STATUS_FAIL); - - EXPECT_EQ(2, callback_count); - ASSERT_TRUE(scanner.get() == - nullptr); // Assert to terminate in case of error - EXPECT_EQ(BLE_STATUS_FAILURE, status); - EXPECT_EQ(uuid1, cb_uuid); -} - -TEST_F(LowEnergyScannerPostRegisterTest, ScanSettings) { - EXPECT_CALL(mock_adapter_, IsEnabled()) - .WillOnce(Return(false)) - .WillRepeatedly(Return(true)); - - ScanSettings settings; - std::vector<ScanFilter> filters; - - // Adapter is not enabled. - EXPECT_FALSE(le_scanner_->StartScan(settings, filters)); - - // TODO(jpawlowski): add tests checking settings and filter parsing when - // implemented - - // These should succeed and result in a HAL call - EXPECT_CALL(*mock_handler_, Scan(true)).Times(1).WillOnce(Return()); - EXPECT_TRUE(le_scanner_->StartScan(settings, filters)); - - // These should succeed and result in a HAL call - EXPECT_CALL(*mock_handler_, Scan(false)).Times(1).WillOnce(Return()); - EXPECT_TRUE(le_scanner_->StopScan()); - - ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get()); -} - -TEST_F(LowEnergyScannerPostRegisterTest, ScanRecord) { - TestDelegate delegate; - le_scanner_->SetDelegate(&delegate); - - EXPECT_EQ(0, delegate.scan_result_count()); - - std::vector<uint8_t> kTestRecord0({0x02, 0x01, 0x00, 0x00}); - std::vector<uint8_t> kTestRecord1({0x00}); - std::vector<uint8_t> kTestRecord2( - {0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, - 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, - 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, - 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, - 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, - 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00}); - const RawAddress kTestAddress = {{0x01, 0x02, 0x03, 0x0A, 0x0B, 0x0C}}; - const char kTestAddressStr[] = "01:02:03:0A:0B:0C"; - const int kTestRssi = 64; - - // Scan wasn't started. Result should be ignored. - fake_hal_gatt_iface_->NotifyScanResultCallback(kTestAddress, kTestRssi, - kTestRecord0); - EXPECT_EQ(0, delegate.scan_result_count()); - - // Start a scan session for |le_scanner_|. - EXPECT_CALL(mock_adapter_, IsEnabled()).Times(1).WillOnce(Return(true)); - EXPECT_CALL(*mock_handler_, Scan(_)) - .Times(2) - .WillOnce(Return()) - .WillOnce(Return()); - ScanSettings settings; - std::vector<ScanFilter> filters; - ASSERT_TRUE(le_scanner_->StartScan(settings, filters)); - - fake_hal_gatt_iface_->NotifyScanResultCallback(kTestAddress, kTestRssi, - kTestRecord0); - EXPECT_EQ(1, delegate.scan_result_count()); - EXPECT_EQ(kTestAddressStr, delegate.last_scan_result().device_address()); - EXPECT_EQ(kTestRssi, delegate.last_scan_result().rssi()); - EXPECT_EQ(3U, delegate.last_scan_result().scan_record().size()); - - fake_hal_gatt_iface_->NotifyScanResultCallback(kTestAddress, kTestRssi, - kTestRecord1); - EXPECT_EQ(2, delegate.scan_result_count()); - EXPECT_EQ(kTestAddressStr, delegate.last_scan_result().device_address()); - EXPECT_EQ(kTestRssi, delegate.last_scan_result().rssi()); - EXPECT_TRUE(delegate.last_scan_result().scan_record().empty()); - - fake_hal_gatt_iface_->NotifyScanResultCallback(kTestAddress, kTestRssi, - kTestRecord2); - EXPECT_EQ(3, delegate.scan_result_count()); - EXPECT_EQ(kTestAddressStr, delegate.last_scan_result().device_address()); - EXPECT_EQ(kTestRssi, delegate.last_scan_result().rssi()); - EXPECT_EQ(62U, delegate.last_scan_result().scan_record().size()); - - le_scanner_->SetDelegate(nullptr); -} - -} // namespace -} // namespace bluetooth diff --git a/system/service/test/main.cc b/system/service/test/main.cc deleted file mode 100644 index d9a173505c..0000000000 --- a/system/service/test/main.cc +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include <base/at_exit.h> -#include <base/command_line.h> -#include <base/logging.h> - -#include <gtest/gtest.h> - -GTEST_API_ int main(int argc, char** argv) { - base::AtExitManager exit_manager; - base::CommandLine::Init(argc, argv); - logging::LoggingSettings log_settings; - logging::InitLogging(log_settings); - - LOG(INFO) << "Running Bluetooth daemon unit tests."; - testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} diff --git a/system/service/test/mock_adapter.h b/system/service/test/mock_adapter.h deleted file mode 100644 index 4042f6a975..0000000000 --- a/system/service/test/mock_adapter.h +++ /dev/null @@ -1,69 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <gmock/gmock.h> - -#include "service/daemon.h" - -namespace bluetooth { -namespace testing { - -class MockAdapter : public Adapter { - public: - MockAdapter() = default; - MockAdapter(const MockAdapter&) = delete; - MockAdapter& operator=(const MockAdapter&) = delete; - - ~MockAdapter() override = default; - - MOCK_METHOD1(AddObserver, void(Observer*)); - MOCK_METHOD1(RemoveObserver, void(Observer*)); - MOCK_CONST_METHOD0(GetState, AdapterState()); - MOCK_CONST_METHOD0(IsEnabled, bool()); - MOCK_METHOD0(Enable, bool()); - MOCK_METHOD0(Disable, bool()); - MOCK_CONST_METHOD0(GetName, std::string()); - MOCK_METHOD1(SetName, bool(const std::string&)); - MOCK_CONST_METHOD0(GetAddress, std::string()); - MOCK_METHOD1(SetScanMode, bool(int)); - MOCK_METHOD1(SetScanEnable, bool(bool)); - MOCK_METHOD4(SspReply, bool(const std::string&, int, bool, int32_t)); - MOCK_METHOD2(CreateBond, - bool(const std::string& device_address, int transport)); - MOCK_METHOD0(IsMultiAdvertisementSupported, bool()); - MOCK_METHOD1(IsDeviceConnected, bool(const std::string&)); - MOCK_METHOD0(GetTotalNumberOfTrackableAdvertisements, int()); - MOCK_METHOD0(IsOffloadedFilteringSupported, bool()); - MOCK_METHOD0(IsOffloadedScanBatchingSupported, bool()); - MOCK_METHOD0(GetBondedDevices, bool()); - MOCK_METHOD1(RemoveBond, bool(const std::string&)); - MOCK_METHOD1(GetRemoteDeviceProperties, - bool(const std::string& device_address)); - MOCK_CONST_METHOD0(GetA2dpSinkFactory, A2dpSinkFactory*()); - MOCK_CONST_METHOD0(GetA2dpSourceFactory, A2dpSourceFactory*()); - MOCK_CONST_METHOD0(GetAvrcpControlFactory, AvrcpControlFactory*()); - MOCK_CONST_METHOD0(GetAvrcpTargetFactory, AvrcpTargetFactory*()); - MOCK_CONST_METHOD0(GetLowEnergyClientFactory, LowEnergyClientFactory*()); - MOCK_CONST_METHOD0(GetLeAdvertiserFactory, LowEnergyAdvertiserFactory*()); - MOCK_CONST_METHOD0(GetLeScannerFactory, LowEnergyScannerFactory*()); - MOCK_CONST_METHOD0(GetGattClientFactory, GattClientFactory*()); - MOCK_CONST_METHOD0(GetGattServerFactory, GattServerFactory*()); -}; - -} // namespace testing -} // namespace bluetooth diff --git a/system/service/test/mock_daemon.h b/system/service/test/mock_daemon.h deleted file mode 100644 index 410b962b52..0000000000 --- a/system/service/test/mock_daemon.h +++ /dev/null @@ -1,42 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#pragma once - -#include <gmock/gmock.h> - -#include "abstract_message_loop.h" -#include "service/daemon.h" - -namespace bluetooth { -namespace testing { - -class MockDaemon : public Daemon { - public: - MockDaemon() = default; - MockDaemon(const MockDaemon&) = delete; - MockDaemon& operator=(const MockDaemon&) = delete; - - ~MockDaemon() override = default; - - MOCK_CONST_METHOD0(GetSettings, Settings*()); - MOCK_CONST_METHOD0(GetMessageLoop, btbase::AbstractMessageLoop*()); - MOCK_METHOD0(StartMainLoop, void()); - MOCK_METHOD0(Init, bool()); -}; - -} // namespace testing -} // namespace bluetooth diff --git a/system/service/test/parcelable_unittest.cc b/system/service/test/parcelable_unittest.cc deleted file mode 100644 index 84e67aa1bc..0000000000 --- a/system/service/test/parcelable_unittest.cc +++ /dev/null @@ -1,219 +0,0 @@ -// -// Copyright 2016 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include <gtest/gtest.h> - -#include "service/common/android/bluetooth/advertise_data.h" -#include "service/common/android/bluetooth/advertise_settings.h" -#include "service/common/android/bluetooth/bluetooth_gatt_characteristic.h" -#include "service/common/android/bluetooth/bluetooth_gatt_descriptor.h" -#include "service/common/android/bluetooth/bluetooth_gatt_service.h" -#include "service/common/android/bluetooth/scan_filter.h" -#include "service/common/android/bluetooth/scan_result.h" -#include "service/common/android/bluetooth/scan_settings.h" -#include "service/common/android/bluetooth/uuid.h" -#include "service/common/bluetooth/low_energy_constants.h" - -using android::Parcel; - -using bluetooth::AdvertiseData; -using bluetooth::AdvertiseSettings; -using bluetooth::Characteristic; -using bluetooth::Descriptor; -using bluetooth::ScanFilter; -using bluetooth::ScanResult; -using bluetooth::ScanSettings; -using bluetooth::Service; -using bluetooth::Uuid; - -namespace bluetooth { -namespace { - -template <class IN, class OUT> -bool TestData(IN& in) { - Parcel parcel; - - parcel.writeParcelable((OUT)in); - parcel.setDataPosition(0); - OUT out; - parcel.readParcelable(&out); - // in case of error this display nice log message - EXPECT_EQ(out, in); - return in == out; -} - -TEST(ParcelableTest, NonEmptyAdvertiseData) { - std::vector<uint8_t> data{0x02, 0x02, 0x00}; - AdvertiseData adv0(data); - bool result = - TestData<AdvertiseData, android::bluetooth::AdvertiseData>(adv0); - EXPECT_TRUE(result); -} - -TEST(ParcelableTest, DefaultAdvertiseSettings) { - AdvertiseSettings settings; - bool result = - TestData<AdvertiseSettings, android::bluetooth::AdvertiseSettings>( - settings); - EXPECT_TRUE(result); -} - -TEST(ParcelableTest, NonEmptyAdvertiseSettings) { - AdvertiseSettings settings( -#if BASE_VER < 931007 - AdvertiseSettings::MODE_BALANCED, base::TimeDelta::FromMilliseconds(150), -#else - AdvertiseSettings::MODE_BALANCED, base::Milliseconds(150), -#endif - AdvertiseSettings::TX_POWER_LEVEL_HIGH, false /* connectable */); - - bool result = - TestData<AdvertiseSettings, android::bluetooth::AdvertiseSettings>( - settings); - EXPECT_TRUE(result); -} - -TEST(ParcelableTest, Uuid) { - // Try a whole bunch of Uuids. - for (int i = 0; i < 10; i++) { - Uuid uuid = Uuid::GetRandom(); - TestData<Uuid, android::bluetooth::UUID>(uuid); - } -} - -TEST(ParcelableTest, ScanSettings) { - ScanSettings settings0; - ScanSettings settings1( - ScanSettings::MODE_BALANCED, ScanSettings::CALLBACK_TYPE_FIRST_MATCH, - ScanSettings::RESULT_TYPE_ABBREVIATED, -#if BASE_VER < 931007 - base::TimeDelta::FromMilliseconds(150), ScanSettings::MATCH_MODE_STICKY, -#else - base::Milliseconds(150), ScanSettings::MATCH_MODE_STICKY, -#endif - ScanSettings::MATCH_COUNT_FEW_ADVERTISEMENTS); - - bool result = - TestData<ScanSettings, android::bluetooth::ScanSettings>(settings0); - EXPECT_TRUE(result); - - result = TestData<ScanSettings, android::bluetooth::ScanSettings>(settings0); - EXPECT_TRUE(result); -} - -TEST(ParcelableTest, ScanFilter) { - ScanFilter filter; - - filter.set_device_name("Test Device Name"); - ASSERT_TRUE(filter.SetDeviceAddress("01:02:04:AB:CD:EF")); - - bool result = TestData<ScanFilter, android::bluetooth::ScanFilter>(filter); - EXPECT_TRUE(result); - - Uuid uuid = Uuid::GetRandom(); - filter.SetServiceUuid(uuid); - - result = TestData<ScanFilter, android::bluetooth::ScanFilter>(filter); - EXPECT_TRUE(result); - - Uuid mask = Uuid::GetRandom(); - filter.SetServiceUuidWithMask(uuid, mask); - result = TestData<ScanFilter, android::bluetooth::ScanFilter>(filter); - EXPECT_TRUE(result); -} - -TEST(ParcelableTest, ScanResult) { - const char kTestAddress[] = "01:02:03:AB:CD:EF"; - - const std::vector<uint8_t> kEmptyBytes; - const std::vector<uint8_t> kTestBytes{0x01, 0x02, 0x03}; - - const int kTestRssi = 127; - - ScanResult result0(kTestAddress, kEmptyBytes, kTestRssi); - ScanResult result1(kTestAddress, kTestBytes, kTestRssi); - - bool result = TestData<ScanResult, android::bluetooth::ScanResult>(result0); - EXPECT_TRUE(result); - - result = TestData<ScanResult, android::bluetooth::ScanResult>(result1); - EXPECT_TRUE(result); -} - -TEST(ParcelableTest, GattDescriptor) { - Descriptor s = Descriptor(0x0000, Uuid::GetRandom(), - bluetooth::kAttributePermissionRead); - Descriptor s2 = Descriptor(0xFFFE, Uuid::GetRandom(), - bluetooth::kAttributePermissionWrite); - Descriptor s3 = Descriptor(0x003D, Uuid::GetRandom(), - bluetooth::kAttributePermissionReadEncryptedMITM | - bluetooth::kAttributePermissionRead); - - bool result = - TestData<Descriptor, android::bluetooth::BluetoothGattDescriptor>(s); - EXPECT_TRUE(result); - - result = - TestData<Descriptor, android::bluetooth::BluetoothGattDescriptor>(s2); - EXPECT_TRUE(result); - - result = - TestData<Descriptor, android::bluetooth::BluetoothGattDescriptor>(s3); - EXPECT_TRUE(result); -} - -TEST(ParcelableTest, GattCharacteristic) { - Characteristic c = Characteristic(0x0004, Uuid::GetRandom(), 0, 0, - {Descriptor(0x0005, Uuid::GetRandom(), 0), - Descriptor(0x0007, Uuid::GetRandom(), 0), - Descriptor(0x00A1, Uuid::GetRandom(), 0)}); - - bool result = - TestData<Characteristic, android::bluetooth::BluetoothGattCharacteristic>( - c); - EXPECT_TRUE(result); -} - -TEST(ParcelableTest, GattService) { - Service s = - Service(0x0001, true, Uuid::FromString("CAFE", nullptr), - {Characteristic(0x0004, Uuid::GetRandom(), - bluetooth::kCharacteristicPropertyNotify, - bluetooth::kAttributePermissionRead, - {Descriptor(0x0005, Uuid::GetRandom(), 0), - Descriptor(0x0007, Uuid::GetRandom(), 0), - Descriptor(0x0009, Uuid::GetRandom(), 0)}), - Characteristic(0x000D, Uuid::GetRandom(), - bluetooth::kCharacteristicPropertyWrite, - bluetooth::kAttributePermissionWrite, - {Descriptor(0x0010, Uuid::GetRandom(), 0), - Descriptor(0x0012, Uuid::GetRandom(), 0)}), - Characteristic(0x0015, Uuid::GetRandom(), 0, 0, {})}, - {}); - - Parcel parcel; - - parcel.writeParcelable((android::bluetooth::BluetoothGattService)s); - parcel.setDataPosition(0); - android::bluetooth::BluetoothGattService out; - parcel.readParcelable(&out); - - bool result = TestData<Service, android::bluetooth::BluetoothGattService>(s); - EXPECT_TRUE(result); -} - -} // namespace -} // namespace bluetooth diff --git a/system/service/test/settings_unittest.cc b/system/service/test/settings_unittest.cc deleted file mode 100644 index 31baaaaad8..0000000000 --- a/system/service/test/settings_unittest.cc +++ /dev/null @@ -1,99 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include <base/at_exit.h> -#include <base/command_line.h> -#include <gtest/gtest.h> - -#include "array_utils.h" -#include "service/settings.h" -#include "service/switches.h" - -using bluetooth::Settings; -using namespace bluetooth::switches; - -namespace { - -class SettingsTest : public ::testing::Test { - public: - SettingsTest() = default; - SettingsTest(const SettingsTest&) = delete; - SettingsTest& operator=(const SettingsTest&) = delete; - - void SetUp() override { base::CommandLine::Reset(); } - - void TearDown() override { base::CommandLine::Reset(); } - - protected: - base::AtExitManager exit_manager_; - Settings settings_; -}; - -TEST_F(SettingsTest, EmptyCommandLine) { - const base::CommandLine::CharType* argv[] = {"program"}; - EXPECT_TRUE(base::CommandLine::Init(ARRAY_SIZE(argv), argv)); - EXPECT_TRUE(settings_.Init()); -} - -TEST_F(SettingsTest, UnexpectedSwitches1) { - const base::CommandLine::CharType* argv[] = { - "program", "--create-ipc-socket=foobar", "--foobarbaz"}; - EXPECT_TRUE(base::CommandLine::Init(ARRAY_SIZE(argv), argv)); - EXPECT_FALSE(settings_.Init()); -} - -TEST_F(SettingsTest, UnexpectedSwitches2) { - const base::CommandLine::CharType* argv[] = {"program", "--foobarbaz"}; - EXPECT_TRUE(base::CommandLine::Init(ARRAY_SIZE(argv), argv)); - EXPECT_FALSE(settings_.Init()); -} - -TEST_F(SettingsTest, UnexpectedArguments1) { - const base::CommandLine::CharType* argv[] = {"program", "foobarbaz"}; - EXPECT_TRUE(base::CommandLine::Init(ARRAY_SIZE(argv), argv)); - EXPECT_FALSE(settings_.Init()); -} - -TEST_F(SettingsTest, UnexpectedArguments2) { - const base::CommandLine::CharType* argv[] = { - "program", "--create-ipc-socket=foobar", "foobarbaz"}; - EXPECT_TRUE(base::CommandLine::Init(ARRAY_SIZE(argv), argv)); - EXPECT_FALSE(settings_.Init()); -} - -TEST_F(SettingsTest, TooManyIpcOptions) { - const base::CommandLine::CharType* argv[] = { - "program", "--create-ipc-socket=foobar", - "--android-ipc-socket-suffix=foobar"}; - EXPECT_TRUE(base::CommandLine::Init(ARRAY_SIZE(argv), argv)); - EXPECT_FALSE(settings_.Init()); -} - -TEST_F(SettingsTest, GoodArgumentsCreateIpc) { - const base::CommandLine::CharType* argv[] = {"program", - "--create-ipc-socket=foobar"}; - EXPECT_TRUE(base::CommandLine::Init(ARRAY_SIZE(argv), argv)); - EXPECT_TRUE(settings_.Init()); -} - -TEST_F(SettingsTest, GoodArgumentsAndroidIpc) { - const base::CommandLine::CharType* argv[] = { - "program", "--android-ipc-socket-suffix=foobar"}; - EXPECT_TRUE(base::CommandLine::Init(ARRAY_SIZE(argv), argv)); - EXPECT_TRUE(settings_.Init()); -} - -} // namespace diff --git a/system/service/test/stub_ipc_handler_binder.cc b/system/service/test/stub_ipc_handler_binder.cc deleted file mode 100644 index 2fb450f147..0000000000 --- a/system/service/test/stub_ipc_handler_binder.cc +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright 2015 Google, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "service/ipc/binder/ipc_handler_binder.h" - -// TODO(armansito): This is a crappy workaround to link IPCHandlerBinder into -// host-native unit tests. We should instead figure out a way to build Binder -// unit tests for host. - -namespace ipc { - -IPCHandlerBinder::IPCHandlerBinder(bluetooth::Adapter* adapter, - IPCManager::Delegate* delegate) - : IPCHandler(adapter, delegate) { - // Stub -} - -IPCHandlerBinder::~IPCHandlerBinder() { - // Stub -} - -bool IPCHandlerBinder::Run() { - // Stub - return false; -} - -void IPCHandlerBinder::Stop() { - // Stub -} - -void IPCHandlerBinder::NotifyStarted() { - // Stub -} - -} // namespace |