1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
|
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/bluetooth/bluetooth_low_energy_adapter_apple.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import <Foundation/Foundation.h>
#include <memory>
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/task/sequenced_task_runner.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "base/test/test_simple_task_runner.h"
#include "build/build_config.h"
#include "device/bluetooth/bluetooth_adapter.h"
#include "device/bluetooth/bluetooth_common.h"
#include "device/bluetooth/bluetooth_discovery_session.h"
#include "device/bluetooth/bluetooth_discovery_session_outcome.h"
#import "device/bluetooth/bluetooth_low_energy_device_mac.h"
#include "device/bluetooth/bluetooth_low_energy_device_watcher_mac.h"
#import "device/bluetooth/test/mock_bluetooth_cbperipheral_mac.h"
#import "device/bluetooth/test/mock_bluetooth_central_manager_mac.h"
#import "device/bluetooth/test/test_bluetooth_adapter_observer.h"
#include "testing/gtest/include/gtest/gtest.h"
#if BUILDFLAG(IS_IOS)
#include "device/bluetooth/bluetooth_adapter_ios.h"
#else
#include "device/bluetooth/bluetooth_adapter_mac.h"
#endif
namespace {
const char kTestPropertyListFileName[] = "test_property_list_file.plist";
// |kTestHashAddress| is the hash corresponding to identifier |kTestNSUUID|.
const char kTestNSUUID[] = "00000000-1111-2222-3333-444444444444";
const char kTestHashAddress[] = "D1:6F:E3:22:FD:5B";
const int kTestRssi = 0;
NSDictionary* TestPropertyListData() {
return @{
@"CoreBluetoothCache" : @{
@"00000000-1111-2222-3333-444444444444" : @{
@"DeviceAddress" : @"22-22-22-22-22-22",
@"DeviceAddressType" : @1,
@"ServiceChangedHandle" : @3,
@"ServiceChangeSubscribed" : @0,
@"ServiceDiscoveryComplete" : @0
}
}
};
}
#if BUILDFLAG(IS_MAC)
bool IsTestDeviceSystemPaired(const std::string& address) {
return true;
}
#endif
} // namespace
namespace device {
class BluetoothLowEnergyAdapterAppleTest : public testing::Test {
public:
class FakeBluetoothLowEnergyDeviceWatcherMac
: public BluetoothLowEnergyDeviceWatcherMac {
public:
FakeBluetoothLowEnergyDeviceWatcherMac(
scoped_refptr<base::SequencedTaskRunner> ui_thread_task_runner,
LowEnergyDeviceListUpdatedCallback callback)
: BluetoothLowEnergyDeviceWatcherMac(ui_thread_task_runner, callback),
weak_ptr_factory_(this) {}
void SimulatePropertyListFileChanged(
const base::FilePath& path,
const std::string& changed_file_content) {
ASSERT_TRUE(base::WriteFile(path, changed_file_content));
OnPropertyListFileChangedOnFileThread(path, false /* error */);
}
private:
~FakeBluetoothLowEnergyDeviceWatcherMac() override = default;
void Init() override { ReadBluetoothPropertyListFile(); }
void ReadBluetoothPropertyListFile() override {
low_energy_device_list_updated_callback().Run(
ParseBluetoothDevicePropertyListData(TestPropertyListData()));
}
base::WeakPtrFactory<FakeBluetoothLowEnergyDeviceWatcherMac>
weak_ptr_factory_;
};
BluetoothLowEnergyAdapterAppleTest()
: ui_task_runner_(new base::TestSimpleTaskRunner()),
adapter_(CreateBluetoothLowEnergyAdapterApple()),
adapter_low_energy_(
static_cast<BluetoothLowEnergyAdapterApple*>(adapter_.get())),
observer_(adapter_),
callback_count_(0),
error_callback_count_(0) {
adapter_low_energy_->InitForTest(ui_task_runner_);
fake_low_energy_device_watcher_ =
base::MakeRefCounted<FakeBluetoothLowEnergyDeviceWatcherMac>(
ui_task_runner_,
base::BindRepeating(
&BluetoothLowEnergyAdapterApple::UpdateKnownLowEnergyDevices,
adapter_low_energy_->GetLowEnergyWeakPtr()));
#if BUILDFLAG(IS_MAC)
static_cast<BluetoothAdapterMac*>(adapter_low_energy_)
->SetGetDevicePairedStatusCallbackForTesting(
base::BindRepeating(&IsTestDeviceSystemPaired));
#endif
}
void SetUp() override {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
test_property_list_file_path_ =
temp_dir_.GetPath().AppendASCII(kTestPropertyListFileName);
}
void TearDown() override { task_environment_.RunUntilIdle(); }
void LowEnergyDeviceUpdated(CBPeripheral* peripheral,
NSDictionary* advertisement_data,
int rssi) {
adapter_low_energy_->LowEnergyDeviceUpdated(peripheral, advertisement_data,
rssi);
}
BluetoothLowEnergyAdapterApple* CreateBluetoothLowEnergyAdapterApple() {
#if BUILDFLAG(IS_IOS)
return static_cast<BluetoothLowEnergyAdapterApple*>(
new BluetoothAdapterIOS());
#else
return static_cast<BluetoothLowEnergyAdapterApple*>(
new BluetoothAdapterMac());
#endif
}
BluetoothDevice* GetDevice(const std::string& address) {
return adapter_->GetDevice(address);
}
CBPeripheral* CreateMockPeripheral(const char* identifier) {
MockCBPeripheral* mock_peripheral =
[[MockCBPeripheral alloc] initWithUTF8StringIdentifier:identifier];
return [mock_peripheral peripheral];
}
NSDictionary* AdvertisementData() {
return @{
CBAdvertisementDataIsConnectable : @YES,
CBAdvertisementDataServiceDataKey : @{},
};
}
std::string GetHashAddress(CBPeripheral* peripheral) {
return BluetoothLowEnergyDeviceMac::GetPeripheralHashAddress(peripheral);
}
int NumDevices() { return adapter_low_energy_->devices_.size(); }
bool DevicePresent(CBPeripheral* peripheral) {
BluetoothDevice* device = adapter_low_energy_->GetDevice(
BluetoothLowEnergyDeviceMac::GetPeripheralHashAddress(peripheral));
return device;
}
bool SetMockCentralManager(CBManagerState desired_state) {
mock_central_manager_ = [[MockCentralManager alloc] init];
mock_central_manager_.state = desired_state;
CBCentralManager* centralManager =
static_cast<CBCentralManager*>(mock_central_manager_);
adapter_low_energy_->SetCentralManagerForTesting(centralManager);
return true;
}
void OnStartDiscoverySessionSuccess(
std::unique_ptr<device::BluetoothDiscoverySession> discovery_session) {
active_sessions_.push_back(std::move(discovery_session));
Callback();
}
int NumDiscoverySessions() {
return adapter_low_energy_->NumDiscoverySessions();
}
void SetFakeLowEnergyDeviceWatcher() {
adapter_low_energy_->SetLowEnergyDeviceWatcherForTesting(
fake_low_energy_device_watcher_);
}
// Generic callbacks.
void Callback() { ++callback_count_; }
void ErrorCallback() { ++error_callback_count_; }
void DiscoveryErrorCallback(UMABluetoothDiscoverySessionOutcome) {
++error_callback_count_;
}
protected:
base::test::TaskEnvironment task_environment_;
scoped_refptr<base::TestSimpleTaskRunner> ui_task_runner_;
scoped_refptr<BluetoothAdapter> adapter_;
raw_ptr<BluetoothLowEnergyAdapterApple> adapter_low_energy_;
scoped_refptr<FakeBluetoothLowEnergyDeviceWatcherMac>
fake_low_energy_device_watcher_;
TestBluetoothAdapterObserver observer_;
std::vector<std::unique_ptr<BluetoothDiscoverySession>> active_sessions_;
// Owned by |adapter_low_energy_|.
MockCentralManager* __strong mock_central_manager_;
int callback_count_;
int error_callback_count_;
base::ScopedTempDir temp_dir_;
base::FilePath test_property_list_file_path_;
};
TEST_F(BluetoothLowEnergyAdapterAppleTest,
AddDiscoverySessionWithLowEnergyFilter) {
if (!SetMockCentralManager(CBManagerStatePoweredOn)) {
return;
}
EXPECT_EQ(0, [mock_central_manager_ scanForPeripheralsCallCount]);
EXPECT_EQ(0, NumDiscoverySessions());
std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter(
new BluetoothDiscoveryFilter(BLUETOOTH_TRANSPORT_LE));
adapter_low_energy_->StartDiscoverySessionWithFilter(
std::move(discovery_filter),
/*client_name=*/std::string(),
base::BindOnce(
&BluetoothLowEnergyAdapterAppleTest::OnStartDiscoverySessionSuccess,
base::Unretained(this)),
base::BindOnce(&BluetoothLowEnergyAdapterAppleTest::ErrorCallback,
base::Unretained(this)));
EXPECT_TRUE(ui_task_runner_->HasPendingTask());
ui_task_runner_->RunPendingTasks();
EXPECT_EQ(1, callback_count_);
EXPECT_EQ(0, error_callback_count_);
EXPECT_EQ(1, NumDiscoverySessions());
// Check that adding a discovery session resulted in
// scanForPeripheralsWithServices being called on the Central Manager.
EXPECT_EQ(1, [mock_central_manager_ scanForPeripheralsCallCount]);
}
// TODO(krstnmnlsn): Test changing the filter when adding the second discovery
// session (once we have that ability).
TEST_F(BluetoothLowEnergyAdapterAppleTest,
AddSecondDiscoverySessionWithLowEnergyFilter) {
if (!SetMockCentralManager(CBManagerStatePoweredOn)) {
return;
}
std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter(
new BluetoothDiscoveryFilter(BLUETOOTH_TRANSPORT_LE));
std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter2(
new BluetoothDiscoveryFilter(BLUETOOTH_TRANSPORT_LE));
// Adding uuid to first discovery session so that there is a change to be made
// when starting the second session.
BluetoothDiscoveryFilter::DeviceInfoFilter device_filter;
device_filter.uuids.insert(device::BluetoothUUID("1000"));
discovery_filter->AddDeviceFilter(device_filter);
adapter_low_energy_->StartDiscoverySessionWithFilter(
std::move(discovery_filter),
/*client_name=*/std::string(),
base::BindOnce(
&BluetoothLowEnergyAdapterAppleTest::OnStartDiscoverySessionSuccess,
base::Unretained(this)),
base::BindOnce(&BluetoothLowEnergyAdapterAppleTest::ErrorCallback,
base::Unretained(this)));
EXPECT_TRUE(ui_task_runner_->HasPendingTask());
ui_task_runner_->RunPendingTasks();
EXPECT_EQ(1, callback_count_);
EXPECT_EQ(0, error_callback_count_);
EXPECT_EQ(1, NumDiscoverySessions());
// We replaced the success callback handed to AddDiscoverySession, so
// |adapter_low_energy_| should remain in a discovering state indefinitely.
EXPECT_TRUE(adapter_low_energy_->IsDiscovering());
adapter_low_energy_->StartDiscoverySessionWithFilter(
std::move(discovery_filter2),
/*client_name=*/std::string(),
base::BindOnce(
&BluetoothLowEnergyAdapterAppleTest::OnStartDiscoverySessionSuccess,
base::Unretained(this)),
base::BindOnce(&BluetoothLowEnergyAdapterAppleTest::ErrorCallback,
base::Unretained(this)));
EXPECT_TRUE(ui_task_runner_->HasPendingTask());
ui_task_runner_->RunPendingTasks();
EXPECT_EQ(2, [mock_central_manager_ scanForPeripheralsCallCount]);
EXPECT_EQ(2, callback_count_);
EXPECT_EQ(0, error_callback_count_);
EXPECT_EQ(2, NumDiscoverySessions());
}
TEST_F(BluetoothLowEnergyAdapterAppleTest,
RemoveDiscoverySessionWithLowEnergyFilter) {
if (!SetMockCentralManager(CBManagerStatePoweredOn)) {
return;
}
EXPECT_EQ(0, [mock_central_manager_ scanForPeripheralsCallCount]);
std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter(
new BluetoothDiscoveryFilter(BLUETOOTH_TRANSPORT_LE));
adapter_low_energy_->StartDiscoverySessionWithFilter(
std::move(discovery_filter),
/*client_name=*/std::string(),
base::BindOnce(
&BluetoothLowEnergyAdapterAppleTest::OnStartDiscoverySessionSuccess,
base::Unretained(this)),
base::BindOnce(&BluetoothLowEnergyAdapterAppleTest::ErrorCallback,
base::Unretained(this)));
EXPECT_TRUE(ui_task_runner_->HasPendingTask());
ui_task_runner_->RunPendingTasks();
EXPECT_EQ(1, callback_count_);
EXPECT_EQ(0, error_callback_count_);
EXPECT_EQ(1, NumDiscoverySessions());
EXPECT_EQ(0, [mock_central_manager_ stopScanCallCount]);
active_sessions_[0]->Stop(
base::BindOnce(&BluetoothLowEnergyAdapterAppleTest::Callback,
base::Unretained(this)),
base::BindOnce(&BluetoothLowEnergyAdapterAppleTest::ErrorCallback,
base::Unretained(this)));
EXPECT_EQ(2, callback_count_);
EXPECT_EQ(0, error_callback_count_);
EXPECT_EQ(0, NumDiscoverySessions());
// Check that removing the discovery session resulted in stopScan being called
// on the Central Manager.
EXPECT_EQ(1, [mock_central_manager_ stopScanCallCount]);
}
TEST_F(BluetoothLowEnergyAdapterAppleTest, CheckGetPeripheralHashAddress) {
if (!SetMockCentralManager(CBManagerStatePoweredOn)) {
return;
}
CBPeripheral* mock_peripheral = CreateMockPeripheral(kTestNSUUID);
if (!mock_peripheral) {
return;
}
EXPECT_EQ(kTestHashAddress, GetHashAddress(mock_peripheral));
}
TEST_F(BluetoothLowEnergyAdapterAppleTest, LowEnergyDeviceUpdatedNewDevice) {
if (!SetMockCentralManager(CBManagerStatePoweredOn)) {
return;
}
CBPeripheral* mock_peripheral = CreateMockPeripheral(kTestNSUUID);
if (!mock_peripheral) {
return;
}
NSDictionary* advertisement_data = AdvertisementData();
EXPECT_EQ(0, NumDevices());
EXPECT_FALSE(DevicePresent(mock_peripheral));
LowEnergyDeviceUpdated(mock_peripheral, advertisement_data, kTestRssi);
EXPECT_EQ(1, NumDevices());
EXPECT_TRUE(DevicePresent(mock_peripheral));
}
TEST_F(BluetoothLowEnergyAdapterAppleTest, GetSystemPairedLowEnergyDevice) {
SetFakeLowEnergyDeviceWatcher();
ui_task_runner_->RunUntilIdle();
EXPECT_TRUE(
adapter_low_energy_->IsBluetoothLowEnergyDeviceSystemPaired(kTestNSUUID));
}
TEST_F(BluetoothLowEnergyAdapterAppleTest, GetNewlyPairedLowEnergyDevice) {
constexpr char kPropertyListFileContentWithAddedDevice[] =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" "
"\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">"
"<plist version=\"1.0\">"
"<dict>"
" <key>CoreBluetoothCache</key>"
" <dict> "
" <key>E7F8589A-A7D9-4B94-9A08-D89076A159F4</key>"
" <dict> "
" <key>DeviceAddress</key>"
" <string>11-11-11-11-11-11</string>"
" <key>DeviceAddressType</key>"
" <integer>1</integer>"
" <key>ServiceChangedHandle</key>"
" <integer>3</integer>"
" <key>ServiceChangeSubscribed</key>"
" <integer>0</integer>"
" <key>ServiceDiscoveryComplete</key>"
" <integer>0</integer>"
" </dict>"
" <key>00000000-1111-2222-3333-444444444444</key>"
" <dict> "
" <key>DeviceAddress</key>"
" <string>22-22-22-22-22-22</string>"
" <key>DeviceAddressType</key>"
" <integer>1</integer>"
" <key>ServiceChangedHandle</key>"
" <integer>3</integer>"
" <key>ServiceChangeSubscribed</key>"
" <integer>0</integer>"
" <key>ServiceDiscoveryComplete</key>"
" <integer>0</integer>"
" </dict>"
" </dict>"
"</dict>"
"</plist>";
const char kTestAddedDeviceNSUUID[] = "E7F8589A-A7D9-4B94-9A08-D89076A159F4";
ASSERT_TRUE(SetMockCentralManager(CBManagerStatePoweredOn));
CBPeripheral* mock_peripheral_one = CreateMockPeripheral(kTestNSUUID);
ASSERT_TRUE(mock_peripheral_one);
LowEnergyDeviceUpdated(mock_peripheral_one, AdvertisementData(), kTestRssi);
CBPeripheral* mock_peripheral_two =
CreateMockPeripheral(kTestAddedDeviceNSUUID);
ASSERT_TRUE(mock_peripheral_two);
LowEnergyDeviceUpdated(mock_peripheral_two, AdvertisementData(), kTestRssi);
observer_.Reset();
// BluetoothAdapterMac only notifies observers of changed devices detected by
// BluetoothLowEnergyDeviceWatcherMac if the device has been already known to
// the system(i.e. the changed device is in BluetoothAdapter::devices_). As
// so, add mock devices prior to setting BluetoothLowEnergyDeviceWatcherMac.
SetFakeLowEnergyDeviceWatcher();
EXPECT_EQ(1, observer_.device_changed_count());
observer_.Reset();
fake_low_energy_device_watcher_->SimulatePropertyListFileChanged(
test_property_list_file_path_, kPropertyListFileContentWithAddedDevice);
ui_task_runner_->RunUntilIdle();
EXPECT_EQ(1, observer_.device_changed_count());
EXPECT_TRUE(adapter_low_energy_->IsBluetoothLowEnergyDeviceSystemPaired(
kTestAddedDeviceNSUUID));
}
TEST_F(BluetoothLowEnergyAdapterAppleTest, NotifyObserverWhenDeviceIsUnpaired) {
constexpr char kPropertyListFileContentWithRemovedDevice[] =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" "
"\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">"
"<plist version=\"1.0\">"
"<dict>"
" <key>CoreBluetoothCache</key>"
" <dict> "
" </dict>"
"</dict>"
"</plist>";
if (!SetMockCentralManager(CBManagerStatePoweredOn)) {
return;
}
CBPeripheral* mock_peripheral = CreateMockPeripheral(kTestNSUUID);
if (!mock_peripheral) {
return;
}
LowEnergyDeviceUpdated(mock_peripheral, AdvertisementData(), kTestRssi);
observer_.Reset();
SetFakeLowEnergyDeviceWatcher();
EXPECT_EQ(1, observer_.device_changed_count());
observer_.Reset();
fake_low_energy_device_watcher_->SimulatePropertyListFileChanged(
test_property_list_file_path_, kPropertyListFileContentWithRemovedDevice);
ui_task_runner_->RunUntilIdle();
EXPECT_EQ(1, observer_.device_changed_count());
EXPECT_FALSE(
adapter_low_energy_->IsBluetoothLowEnergyDeviceSystemPaired(kTestNSUUID));
}
} // namespace device
|