summaryrefslogtreecommitdiffstats
path: root/device/bluetooth/test/bluetooth_test_mac.mm
blob: 0563fd431e50eabc4d9c14f067d2671b0ca38a68 (plain)
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
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "device/bluetooth/test/bluetooth_test_mac.h"

#include <stdint.h>

#include "base/mac/foundation_util.h"
#include "base/strings/string_number_conversions.h"
#include "build/build_config.h"
#include "device/bluetooth/bluetooth_adapter_mac.h"
#include "device/bluetooth/test/mock_bluetooth_cbperipheral_mac.h"
#include "device/bluetooth/test/mock_bluetooth_central_manager_mac.h"
#include "device/bluetooth/test/test_bluetooth_adapter_observer.h"
#include "third_party/ocmock/OCMock/OCMock.h"

#import <CoreBluetooth/CoreBluetooth.h>

using base::mac::ObjCCast;
using base::scoped_nsobject;

namespace device {

// This class hides Objective-C from bluetooth_test_mac.h.
class BluetoothTestMac::ScopedMockCentralManager {
 public:
  explicit ScopedMockCentralManager(MockCentralManager* mock_central_manager) {
    mock_central_manager_.reset(mock_central_manager);
  }

  // Returns MockCentralManager instance.
  MockCentralManager* get() { return mock_central_manager_.get(); };

 private:
  scoped_nsobject<MockCentralManager> mock_central_manager_;

