File: fake_peripheral.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (393 lines) | stat: -rw-r--r-- 11,431 bytes parent folder | download | duplicates (5)
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
// Copyright 2017 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/emulation/fake_peripheral.h"

#include <algorithm>
#include <memory>
#include <utility>

#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/notimplemented.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/task/single_thread_task_runner.h"
#include "build/build_config.h"
#include "device/bluetooth/emulation/fake_remote_gatt_service.h"
#include "device/bluetooth/public/cpp/bluetooth_uuid.h"

namespace bluetooth {

FakePeripheral::FakePeripheral(FakeCentral* fake_central,
                               const std::string& address)
    : device::BluetoothDevice(fake_central),
      address_(address),
      system_connected_(false),
      gatt_connected_(false),
      last_service_id_(0),
      pending_gatt_discovery_(false),
      fake_central_(*fake_central) {}

FakePeripheral::~FakePeripheral() = default;

void FakePeripheral::SetName(std::optional<std::string> name) {
  name_ = std::move(name);
}

void FakePeripheral::SetSystemConnected(bool connected) {
  system_connected_ = connected;
}

void FakePeripheral::SetServiceUUIDs(UUIDSet service_uuids) {
  device::BluetoothDevice::GattServiceMap gatt_services;
  bool inserted;

  // Create a temporary map of services, because ReplaceServiceUUIDs expects a
  // GattServiceMap even though it only uses the UUIDs.
  int count = 0;
  for (const auto& uuid : service_uuids) {
    std::string id = base::NumberToString(count++);
    std::tie(std::ignore, inserted) =
        gatt_services.emplace(id, std::make_unique<FakeRemoteGattService>(
                                      id, uuid, /*is_primary=*/true, this));
    DCHECK(inserted);
  }
  device_uuids_.ReplaceServiceUUIDs(gatt_services);
}

void FakePeripheral::SetManufacturerData(
    ManufacturerDataMap manufacturer_data) {
  manufacturer_data_ = std::move(manufacturer_data);
}

void FakePeripheral::SetNextGATTConnectionResponse(uint16_t code) {
  DCHECK(!next_connection_response_);
  DCHECK(create_gatt_connection_callbacks_.empty());
  next_connection_response_ = code;
}

void FakePeripheral::SetNextGATTDiscoveryResponse(uint16_t code) {
  DCHECK(!next_discovery_response_);
  next_discovery_response_ = code;
}

void FakePeripheral::SimulateGATTConnectionResponse(uint16_t code) {
  if (code == mojom::kHCISuccess) {
    gatt_connected_ = true;
    DidConnectGatt(/*error_code=*/std::nullopt);
  } else if (code == mojom::kHCIConnectionTimeout) {
    DidConnectGatt(ERROR_FAILED);
  } else {
    DidConnectGatt(ERROR_UNKNOWN);
  }
}

void FakePeripheral::SimulateGATTDiscoveryResponse(uint16_t code) {
  pending_gatt_discovery_ = false;
  if (code == mojom::kHCISuccess) {
    device_uuids_.ReplaceServiceUUIDs(gatt_services_);
    SetGattServicesDiscoveryComplete(true);
    GetAdapter()->NotifyGattServicesDiscovered(this);
  } else {
    SetGattServicesDiscoveryComplete(false);
  }
}

bool FakePeripheral::AllResponsesConsumed() {
  return !next_connection_response_ && !next_discovery_response_ &&
         std::ranges::all_of(gatt_services_, [](const auto& e) {
           return static_cast<FakeRemoteGattService*>(e.second.get())
               ->AllResponsesConsumed();
         });
}

void FakePeripheral::SimulateGATTDisconnection() {
  gatt_services_.clear();
  // TODO(crbug.com/41322843): Only set get_connected_ to false once system
  // connected peripherals are supported and Web Bluetooth uses them. See issue
  // for more details.
  system_connected_ = false;
  gatt_connected_ = false;
  device_uuids_.ClearServiceUUIDs();
  SetGattServicesDiscoveryComplete(false);
  DidDisconnectGatt();
}

std::string FakePeripheral::AddFakeService(
    const device::BluetoothUUID& service_uuid) {
  // Attribute instance Ids need to be unique.
  std::string new_service_id =
      base::StringPrintf("%s_%zu", GetAddress().c_str(), ++last_service_id_);

  auto [it, inserted] = gatt_services_.emplace(
      new_service_id,
      std::make_unique<FakeRemoteGattService>(new_service_id, service_uuid,
                                              true /* is_primary */, this));

  DCHECK(inserted);
  return it->second->GetIdentifier();
}

bool FakePeripheral::RemoveFakeService(const std::string& identifier) {
  auto it = gatt_services_.find(identifier);
  if (it == gatt_services_.end()) {
    return false;
  }

  gatt_services_.erase(it);
  return true;
}

uint32_t FakePeripheral::GetBluetoothClass() const {
  NOTREACHED();
}

#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID)
device::BluetoothTransport FakePeripheral::GetType() const {
  NOTREACHED();
}
#endif  // BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)

std::string FakePeripheral::GetIdentifier() const {
  NOTREACHED();
}

std::string FakePeripheral::GetAddress() const {
  return address_;
}

device::BluetoothDevice::AddressType FakePeripheral::GetAddressType() const {
  NOTREACHED();
}

device::BluetoothDevice::VendorIDSource FakePeripheral::GetVendorIDSource()
    const {
  NOTREACHED();
}

uint16_t FakePeripheral::GetVendorID() const {
  NOTREACHED();
}

uint16_t FakePeripheral::GetProductID() const {
  NOTREACHED();
}

uint16_t FakePeripheral::GetDeviceID() const {
  NOTREACHED();
}

uint16_t FakePeripheral::GetAppearance() const {
  NOTREACHED();
}

std::optional<std::string> FakePeripheral::GetName() const {
  return name_;
}

std::u16string FakePeripheral::GetNameForDisplay() const {
  return std::u16string();
}

bool FakePeripheral::IsPaired() const {
  NOTREACHED();
}

#if BUILDFLAG(IS_CHROMEOS)
bool FakePeripheral::IsBonded() const {
  NOTREACHED();
}
#endif  // BUILDFLAG(IS_CHROMEOS)

bool FakePeripheral::IsConnected() const {
  NOTREACHED();
}

bool FakePeripheral::IsGattConnected() const {
  // TODO(crbug.com/41322843): Return gatt_connected_ only once system connected
  // peripherals are supported and Web Bluetooth uses them. See issue for more
  // details.
  return system_connected_ || gatt_connected_;
}

bool FakePeripheral::IsConnectable() const {
  NOTREACHED();
}

bool FakePeripheral::IsConnecting() const {
  NOTREACHED();
}

bool FakePeripheral::ExpectingPinCode() const {
  NOTREACHED();
}

bool FakePeripheral::ExpectingPasskey() const {
  NOTREACHED();
}

bool FakePeripheral::ExpectingConfirmation() const {
  NOTREACHED();
}

void FakePeripheral::GetConnectionInfo(ConnectionInfoCallback callback) {
  NOTREACHED();
}

void FakePeripheral::SetConnectionLatency(ConnectionLatency connection_latency,
                                          base::OnceClosure callback,
                                          ErrorCallback error_callback) {
  NOTREACHED();
}

void FakePeripheral::Connect(PairingDelegate* pairing_delegate,
                             ConnectCallback callback) {
  NOTREACHED();
}

#if BUILDFLAG(IS_CHROMEOS)
void FakePeripheral::ConnectClassic(PairingDelegate* pairing_delegate,
                                    ConnectCallback callback) {
  NOTREACHED();
}
#endif  // BUILDFLAG(IS_CHROMEOS)

void FakePeripheral::SetPinCode(const std::string& pincode) {
  NOTREACHED();
}

void FakePeripheral::SetPasskey(uint32_t passkey) {
  NOTREACHED();
}

void FakePeripheral::ConfirmPairing() {
  NOTREACHED();
}

void FakePeripheral::RejectPairing() {
  NOTREACHED();
}

void FakePeripheral::CancelPairing() {
  NOTREACHED();
}

void FakePeripheral::Disconnect(base::OnceClosure callback,
                                ErrorCallback error_callback) {
  NOTREACHED();
}

void FakePeripheral::Forget(base::OnceClosure callback,
                            ErrorCallback error_callback) {
  NOTREACHED();
}

void FakePeripheral::ConnectToService(
    const device::BluetoothUUID& uuid,
    ConnectToServiceCallback callback,
    ConnectToServiceErrorCallback error_callback) {
  NOTREACHED();
}

void FakePeripheral::ConnectToServiceInsecurely(
    const device::BluetoothUUID& uuid,
    ConnectToServiceCallback callback,
    ConnectToServiceErrorCallback error_callback) {
  NOTREACHED();
}

void FakePeripheral::CreateGattConnection(
    GattConnectionCallback callback,
    std::optional<device::BluetoothUUID> service_uuid) {
  create_gatt_connection_callbacks_.push_back(std::move(callback));

  // TODO(crbug.com/41322843): Stop overriding CreateGattConnection once
  // IsGattConnected() is fixed. See issue for more details.
  if (gatt_connected_) {
    return DidConnectGatt(/*error_code=*/std::nullopt);
  }

  CreateGattConnectionImpl(std::move(service_uuid));
}

bool FakePeripheral::IsGattServicesDiscoveryComplete() const {
  const bool discovery_complete =
      BluetoothDevice::IsGattServicesDiscoveryComplete();
  DCHECK(!(pending_gatt_discovery_ && discovery_complete));

  // There is currently no method to intiate a Service Discovery procedure.
  // Web Bluetooth keeps a queue of pending getPrimaryServices() requests until
  // BluetoothAdapter::Observer::GattServicesDiscovered is called.
  // We use a call to IsGattServicesDiscoveryComplete as a signal that Web
  // Bluetooth needs to initiate a Service Discovery procedure and post
  // a task to call GattServicesDiscovered to simulate that the procedure has
  // completed.
  // TODO(crbug.com/41323173): Remove this override and run
  // DiscoverGattServices() callback with next_discovery_response_ once
  // DiscoverGattServices() is implemented.
  if (!pending_gatt_discovery_ && !discovery_complete) {
    pending_gatt_discovery_ = true;
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(&FakePeripheral::DispatchDiscoveryEvent,
                                  weak_ptr_factory_.GetWeakPtr()));
  }

