Merge branch 'master' into release

Change-Id: I6e5c45cffa1cae932ca1e7294f3b6ef1be26b8ee
This commit is contained in:
Alexey Polyudov
2020-06-04 13:04:42 -07:00
29 changed files with 2042 additions and 20 deletions
+3
View File
@@ -35,6 +35,9 @@ namespace connections {
using ::location::nearby::proto::connections::Medium;
using ::securegcm::UKey2Handshake;
constexpr absl::Duration BasePcpHandler::kConnectionRequestReadTimeout;
constexpr absl::Duration BasePcpHandler::kRejectedConnectionCloseDelay;
BasePcpHandler::BasePcpHandler(EndpointManager* endpoint_manager,
EndpointChannelManager* channel_manager)
: endpoint_manager_(endpoint_manager), channel_manager_(channel_manager) {}
+5
View File
@@ -30,6 +30,11 @@ namespace connections {
using ::location::nearby::proto::connections::Medium;
constexpr absl::Duration EndpointManager::kKeepAliveWriteInterval;
constexpr absl::Duration EndpointManager::kKeepAliveReadTimeout;
constexpr absl::Duration EndpointManager::kProcessEndpointDisconnectionTimeout;
constexpr absl::Time EndpointManager::kInvalidTimestamp;
// A Runnable that continuously grabs the most recent EndpointChannel available
// for an endpoint.
//
+9 -1
View File
@@ -20,7 +20,9 @@ cc_library(
"ble_advertisement_header.cc",
"ble_packet.cc",
"bloom_filter.cc",
"bluetooth_classic.cc",
"bluetooth_radio.cc",
"mediums.cc",
"uuid.cc",
],
hdrs = [
@@ -30,14 +32,17 @@ cc_library(
"ble_packet.h",
"ble_peripheral.h",
"bloom_filter.h",
"bluetooth_classic.h",
"bluetooth_radio.h",
"lost_entity_tracker.h",
"mediums.h",
"uuid.h",
],
visibility = [
"//core_v2/internal:__pkg__",
"//core_v2/internal:__subpackages__",
],
deps = [
"//core_v2:core_types",
"//platform_v2/base",
"//platform_v2/public:comm",
"//platform_v2/public:logging",
@@ -67,6 +72,7 @@ cc_library(
cc_test(
name = "core_v2_internal_mediums_test",
size = "small",
srcs = [
"advertisement_read_result_test.cc",
"ble_advertisement_header_test.cc",
@@ -74,6 +80,7 @@ cc_test(
"ble_packet_test.cc",
"ble_peripheral_test.cc",
"bloom_filter_test.cc",
"bluetooth_classic_test.cc",
"bluetooth_radio_test.cc",
"lost_entity_tracker_test.cc",
"uuid_test.cc",
@@ -82,6 +89,7 @@ cc_test(
deps = [
":mediums",
"//platform_v2/base",
"//platform_v2/base:test_util",
"//platform_v2/impl/g3", # build_cleaner: keep
"//platform_v2/public:comm",
"//platform_v2/public:logging",
@@ -0,0 +1,391 @@
// Copyright 2020 Google LLC
//
// 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
//
// https://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 "core_v2/internal/mediums/bluetooth_classic.h"
#include <memory>
#include <string>
#include <utility>
#include "core_v2/internal/mediums/uuid.h"
#include "platform_v2/public/logging.h"
#include "platform_v2/public/mutex_lock.h"
namespace location {
namespace nearby {
namespace connections {
BluetoothClassic::BluetoothClassic(BluetoothRadio& radio) : radio_(radio) {}
BluetoothClassic::~BluetoothClassic() {
// Destructor is not taking locks, but methods it is calling are.
StopDiscovery();
while (!server_sockets_.empty()) {
StopAcceptingConnections(server_sockets_.begin()->first);
}
TurnOffDiscoverability();
// All the AcceptLoopRunnable objects in here should already have gotten an
// opportunity to shut themselves down cleanly in the calls to
// StopAcceptingConnections() above.
accept_loops_runner_.Shutdown();
}
bool BluetoothClassic::IsAvailable() const {
MutexLock lock(&mutex_);
return IsAvailableLocked();
}
bool BluetoothClassic::IsAvailableLocked() const {
return medium_.IsValid() && adapter_.IsValid();
}
bool BluetoothClassic::TurnOnDiscoverability(const std::string& device_name) {
MutexLock lock(&mutex_);
if (device_name.empty()) {
NEARBY_LOG(INFO,
"Refusing to turn on BT discoverability. Empty device name.");
return false;
}
if (!radio_.IsEnabled()) {
NEARBY_LOG(INFO, "Can't turn on BT discoverability. BT is off.");
return false;
}
if (!IsAvailableLocked()) {
NEARBY_LOG(INFO, "Can't turn on BT discoverability. BT is not available.");
return false;
}
if (IsDiscoverable()) {
NEARBY_LOG(INFO,
"Refusing to turn on BT discoverability; new name='%s'; "
"current name='%s'",
device_name.c_str(), adapter_.GetName().c_str());
return false;
}
if (!ModifyDeviceName(device_name)) {
NEARBY_LOG(INFO,
"Failed to turn on BT discoverability; "
"failed to set name to %s",
device_name.c_str());
return false;
}
if (!ModifyScanMode(ScanMode::kConnectableDiscoverable)) {
NEARBY_LOG(INFO,
"Failed to turn on BT discoverability; "
"failed to set scan_mode to %d",
ScanMode::kConnectableDiscoverable);
// Don't forget to perform this rollback of the partial state changes we've
// made til now.
RestoreDeviceName();
return false;
}
NEARBY_LOG(INFO, "Turned on BT discoverability with device_name=%s",
device_name.c_str());
return true;
}
bool BluetoothClassic::TurnOffDiscoverability() {
MutexLock lock(&mutex_);
if (!IsDiscoverable()) {
NEARBY_LOG(INFO, "Can't turn off BT discoverability; it is already off");
return false;
}
RestoreScanMode();
RestoreDeviceName();
NEARBY_LOG(INFO, "Turned Bluetooth discoverability off");
return true;
}
bool BluetoothClassic::IsDiscoverable() const {
return (!original_device_name_.empty() &&
(adapter_.GetScanMode() == ScanMode::kConnectableDiscoverable));
}
bool BluetoothClassic::ModifyDeviceName(const std::string& device_name) {
if (original_device_name_.empty()) {
original_device_name_ = adapter_.GetName();
}
return adapter_.SetName(device_name);
}
bool BluetoothClassic::ModifyScanMode(ScanMode scan_mode) {
if (original_scan_mode_ == ScanMode::kUnknown) {
original_scan_mode_ = adapter_.GetScanMode();
}
if (!adapter_.SetScanMode(scan_mode)) {
original_scan_mode_ = ScanMode::kUnknown;
return false;
}
return true;
}
bool BluetoothClassic::RestoreScanMode() {
if (original_scan_mode_ == ScanMode::kUnknown ||
!adapter_.SetScanMode(original_scan_mode_)) {
NEARBY_LOG(INFO, "Failed to restore original Bluetooth scan mode to %d",
original_scan_mode_);
return false;
}
// Regardless of whether or not we could actually restore the Bluetooth scan
// mode, reset our relevant state.
original_scan_mode_ = ScanMode::kUnknown;
return true;
}
bool BluetoothClassic::RestoreDeviceName() {
if (original_device_name_.empty() ||
!adapter_.SetName(original_device_name_)) {
NEARBY_LOG(INFO, "Failed to restore original Bluetooth device name to %s",
original_device_name_.c_str());
return false;
}
original_device_name_.clear();
return true;
}
bool BluetoothClassic::StartDiscovery(DiscoveredDeviceCallback callback) {
MutexLock lock(&mutex_);
if (!radio_.IsEnabled()) {
NEARBY_LOG(INFO, "Can't discover BT devices because BT isn't enabled.");
return false;
}
if (!IsAvailableLocked()) {
NEARBY_LOG(INFO, "Can't discover BT devices because BT isn't available.");
return false;
}
if (IsDiscovering()) {
NEARBY_LOG(INFO,
"Refusing to start discovery of BT devices because another "
"discovery is already in-progress.");
return false;
}
if (!medium_.StartDiscovery(callback)) {
NEARBY_LOG(INFO, "Failed to start discovery of BT devices.");
return false;
}
// Mark the fact that we're currently performing a Bluetooth scan.
scan_info_.valid = true;
return true;
}
bool BluetoothClassic::StopDiscovery() {
MutexLock lock(&mutex_);
if (!IsDiscovering()) {
NEARBY_LOG(INFO,
"Can't stop discovery of BT devices because it never started.");
return false;
}
if (!medium_.StopDiscovery()) {
NEARBY_LOG(INFO, "Failed to stop discovery of Bluetooth devices.");
return false;
}
scan_info_.valid = false;
return true;
}
bool BluetoothClassic::IsDiscovering() const { return scan_info_.valid; }
bool BluetoothClassic::StartAcceptingConnections(
const std::string& service_name, AcceptedConnectionCallback callback) {
MutexLock lock(&mutex_);
if (service_name.empty()) {
NEARBY_LOG(
INFO,
"Refusing to start accepting BT connections; service name is empty.");
return false;
}
if (!radio_.IsEnabled()) {
NEARBY_LOG(INFO,
"Can't create BT server socket [service=%s]; BT is disabled.",
service_name.c_str());
return false;
}
if (!IsAvailableLocked()) {
NEARBY_LOG(
INFO,
"Can't start accepting BT connections [service=%s]; BT not available.",
service_name.c_str());
return false;
}
if (IsAcceptingConnectionsLocked(service_name)) {
NEARBY_LOG(INFO,
"Refusing to start accepting BT connections [service=%s]; BT "
"server is already in-progress with the same name.",
service_name.c_str());
return false;
}
BluetoothServerSocket socket = medium_.ListenForService(
service_name, GenerateUuidFromString(service_name));
if (!socket.IsValid()) {
NEARBY_LOG(INFO, "Failed to start accepting Bluetooth connections for %s.",
service_name.c_str());
return false;
}
// Mark the fact that there's an in-progress Bluetooth server accepting
// connections.
auto owned_socket =
server_sockets_.emplace(service_name, std::move(socket)).first->second;
// Start the accept loop on a dedicated thread - this stays alive and
// listening for new incoming connections until StopAcceptingConnections() is
// invoked.
accept_loops_runner_.Execute([callback = std::move(callback),
server_socket = std::move(owned_socket),
service_name]() mutable {
while (true) {
BluetoothSocket client_socket = server_socket.Accept();
if (!client_socket.IsValid()) {
server_socket.Close();
break;
}
callback.accepted_cb(std::move(client_socket));
}
});
return true;
}
bool BluetoothClassic::IsAcceptingConnections(const std::string& service_name) {
MutexLock lock(&mutex_);
return IsAcceptingConnectionsLocked(service_name);
}
bool BluetoothClassic::IsAcceptingConnectionsLocked(
const std::string& service_name) {
return server_sockets_.find(service_name) != server_sockets_.end();
}
bool BluetoothClassic::StopAcceptingConnections(
const std::string& service_name) {
MutexLock lock(&mutex_);
if (service_name.empty()) {
NEARBY_LOG(INFO,
"Unable to stop accepting BT connections because the "
"service_name is empty.");
return false;
}
const auto& it = server_sockets_.find(service_name);
if (it == server_sockets_.end()) {
NEARBY_LOG(INFO,
"Can't stop accepting BT connections for %s because it was "
"never started.",
service_name.c_str());
return false;
}
// Closing the BluetoothServerSocket will kick off the suicide of the thread
// in accept_loops_thread_pool_ that blocks on BluetoothServerSocket.accept().
// That may take some time to complete, but there's no particular reason to
// wait around for it.
auto item = server_sockets_.extract(it);
// Store a handle to the BluetoothServerSocket, so we can use it after
// removing the entry from server_sockets_; making it scoped
// is a bonus that takes care of deallocation before we leave this method.
BluetoothServerSocket& listening_socket = item.mapped();
// Regardless of whether or not we fail to close the existing
// BluetoothServerSocket, remove it from server_sockets_ so that it
// frees up this service for another round.
// Finally, close the BluetoothServerSocket.
if (!listening_socket.Close().Ok()) {
NEARBY_LOG(INFO, "Failed to close BT server socket for %s.",
service_name.c_str());
return false;
}
return true;
}
BluetoothSocket BluetoothClassic::Connect(BluetoothDevice& bluetooth_device,
const std::string& service_name) {
MutexLock lock(&mutex_);
NEARBY_LOG(INFO, "BluetoothClassic::Connect: device=%p", &bluetooth_device);
// Socket to return. To allow for NRVO to work, it has to be a single object.
BluetoothSocket socket;
if (service_name.empty()) {
NEARBY_LOG(
INFO,
"Refusing to create client BT socket because service_name is empty.");
return socket;
}
if (!radio_.IsEnabled()) {
NEARBY_LOG(INFO,
"Can't create client BT socket [service=%s]: BT isn't enabled.",
service_name.c_str());
return socket;
}
if (!IsAvailableLocked()) {
NEARBY_LOG(
INFO, "Can't create client BT socket [service=%s]; BT isn't available.",
service_name.c_str());
return socket;
}
socket = medium_.ConnectToService(bluetooth_device,
GenerateUuidFromString(service_name));
if (!socket.IsValid()) {
NEARBY_LOG(INFO, "Failed to Connect via BT [service=%s]",
service_name.c_str());
}
return socket;
}
std::string BluetoothClassic::GenerateUuidFromString(const std::string& data) {
return std::string(Uuid(data));
}
} // namespace connections
} // namespace nearby
} // namespace location
@@ -0,0 +1,192 @@
// Copyright 2020 Google LLC
//
// 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
//
// https://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.
#ifndef CORE_V2_INTERNAL_MEDIUMS_BLUETOOTH_CLASSIC_H_
#define CORE_V2_INTERNAL_MEDIUMS_BLUETOOTH_CLASSIC_H_
#include <cstdint>
#include <string>
#include "core_v2/internal/mediums/bluetooth_radio.h"
#include "core_v2/listeners.h"
#include "platform_v2/base/byte_array.h"
#include "platform_v2/public/bluetooth_adapter.h"
#include "platform_v2/public/bluetooth_classic.h"
#include "platform_v2/public/multi_thread_executor.h"
#include "platform_v2/public/mutex.h"
#include "absl/container/flat_hash_map.h"
namespace location {
namespace nearby {
namespace connections {
class BluetoothClassic {
public:
using DiscoveredDeviceCallback = BluetoothClassicMedium::DiscoveryCallback;
using ScanMode = BluetoothAdapter::ScanMode;
// Callback that is invoked when a new connection is accepted.
struct AcceptedConnectionCallback {
std::function<void(BluetoothSocket socket)> accepted_cb =
DefaultCallback<BluetoothSocket>();
};
explicit BluetoothClassic(BluetoothRadio& bluetooth_radio);
~BluetoothClassic();
// Returns true, if BT communications are supported by a platform.
bool IsAvailable() const ABSL_LOCKS_EXCLUDED(mutex_);
// Sets custom device name, and then enables BT discoverable mode.
// Returns true, if name and scan mode are successfully set, and false
// otherwise.
// Called by server.
bool TurnOnDiscoverability(const std::string& device_name)
ABSL_LOCKS_EXCLUDED(mutex_);
// Disables BT discoverability, and restores scan mode and device name to
// what they were before the call to TurnOnDiscoverability().
// Returns false if no successful call TurnOnDiscoverability() was previously
// made, otherwise returns true.
// Called by server.
bool TurnOffDiscoverability() ABSL_LOCKS_EXCLUDED(mutex_);
// Enables BT discovery mode. Will report any discoverable devices in range
// through a callback.
// Returns true, if discovery mode was enabled, false otherwise.
// Called by client.
bool StartDiscovery(DiscoveredDeviceCallback callback)
ABSL_LOCKS_EXCLUDED(mutex_);
// Disables BT discovery mode.
// Returns true, if discovery mode was previously enabled, false otherwise.
// Called by client.
bool StopDiscovery() ABSL_LOCKS_EXCLUDED(mutex_);
// Starts a worker thread, creates a BT server socket, associates it with a
// service name; in a worker thread repeatedly calls ServerSocket::Accept().
// Any connected sockets returned from Accept() are passed to a callback.
// Returns true, if server socket was successfully created, false otherwise.
// Called by server.
bool StartAcceptingConnections(const std::string& service_name,
AcceptedConnectionCallback callback)
ABSL_LOCKS_EXCLUDED(mutex_);
// Returns true, if object is currently running a Accept() loop.
bool IsAcceptingConnections(const std::string& service_name)
ABSL_LOCKS_EXCLUDED(mutex_);
// Closes server socket corresponding to a service name. This automatically
// terminates Accept() loop, if it were running.
// Called by server.
bool StopAcceptingConnections(const std::string& service_name)
ABSL_LOCKS_EXCLUDED(mutex_);
// Returns true if this object owns a valid platform implementation.
bool IsMediumValid() const ABSL_LOCKS_EXCLUDED(mutex_) {
MutexLock lock(&mutex_);
return medium_.IsValid();
}
// Returns true if this object has a valid BluetoothAdapter reference.
bool IsAdapterValid() const ABSL_LOCKS_EXCLUDED(mutex_) {
MutexLock lock(&mutex_);
return adapter_.IsValid();
}
// Establishes connection to BT service that was might be started on another
// device with StartAcceptingConnections() using the same service_name.
// Blocks until connection is established, or server-side is terminated.
// Returns socket instance. On success, BluetoothSocket.IsValid() return true.
// Called by client.
BluetoothSocket Connect(BluetoothDevice& bluetooth_device,
const std::string& service_name)
ABSL_LOCKS_EXCLUDED(mutex_);
private:
struct ScanInfo {
bool valid = false;
};
static constexpr int kMaxConcurrentAcceptLoops = 5;
// Constructs UUID object from arbitrary string, using MD5 hash, and then
// converts UUID to a readable UUID string and returns it.
static std::string GenerateUuidFromString(const std::string& data);
// Same as IsAvailable(), but must be called with mutex_ held.
bool IsAvailableLocked() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
// Same as IsAcceptingConnections(), but must be called with mutex_ held.
bool IsAcceptingConnectionsLocked(const std::string& service_name)
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
// Returns true, if discoverability is enabled with TurnOnDiscoverability().
bool IsDiscoverable() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
// Assignes a different name to BT adapter.
// Returns true if successful. Stores original device name.
bool ModifyDeviceName(const std::string& device_name)
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
// Changes current scan mode. This is an implementation of
// Turn<On/Off>Discoveradility() method. Stores original scan mode.
bool ModifyScanMode(ScanMode scan_mode) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
// Restores original device name (the one before the very first call to
// ModifyDeviceName()). Returns true if successful.
bool RestoreScanMode() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
// Restores original device scan mode (the one before the very first call to
// ModifyScanMode()). Returns true if successful.
bool RestoreDeviceName() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
// Returns true if device is currently in discovery mode.
bool IsDiscovering() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
mutable Mutex mutex_;
BluetoothRadio& radio_ ABSL_GUARDED_BY(mutex_);
BluetoothAdapter& adapter_ ABSL_GUARDED_BY(mutex_){
radio_.GetBluetoothAdapter()};
BluetoothClassicMedium medium_ ABSL_GUARDED_BY(mutex_){adapter_};
// A bundle of state required to do a Bluetooth Classic scan. When non-null,
// we are currently performing a Bluetooth scan.
ScanInfo scan_info_ ABSL_GUARDED_BY(mutex_);
// The original scan mode (that controls visibility to scanners) of the device
// before we modified it. Restored when we stop advertising.
ScanMode original_scan_mode_ ABSL_GUARDED_BY(mutex_) = ScanMode::kUnknown;
// The original Bluetooth device name, before we modified it. If non-empty, we
// are currently Bluetooth discoverable. Restored when we stop advertising.
std::string original_device_name_ ABSL_GUARDED_BY(mutex_);
// A thread pool dedicated to running all the accept loops from
// StartAcceptingConnections().
MultiThreadExecutor accept_loops_runner_{kMaxConcurrentAcceptLoops};
// A map of service Name -> ServerSocket. If map is non-empty, we
// are currently listening for incoming connections.
// BluetoothServerSocket instances are used from accept_loops_runner_,
// and thus require pointer stability.
absl::flat_hash_map<std::string, BluetoothServerSocket> server_sockets_
ABSL_GUARDED_BY(mutex_);
};
} // namespace connections
} // namespace nearby
} // namespace location
#endif // CORE_V2_INTERNAL_MEDIUMS_BLUETOOTH_CLASSIC_H_
@@ -0,0 +1,208 @@
// Copyright 2020 Google LLC
//
// 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
//
// https://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 "core_v2/internal/mediums/bluetooth_classic.h"
#include <string>
#include "core_v2/internal/mediums/bluetooth_radio.h"
#include "platform_v2/base/medium_environment.h"
#include "platform_v2/public/bluetooth_classic.h"
#include "platform_v2/public/count_down_latch.h"
#include "platform_v2/public/logging.h"
#include "platform_v2/public/system_clock.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/time/time.h"
namespace location {
namespace nearby {
namespace connections {
namespace {
constexpr absl::Duration kWaitDuration = absl::Milliseconds(1000);
class BluetoothClassicTest : public ::testing::Test {
protected:
using DiscoveryCallback = BluetoothClassicMedium::DiscoveryCallback;
BluetoothClassicTest() {
env_.Reset();
radio_a_ = std::make_unique<BluetoothRadio>();
radio_b_ = std::make_unique<BluetoothRadio>();
bt_a_ = std::make_unique<BluetoothClassic>(*radio_a_);
bt_b_ = std::make_unique<BluetoothClassic>(*radio_b_);
radio_a_->GetBluetoothAdapter().SetName("Device-A");
radio_b_->GetBluetoothAdapter().SetName("Device-B");
radio_a_->Enable();
radio_b_->Enable();
env_.Sync();
}
~BluetoothClassicTest() override {
env_.Sync(false);
radio_a_->Disable();
radio_b_->Disable();
bt_a_.reset();
bt_b_.reset();
env_.Sync(false);
radio_a_.reset();
radio_b_.reset();
env_.Reset();
}
MediumEnvironment& env_{MediumEnvironment::Instance()};
std::unique_ptr<BluetoothRadio> radio_a_;
std::unique_ptr<BluetoothRadio> radio_b_;
std::unique_ptr<BluetoothClassic> bt_a_;
std::unique_ptr<BluetoothClassic> bt_b_;
};
TEST_F(BluetoothClassicTest, CanConstructValidObject) {
EXPECT_TRUE(bt_a_->IsMediumValid());
EXPECT_TRUE(bt_a_->IsAdapterValid());
EXPECT_TRUE(bt_a_->IsAvailable());
EXPECT_TRUE(bt_b_->IsMediumValid());
EXPECT_TRUE(bt_b_->IsAdapterValid());
EXPECT_TRUE(bt_b_->IsAvailable());
EXPECT_NE(&radio_a_->GetBluetoothAdapter(), &radio_b_->GetBluetoothAdapter());
}
TEST_F(BluetoothClassicTest, CanStartAdvertising) {
constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
EXPECT_TRUE(bt_a_->TurnOnDiscoverability(std::string(kDeviceName)));
EXPECT_EQ(radio_a_->GetBluetoothAdapter().GetName(), kDeviceName);
}
TEST_F(BluetoothClassicTest, CanStopAdvertising) {
constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
EXPECT_TRUE(bt_a_->TurnOnDiscoverability(std::string(kDeviceName)));
EXPECT_EQ(radio_a_->GetBluetoothAdapter().GetName(), kDeviceName);
EXPECT_TRUE(bt_a_->TurnOffDiscoverability());
}
TEST_F(BluetoothClassicTest, CanStartDiscovery) {
constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
EXPECT_TRUE(bt_a_->TurnOnDiscoverability(std::string(kDeviceName)));
EXPECT_EQ(radio_a_->GetBluetoothAdapter().GetName(), kDeviceName);
CountDownLatch latch(1);
EXPECT_TRUE(bt_b_->StartDiscovery({
.device_discovered_cb =
[&latch](BluetoothDevice& device) { latch.CountDown(); },
}));
EXPECT_TRUE(latch.Await(kWaitDuration).result());
EXPECT_TRUE(bt_a_->TurnOffDiscoverability());
}
TEST_F(BluetoothClassicTest, CanStopDiscovery) {
CountDownLatch latch(1);
EXPECT_TRUE(bt_a_->StartDiscovery({
.device_discovered_cb =
[&latch](BluetoothDevice& device) { latch.CountDown(); },
}));
EXPECT_FALSE(latch.Await(kWaitDuration).result());
EXPECT_TRUE(bt_a_->StopDiscovery());
}
TEST_F(BluetoothClassicTest, CanStartAcceptingConnections) {
constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
constexpr absl::string_view kServiceName{"service name"};
BluetoothRadio& radio_for_client = *radio_a_;
BluetoothRadio& radio_for_server = *radio_b_;
BluetoothClassic& bt_client = *bt_a_;
BluetoothClassic& bt_server = *bt_b_;
EXPECT_TRUE(radio_for_client.IsEnabled());
EXPECT_TRUE(radio_for_server.IsEnabled());
EXPECT_TRUE(bt_server.TurnOnDiscoverability(std::string(kDeviceName)));
EXPECT_EQ(radio_for_server.GetBluetoothAdapter().GetName(), kDeviceName);
CountDownLatch latch(1);
BluetoothDevice discovered_device;
EXPECT_TRUE(bt_client.StartDiscovery({
.device_discovered_cb =
[&latch, &discovered_device](BluetoothDevice& device) {
discovered_device = device;
NEARBY_LOG(INFO, "Discovered device=%p [impl=%p]", &device,
&device.GetImpl());
latch.CountDown();
},
}));
EXPECT_TRUE(latch.Await(kWaitDuration).result());
EXPECT_TRUE(bt_server.TurnOffDiscoverability());
EXPECT_TRUE(discovered_device.IsValid());
EXPECT_TRUE(
bt_server.StartAcceptingConnections(std::string(kServiceName), {}));
// Allow StartAcceptingConnections do something, before stopping it.
// This is best effort, because no callbacks are invoked in this scenario.
SystemClock::Sleep(kWaitDuration);
EXPECT_TRUE(bt_server.StopAcceptingConnections(std::string(kServiceName)));
}
TEST_F(BluetoothClassicTest, CanConnect) {
constexpr absl::string_view kDeviceName{"Simulated BT device #1"};
constexpr absl::string_view kServiceName{"service name"};
BluetoothRadio& radio_for_client = *radio_a_;
BluetoothRadio& radio_for_server = *radio_b_;
BluetoothClassic& bt_client = *bt_a_;
BluetoothClassic& bt_server = *bt_b_;
EXPECT_TRUE(radio_for_client.IsEnabled());
EXPECT_TRUE(radio_for_server.IsEnabled());
EXPECT_TRUE(bt_server.TurnOnDiscoverability(std::string(kDeviceName)));
EXPECT_EQ(radio_for_server.GetBluetoothAdapter().GetName(),
std::string(kDeviceName));
CountDownLatch latch(1);
BluetoothDevice discovered_device;
EXPECT_TRUE(bt_client.StartDiscovery({
.device_discovered_cb =
[&latch, &discovered_device](BluetoothDevice& device) {
discovered_device = device;
NEARBY_LOG(INFO, "Discovered device=%p [impl=%p]", &device,
&device.GetImpl());
latch.CountDown();
},
}));
EXPECT_TRUE(latch.Await(kWaitDuration).result());
EXPECT_TRUE(bt_server.TurnOffDiscoverability());
ASSERT_TRUE(discovered_device.IsValid());
BluetoothSocket socket_for_server;
CountDownLatch accept_latch(1);
EXPECT_TRUE(bt_server.StartAcceptingConnections(
std::string(kServiceName),
{
.accepted_cb =
[&socket_for_server, &accept_latch](BluetoothSocket socket) {
socket_for_server = std::move(socket);
accept_latch.CountDown();
},
}));
BluetoothSocket socket_for_client =
bt_client.Connect(discovered_device, std::string(kServiceName));
EXPECT_TRUE(accept_latch.Await(kWaitDuration).result());
EXPECT_TRUE(bt_server.StopAcceptingConnections(std::string(kServiceName)));
EXPECT_TRUE(socket_for_server.IsValid());
EXPECT_TRUE(socket_for_client.IsValid());
EXPECT_TRUE(socket_for_server.GetRemoteDevice().IsValid());
EXPECT_TRUE(socket_for_client.GetRemoteDevice().IsValid());
}
} // namespace
} // namespace connections
} // namespace nearby
} // namespace location
@@ -22,6 +22,8 @@ namespace location {
namespace nearby {
namespace connections {
constexpr absl::Duration BluetoothRadio::kPauseBetweenToggle;
BluetoothRadio::BluetoothRadio() {
if (!IsAdapterValid()) {
NEARBY_LOG(ERROR, "Bluetooth adapter is not valid: BT is not supported");
+31
View File
@@ -0,0 +1,31 @@
// Copyright 2020 Google LLC
//
// 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
//
// https://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 "core_v2/internal/mediums/mediums.h"
namespace location {
namespace nearby {
namespace connections {
BluetoothRadio& Mediums::GetBluetoothRadio() {
return bluetooth_radio_;
}
BluetoothClassic& Mediums::GetBluetoothClassic() {
return bluetooth_classic_;
}
} // namespace connections
} // namespace nearby
} // namespace location
+54
View File
@@ -0,0 +1,54 @@
// Copyright 2020 Google LLC
//
// 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
//
// https://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.
#ifndef CORE_V2_INTERNAL_MEDIUMS_MEDIUMS_H_
#define CORE_V2_INTERNAL_MEDIUMS_MEDIUMS_H_
#include "core_v2/internal/mediums/bluetooth_classic.h"
#include "core_v2/internal/mediums/bluetooth_radio.h"
namespace location {
namespace nearby {
namespace connections {
// Facilitates convenient and reliable usage of various wireless mediums.
class Mediums {
public:
Mediums() = default;
~Mediums() = default;
// Returns a handle to the Bluetooth radio.
BluetoothRadio& GetBluetoothRadio();
// Returns a handle to the Bluetooth Classic medium.
BluetoothClassic& GetBluetoothClassic();
private:
// The order of declaration is critical for both construction and
// destruction.
//
// 1) Construction: The individual mediums have a dependency on the
// corresponding radio, so the radio must be initialized first.
//
// 2) Destruction: The individual mediums should be shut down before the
// corresponding radio.
BluetoothRadio bluetooth_radio_;
BluetoothClassic bluetooth_classic_{bluetooth_radio_};
};
} // namespace connections
} // namespace nearby
} // namespace location
#endif // CORE_V2_INTERNAL_MEDIUMS_MEDIUMS_H_
+2 -2
View File
@@ -17,7 +17,7 @@
#include <memory>
#include <utility>
#include "google/protobuf/message_lite.h"
#include "core/internal/message_lite.h"
#include "platform_v2/base/byte_array.h"
namespace location {
@@ -28,7 +28,7 @@ namespace {
using ExceptionOrOfflineFrame = ExceptionOr<OfflineFrame>;
using Medium = proto::connections::Medium;
using MessageLite = ::google3_proto_compat::MessageLite;
using MessageLite = ::google::protobuf::MessageLite;
ByteArray ToBytes(OfflineFrame&& frame) {
ByteArray bytes(frame.ByteSizeLong());