  DISALLOW_COPY_AND_ASSIGN(ScopedMockCentralManager);
};

namespace {

NSDictionary* CreateAdvertisementData(NSString* name, NSArray* uuids) {
  NSMutableDictionary* advertisement_data =
      [NSMutableDictionary dictionaryWithDictionary:@{
        CBAdvertisementDataLocalNameKey : name,
        CBAdvertisementDataServiceDataKey : @{},
        CBAdvertisementDataIsConnectable : @(YES),
      }];
  if (uuids) {
    [advertisement_data setObject:uuids
                           forKey:CBAdvertisementDataServiceUUIDsKey];
  }
  return [advertisement_data retain];
}

}  // namespace

// UUID1 hashes to kTestDeviceAddress1, and UUID2 to kTestDeviceAddress2.
const std::string BluetoothTestMac::kTestPeripheralUUID1 =
    "34045B00-0000-0000-0000-000000000000";
const std::string BluetoothTestMac::kTestPeripheralUUID2 =
    "EC1B8F00-0000-0000-0000-000000000000";

BluetoothTestMac::BluetoothTestMac() {}

BluetoothTestMac::~BluetoothTestMac() {}

void BluetoothTestMac::SetUp() {}

bool BluetoothTestMac::PlatformSupportsLowEnergy() {
  return BluetoothAdapterMac::IsLowEnergyAvailable();
}

void BluetoothTestMac::InitWithDefaultAdapter() {
  adapter_mac_ = BluetoothAdapterMac::CreateAdapter().get();
  adapter_ = adapter_mac_;
}

void BluetoothTestMac::InitWithoutDefaultAdapter() {
  adapter_mac_ = BluetoothAdapterMac::CreateAdapterForTest(
                     "", "", message_loop_.task_runner())
                     .get();
  adapter_ = adapter_mac_;

  if (BluetoothAdapterMac::IsLowEnergyAvailable()) {
    mock_central_manager_.reset(
        new ScopedMockCentralManager([[MockCentralManager alloc] init]));
    [mock_central_manager_->get() setBluetoothTestMac:this];
    [mock_central_manager_->get() setState:CBCentralManagerStateUnsupported];
    adapter_mac_->SetCentralManagerForTesting((id)mock_central_manager_->get());
  }
}

void BluetoothTestMac::InitWithFakeAdapter() {
  adapter_mac_ =
      BluetoothAdapterMac::CreateAdapterForTest(
          kTestAdapterName, kTestAdapterAddress, message_loop_.task_runner())
          .get();
  adapter_ = adapter_mac_;

  if (BluetoothAdapterMac::IsLowEnergyAvailable()) {
    mock_central_manager_.reset(
        new ScopedMockCentralManager([[MockCentralManager alloc] init]));
    mock_central_manager_->get().bluetoothTestMac = this;
    [mock_central_manager_->get() setState:CBCentralManagerStatePoweredOn];
    adapter_mac_->SetCentralManagerForTesting((id)mock_central_manager_->get());
  }
}

BluetoothDevice* BluetoothTestMac::DiscoverLowEnergyDevice(int device_ordinal) {
  TestBluetoothAdapterObserver observer(adapter_);
  CBCentralManager* central_manager = adapter_mac_->low_energy_central_manager_;
  BluetoothLowEnergyCentralManagerDelegate* central_manager_delegate =
      adapter_mac_->low_energy_central_manager_delegate_;
  switch (device_ordinal) {
    case 1: {
      scoped_nsobject<MockCBPeripheral> mock_peripheral(
          [[MockCBPeripheral alloc]
              initWithUTF8StringIdentifier:kTestPeripheralUUID1.c_str()]);
      NSArray* uuids = @[
        [CBUUID UUIDWithString:@(kTestUUIDGenericAccess.c_str())],
        [CBUUID UUIDWithString:@(kTestUUIDGenericAttribute.c_str())]
      ];
      scoped_nsobject<NSDictionary> advertisement_data =
          CreateAdvertisementData(@(kTestDeviceName.c_str()), uuids);
      [central_manager_delegate centralManager:central_manager
                         didDiscoverPeripheral:mock_peripheral.get().peripheral
                             advertisementData:advertisement_data
                                          RSSI:@(0)];
      break;
    }
    case 2: {
      scoped_nsobject<MockCBPeripheral> mock_peripheral(
          [[MockCBPeripheral alloc]
              initWithUTF8StringIdentifier:kTestPeripheralUUID1.c_str()]);
      NSArray* uuids = @[
        [CBUUID UUIDWithString:@(kTestUUIDImmediateAlert.c_str())],
        [CBUUID UUIDWithString:@(kTestUUIDLinkLoss.c_str())]
      ];
      scoped_nsobject<NSDictionary> advertisement_data =
          CreateAdvertisementData(@(kTestDeviceName.c_str()), uuids);
      [central_manager_delegate centralManager:central_manager
                         didDiscoverPeripheral:mock_peripheral.get().peripheral
                             advertisementData:advertisement_data
                                          RSSI:@(0)];
      break;
    }
    case 3: {
      scoped_nsobject<MockCBPeripheral> mock_peripheral(
          [[MockCBPeripheral alloc]
              initWithUTF8StringIdentifier:kTestPeripheralUUID1.c_str()]);
      scoped_nsobject<NSDictionary> advertisement_data(
          CreateAdvertisementData(@(kTestDeviceNameEmpty.c_str()), nil));
      [central_manager_delegate centralManager:central_manager
                         didDiscoverPeripheral:mock_peripheral.get().peripheral
                             advertisementData:advertisement_data
                                          RSSI:@(0)];
      break;
    }
    case 4: {
      scoped_nsobject<MockCBPeripheral> mock_peripheral(
          [[MockCBPeripheral alloc]
              initWithUTF8StringIdentifier:kTestPeripheralUUID2.c_str()]);
      NSArray* uuids = nil;
      scoped_nsobject<NSDictionary> advertisement_data =
          CreateAdvertisementData(@(kTestDeviceNameEmpty.c_str()), uuids);
      [central_manager_delegate centralManager:central_manager
                         didDiscoverPeripheral:mock_peripheral.get().peripheral
                             advertisementData:advertisement_data
                                          RSSI:@(0)];
      break;
    }
  }
  return observer.last_device();
}

void BluetoothTestMac::SimulateGattConnection(BluetoothDevice* device) {
  BluetoothLowEnergyDeviceMac* lowEnergyDeviceMac =
      static_cast<BluetoothLowEnergyDeviceMac*>(device);
  CBPeripheral* peripheral = lowEnergyDeviceMac->GetPeripheral();
  MockCBPeripheral* mockPeripheral = (MockCBPeripheral*)peripheral;
  [mockPeripheral setState:CBPeripheralStateConnected];
  CBCentralManager* centralManager =
      ObjCCast<CBCentralManager>(mock_central_manager_->get());
  [centralManager.delegate centralManager:centralManager
                     didConnectPeripheral:peripheral];
}

void BluetoothTestMac::SimulateGattDisconnection(BluetoothDevice* device) {
  BluetoothLowEnergyDeviceMac* lowEnergyDeviceMac =
      static_cast<BluetoothLowEnergyDeviceMac*>(device);
  CBPeripheral* peripheral = lowEnergyDeviceMac->GetPeripheral();
  MockCBPeripheral* mockPeripheral = (MockCBPeripheral*)peripheral;
  [mockPeripheral setState:CBPeripheralStateDisconnected];
  CBCentralManager* centralManager =
      ObjCCast<CBCentralManager>(mock_central_manager_->get());
  [centralManager.delegate centralManager:centralManager
                  didDisconnectPeripheral:peripheral
                                    error:nil];
}

void BluetoothTestMac::SimulateGattConnectionError(
    BluetoothDevice* device,
    BluetoothDevice::ConnectErrorCode errorCode) {
  BluetoothLowEnergyDeviceMac* lowEnergyDeviceMac =
      static_cast<BluetoothLowEnergyDeviceMac*>(device);
  CBPeripheral* peripheral = lowEnergyDeviceMac->GetPeripheral();
  MockCBPeripheral* mockPeripheral = (MockCBPeripheral*)peripheral;
  [mockPeripheral setState:CBPeripheralStateDisconnected];
  CBCentralManager* centralManager =
      ObjCCast<CBCentralManager>(mock_central_manager_->get());
  // TODO(http://crbug.com/585894): Need to convert the connect error code into
  // NSError
  NSError* error = [NSError errorWithDomain:@"BluetoothDevice::ConnectErrorCode"
                                       code:-1
                                   userInfo:nil];
  [centralManager.delegate centralManager:centralManager
               didFailToConnectPeripheral:peripheral
                                    error:error];
}

void BluetoothTestMac::OnFakeBluetoothDeviceConnectGattCalled() {
  gatt_connection_attempts_++;
}

void BluetoothTestMac::OnFakeBluetoothGattDisconnect() {
  gatt_disconnection_attempts_++;
}

// Utility function for generating new (CBUUID, address) pairs where CBUUID
// hashes to address. For use when adding a new device address to the testing
// suite because CoreBluetooth peripherals have CBUUIDs in place of addresses,
// and we construct fake addresses for them by hashing the CBUUID. By changing
// |target| the user can generate sequentially numbered test addresses.
//
// std::string BluetoothTestMac::FindCBUUIDForHashTarget() {
//   // The desired first 6 digits of the hash.  For example 0100000, 020000,
//   // 030000, ...
//   const std::string target = "010000";
//   // 128 bit buffer to be encoded as a hex string.
//   int64_t input[2] = {0};
//   // There are 2^24 ~ 10^7 possible configurations for the first 6 digits,
//   // ie. each input has probability 10^-7 of succeeding, under the dubious
//   // assumption that traversing inputs sequentially is as good as traversing
//   // them randomly. After 10^8 iterations then the probability of never
//   // succeeding is ((10^7-1)/10^7)^(10^8) ~= 10^-5.
//   while (input[0] < LLONG_MAX) {
//     // Encode as a hexidecimal number.  Note that on x86 input[0] is stored
//     // as a little-endian number, and so read backwards by HexEncode.
//     std::string input_str = base::HexEncode(&input, sizeof(input));
//     input_str.insert(20, "-");
//     input_str.insert(16, "-");
//     input_str.insert(12, "-");
//     input_str.insert(8, "-");
//     char raw[3];
//     crypto::SHA256HashString(input_str, raw, sizeof(raw));
//     if (base::HexEncode(raw, sizeof(raw)) == target) {
//       return input_str;
//     }
//     ++input[0];
//   }
//   return "";
// }

}  // namespace device