  return discovery_complete;
}

#if BUILDFLAG(IS_APPLE)
bool FakePeripheral::IsLowEnergyDevice() {
  NOTIMPLEMENTED();
  return true;
}
#endif  // BUILDFLAG(IS_APPLE)

void FakePeripheral::CreateGattConnectionImpl(
    std::optional<device::BluetoothUUID>) {
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, base::BindOnce(&FakePeripheral::DispatchConnectionEvent,
                                weak_ptr_factory_.GetWeakPtr()));
}

void FakePeripheral::DispatchConnectionEvent() {
  fake_central_->DispatchGATTOperationEvent(
      bluetooth::mojom::GATTOperationType::kConnect, address_);

  if (!next_connection_response_) {
    return;
  }
  uint16_t code = next_connection_response_.value();
  next_connection_response_.reset();
  SimulateGATTConnectionResponse(code);
}

void FakePeripheral::DispatchDiscoveryEvent() {
  fake_central_->DispatchGATTOperationEvent(
      bluetooth::mojom::GATTOperationType::kDiscovery, address_);

  if (!next_discovery_response_) {
    return;
  }
  uint16_t code = next_discovery_response_.value();
  next_discovery_response_.reset();
  SimulateGATTDiscoveryResponse(code);
}

void FakePeripheral::DisconnectGatt() {}

#if BUILDFLAG(IS_CHROMEOS)
void FakePeripheral::ExecuteWrite(base::OnceClosure callback,
                                  ExecuteWriteErrorCallback error_callback) {
  NOTIMPLEMENTED();
}

void FakePeripheral::AbortWrite(base::OnceClosure callback,
                                AbortWriteErrorCallback error_callback) {
  NOTIMPLEMENTED();
}
#endif  // BUILDFLAG(IS_CHROMEOS)

}  // namespace bluetooth