Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(82)

Side by Side Diff: device/bluetooth/bluetooth_adapter_chromeos.cc

Issue 1367663002: Add Linux support for the Bluetooth API. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@refactor_dbus
Patch Set: Created 5 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "device/bluetooth/bluetooth_adapter_chromeos.h"
6
7 #include <string>
8
9 #include "base/bind.h"
10 #include "base/location.h"
11 #include "base/logging.h"
12 #include "base/metrics/histogram.h"
13 #include "base/sequenced_task_runner.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/thread_task_runner_handle.h"
16 #include "chromeos/system/devicetype.h"
17 #include "device/bluetooth/bluetooth_adapter_profile_chromeos.h"
18 #include "device/bluetooth/bluetooth_advertisement_chromeos.h"
19 #include "device/bluetooth/bluetooth_audio_sink_chromeos.h"
20 #include "device/bluetooth/bluetooth_device.h"
21 #include "device/bluetooth/bluetooth_device_chromeos.h"
22 #include "device/bluetooth/bluetooth_discovery_session_outcome.h"
23 #include "device/bluetooth/bluetooth_pairing_chromeos.h"
24 #include "device/bluetooth/bluetooth_remote_gatt_characteristic_chromeos.h"
25 #include "device/bluetooth/bluetooth_remote_gatt_descriptor_chromeos.h"
26 #include "device/bluetooth/bluetooth_remote_gatt_service_chromeos.h"
27 #include "device/bluetooth/bluetooth_socket_chromeos.h"
28 #include "device/bluetooth/bluetooth_socket_thread.h"
29 #include "device/bluetooth/bluetooth_uuid.h"
30 #include "device/bluetooth/dbus/bluetooth_adapter_client.h"
31 #include "device/bluetooth/dbus/bluetooth_agent_manager_client.h"
32 #include "device/bluetooth/dbus/bluetooth_agent_service_provider.h"
33 #include "device/bluetooth/dbus/bluetooth_device_client.h"
34 #include "device/bluetooth/dbus/bluetooth_input_client.h"
35 #include "device/bluetooth/dbus/bluez_dbus_manager.h"
36 #include "third_party/cros_system_api/dbus/service_constants.h"
37
38 using device::BluetoothAdapter;
39 using device::BluetoothAudioSink;
40 using device::BluetoothDevice;
41 using device::BluetoothDiscoveryFilter;
42 using device::BluetoothSocket;
43 using device::BluetoothUUID;
44 using device::UMABluetoothDiscoverySessionOutcome;
45
46 namespace {
47
48 // The agent path is relatively meaningless since BlueZ only permits one to
49 // exist per D-Bus connection, it just has to be unique within Chromium.
50 const char kAgentPath[] = "/org/chromium/bluetooth_agent";
51
52 void OnUnregisterAgentError(const std::string& error_name,
53 const std::string& error_message) {
54 // It's okay if the agent didn't exist, it means we never saw an adapter.
55 if (error_name == bluetooth_agent_manager::kErrorDoesNotExist)
56 return;
57
58 LOG(WARNING) << "Failed to unregister pairing agent: "
59 << error_name << ": " << error_message;
60 }
61
62 UMABluetoothDiscoverySessionOutcome TranslateDiscoveryErrorToUMA(
63 const std::string& error_name) {
64 if (error_name == bluez::BluetoothAdapterClient::kUnknownAdapterError) {
65 return UMABluetoothDiscoverySessionOutcome::CHROMEOS_DBUS_UNKNOWN_ADAPTER;
66 } else if (error_name == bluez::BluetoothAdapterClient::kNoResponseError) {
67 return UMABluetoothDiscoverySessionOutcome::CHROMEOS_DBUS_NO_RESPONSE;
68 } else if (error_name == bluetooth_device::kErrorInProgress) {
69 return UMABluetoothDiscoverySessionOutcome::CHROMEOS_DBUS_IN_PROGRESS;
70 } else if (error_name == bluetooth_device::kErrorNotReady) {
71 return UMABluetoothDiscoverySessionOutcome::CHROMEOS_DBUS_NOT_READY;
72 } else if (error_name == bluetooth_device::kErrorFailed) {
73 return UMABluetoothDiscoverySessionOutcome::FAILED;
74 } else {
75 LOG(WARNING) << "Can't histogram DBus error " << error_name;
76 return UMABluetoothDiscoverySessionOutcome::UNKNOWN;
77 }
78 }
79
80 } // namespace
81
82 namespace device {
83
84 // static
85 base::WeakPtr<BluetoothAdapter> BluetoothAdapter::CreateAdapter(
86 const InitCallback& init_callback) {
87 return chromeos::BluetoothAdapterChromeOS::CreateAdapter();
88 }
89
90 } // namespace device
91
92 namespace chromeos {
93
94 // static
95 base::WeakPtr<BluetoothAdapter> BluetoothAdapterChromeOS::CreateAdapter() {
96 BluetoothAdapterChromeOS* adapter = new BluetoothAdapterChromeOS();
97 return adapter->weak_ptr_factory_.GetWeakPtr();
98 }
99
100 void BluetoothAdapterChromeOS::Shutdown() {
101 if (dbus_is_shutdown_)
102 return;
103 DCHECK(bluez::BluezDBusManager::IsInitialized())
104 << "Call BluetoothAdapterFactory::Shutdown() before "
105 "BluezDBusManager::Shutdown().";
106
107 if (IsPresent())
108 RemoveAdapter(); // Also deletes devices_.
109 DCHECK(devices_.empty());
110 // profiles_ is empty because all BluetoothSockets have been notified
111 // that this adapter is disappearing.
112 DCHECK(profiles_.empty());
113
114 for (auto& it : profile_queues_)
115 delete it.second;
116 profile_queues_.clear();
117
118 bluez::BluezDBusManager::Get()->GetBluetoothAdapterClient()->RemoveObserver(
119 this);
120 bluez::BluezDBusManager::Get()->GetBluetoothDeviceClient()->RemoveObserver(
121 this);
122 bluez::BluezDBusManager::Get()->GetBluetoothInputClient()->RemoveObserver(
123 this);
124
125 VLOG(1) << "Unregistering pairing agent";
126 bluez::BluezDBusManager::Get()
127 ->GetBluetoothAgentManagerClient()
128 ->UnregisterAgent(dbus::ObjectPath(kAgentPath),
129 base::Bind(&base::DoNothing),
130 base::Bind(&OnUnregisterAgentError));
131
132 agent_.reset();
133 dbus_is_shutdown_ = true;
134 }
135
136 BluetoothAdapterChromeOS::BluetoothAdapterChromeOS()
137 : dbus_is_shutdown_(false),
138 num_discovery_sessions_(0),
139 discovery_request_pending_(false),
140 weak_ptr_factory_(this) {
141 ui_task_runner_ = base::ThreadTaskRunnerHandle::Get();
142 socket_thread_ = device::BluetoothSocketThread::Get();
143
144 bluez::BluezDBusManager::Get()->GetBluetoothAdapterClient()->AddObserver(
145 this);
146 bluez::BluezDBusManager::Get()->GetBluetoothDeviceClient()->AddObserver(this);
147 bluez::BluezDBusManager::Get()->GetBluetoothInputClient()->AddObserver(this);
148
149 // Register the pairing agent.
150 dbus::Bus* system_bus = bluez::BluezDBusManager::Get()->GetSystemBus();
151 agent_.reset(bluez::BluetoothAgentServiceProvider::Create(
152 system_bus, dbus::ObjectPath(kAgentPath), this));
153 DCHECK(agent_.get());
154
155 std::vector<dbus::ObjectPath> object_paths = bluez::BluezDBusManager::Get()
156 ->GetBluetoothAdapterClient()
157 ->GetAdapters();
158
159 if (!object_paths.empty()) {
160 VLOG(1) << object_paths.size() << " Bluetooth adapter(s) available.";
161 SetAdapter(object_paths[0]);
162 }
163 }
164
165 BluetoothAdapterChromeOS::~BluetoothAdapterChromeOS() {
166 Shutdown();
167 }
168
169 std::string BluetoothAdapterChromeOS::GetAddress() const {
170 if (!IsPresent())
171 return std::string();
172
173 bluez::BluetoothAdapterClient::Properties* properties =
174 bluez::BluezDBusManager::Get()
175 ->GetBluetoothAdapterClient()
176 ->GetProperties(object_path_);
177 DCHECK(properties);
178
179 return BluetoothDevice::CanonicalizeAddress(properties->address.value());
180 }
181
182 std::string BluetoothAdapterChromeOS::GetName() const {
183 if (!IsPresent())
184 return std::string();
185
186 bluez::BluetoothAdapterClient::Properties* properties =
187 bluez::BluezDBusManager::Get()
188 ->GetBluetoothAdapterClient()
189 ->GetProperties(object_path_);
190 DCHECK(properties);
191
192 return properties->alias.value();
193 }
194
195 void BluetoothAdapterChromeOS::SetName(const std::string& name,
196 const base::Closure& callback,
197 const ErrorCallback& error_callback) {
198 if (!IsPresent()) {
199 error_callback.Run();
200 return;
201 }
202
203 bluez::BluezDBusManager::Get()
204 ->GetBluetoothAdapterClient()
205 ->GetProperties(object_path_)
206 ->alias.Set(
207 name,
208 base::Bind(&BluetoothAdapterChromeOS::OnPropertyChangeCompleted,
209 weak_ptr_factory_.GetWeakPtr(), callback, error_callback));
210 }
211
212 bool BluetoothAdapterChromeOS::IsInitialized() const {
213 return true;
214 }
215
216 bool BluetoothAdapterChromeOS::IsPresent() const {
217 return !dbus_is_shutdown_ && !object_path_.value().empty();
218 }
219
220 bool BluetoothAdapterChromeOS::IsPowered() const {
221 if (!IsPresent())
222 return false;
223
224 bluez::BluetoothAdapterClient::Properties* properties =
225 bluez::BluezDBusManager::Get()
226 ->GetBluetoothAdapterClient()
227 ->GetProperties(object_path_);
228
229 return properties->powered.value();
230 }
231
232 void BluetoothAdapterChromeOS::SetPowered(
233 bool powered,
234 const base::Closure& callback,
235 const ErrorCallback& error_callback) {
236 if (!IsPresent()) {
237 error_callback.Run();
238 return;
239 }
240
241 bluez::BluezDBusManager::Get()
242 ->GetBluetoothAdapterClient()
243 ->GetProperties(object_path_)
244 ->powered.Set(
245 powered,
246 base::Bind(&BluetoothAdapterChromeOS::OnPropertyChangeCompleted,
247 weak_ptr_factory_.GetWeakPtr(), callback, error_callback));
248 }
249
250 bool BluetoothAdapterChromeOS::IsDiscoverable() const {
251 if (!IsPresent())
252 return false;
253
254 bluez::BluetoothAdapterClient::Properties* properties =
255 bluez::BluezDBusManager::Get()
256 ->GetBluetoothAdapterClient()
257 ->GetProperties(object_path_);
258
259 return properties->discoverable.value();
260 }
261
262 void BluetoothAdapterChromeOS::SetDiscoverable(
263 bool discoverable,
264 const base::Closure& callback,
265 const ErrorCallback& error_callback) {
266 if (!IsPresent()) {
267 error_callback.Run();
268 return;
269 }
270
271 bluez::BluezDBusManager::Get()
272 ->GetBluetoothAdapterClient()
273 ->GetProperties(object_path_)
274 ->discoverable.Set(
275 discoverable,
276 base::Bind(&BluetoothAdapterChromeOS::OnSetDiscoverable,
277 weak_ptr_factory_.GetWeakPtr(), callback, error_callback));
278 }
279
280 bool BluetoothAdapterChromeOS::IsDiscovering() const {
281 if (!IsPresent())
282 return false;
283
284 bluez::BluetoothAdapterClient::Properties* properties =
285 bluez::BluezDBusManager::Get()
286 ->GetBluetoothAdapterClient()
287 ->GetProperties(object_path_);
288
289 return properties->discovering.value();
290 }
291
292 void BluetoothAdapterChromeOS::CreateRfcommService(
293 const BluetoothUUID& uuid,
294 const ServiceOptions& options,
295 const CreateServiceCallback& callback,
296 const CreateServiceErrorCallback& error_callback) {
297 DCHECK(!dbus_is_shutdown_);
298 VLOG(1) << object_path_.value() << ": Creating RFCOMM service: "
299 << uuid.canonical_value();
300 scoped_refptr<BluetoothSocketChromeOS> socket =
301 BluetoothSocketChromeOS::CreateBluetoothSocket(
302 ui_task_runner_, socket_thread_);
303 socket->Listen(this,
304 BluetoothSocketChromeOS::kRfcomm,
305 uuid,
306 options,
307 base::Bind(callback, socket),
308 error_callback);
309 }
310
311 void BluetoothAdapterChromeOS::CreateL2capService(
312 const BluetoothUUID& uuid,
313 const ServiceOptions& options,
314 const CreateServiceCallback& callback,
315 const CreateServiceErrorCallback& error_callback) {
316 DCHECK(!dbus_is_shutdown_);
317 VLOG(1) << object_path_.value() << ": Creating L2CAP service: "
318 << uuid.canonical_value();
319 scoped_refptr<BluetoothSocketChromeOS> socket =
320 BluetoothSocketChromeOS::CreateBluetoothSocket(
321 ui_task_runner_, socket_thread_);
322 socket->Listen(this,
323 BluetoothSocketChromeOS::kL2cap,
324 uuid,
325 options,
326 base::Bind(callback, socket),
327 error_callback);
328 }
329
330 void BluetoothAdapterChromeOS::RegisterAudioSink(
331 const BluetoothAudioSink::Options& options,
332 const device::BluetoothAdapter::AcquiredCallback& callback,
333 const BluetoothAudioSink::ErrorCallback& error_callback) {
334 VLOG(1) << "Registering audio sink";
335 if (!this->IsPresent()) {
336 error_callback.Run(BluetoothAudioSink::ERROR_INVALID_ADAPTER);
337 return;
338 }
339 scoped_refptr<BluetoothAudioSinkChromeOS> audio_sink(
340 new BluetoothAudioSinkChromeOS(this));
341 audio_sink->Register(
342 options, base::Bind(&BluetoothAdapterChromeOS::OnRegisterAudioSink,
343 weak_ptr_factory_.GetWeakPtr(), callback,
344 error_callback, audio_sink),
345 error_callback);
346 }
347
348 void BluetoothAdapterChromeOS::RegisterAdvertisement(
349 scoped_ptr<device::BluetoothAdvertisement::Data> advertisement_data,
350 const CreateAdvertisementCallback& callback,
351 const CreateAdvertisementErrorCallback& error_callback) {
352 scoped_refptr<BluetoothAdvertisementChromeOS> advertisement(
353 new BluetoothAdvertisementChromeOS(advertisement_data.Pass(), this));
354 advertisement->Register(base::Bind(callback, advertisement), error_callback);
355 }
356
357 void BluetoothAdapterChromeOS::RemovePairingDelegateInternal(
358 BluetoothDevice::PairingDelegate* pairing_delegate) {
359 // Check if any device is using the pairing delegate.
360 // If so, clear the pairing context which will make any responses no-ops.
361 for (DevicesMap::iterator iter = devices_.begin();
362 iter != devices_.end(); ++iter) {
363 BluetoothDeviceChromeOS* device_chromeos =
364 static_cast<BluetoothDeviceChromeOS*>(iter->second);
365
366 BluetoothPairingChromeOS* pairing = device_chromeos->GetPairing();
367 if (pairing && pairing->GetPairingDelegate() == pairing_delegate)
368 device_chromeos->EndPairing();
369 }
370 }
371
372 void BluetoothAdapterChromeOS::AdapterAdded(
373 const dbus::ObjectPath& object_path) {
374 // Set the adapter to the newly added adapter only if no adapter is present.
375 if (!IsPresent())
376 SetAdapter(object_path);
377 }
378
379 void BluetoothAdapterChromeOS::AdapterRemoved(
380 const dbus::ObjectPath& object_path) {
381 if (object_path == object_path_)
382 RemoveAdapter();
383 }
384
385 void BluetoothAdapterChromeOS::AdapterPropertyChanged(
386 const dbus::ObjectPath& object_path,
387 const std::string& property_name) {
388 if (object_path != object_path_)
389 return;
390 DCHECK(IsPresent());
391
392 bluez::BluetoothAdapterClient::Properties* properties =
393 bluez::BluezDBusManager::Get()
394 ->GetBluetoothAdapterClient()
395 ->GetProperties(object_path_);
396
397 if (property_name == properties->powered.name()) {
398 PoweredChanged(properties->powered.value());
399 } else if (property_name == properties->discoverable.name()) {
400 DiscoverableChanged(properties->discoverable.value());
401 } else if (property_name == properties->discovering.name()) {
402 DiscoveringChanged(properties->discovering.value());
403 }
404 }
405
406 void BluetoothAdapterChromeOS::DeviceAdded(
407 const dbus::ObjectPath& object_path) {
408 DCHECK(bluez::BluezDBusManager::Get());
409 bluez::BluetoothDeviceClient::Properties* properties =
410 bluez::BluezDBusManager::Get()->GetBluetoothDeviceClient()->GetProperties(
411 object_path);
412 if (!properties || properties->adapter.value() != object_path_)
413 return;
414 DCHECK(IsPresent());
415
416 BluetoothDeviceChromeOS* device_chromeos =
417 new BluetoothDeviceChromeOS(this,
418 object_path,
419 ui_task_runner_,
420 socket_thread_);
421 DCHECK(devices_.find(device_chromeos->GetAddress()) == devices_.end());
422
423 devices_[device_chromeos->GetAddress()] = device_chromeos;
424
425 FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_,
426 DeviceAdded(this, device_chromeos));
427 }
428
429 void BluetoothAdapterChromeOS::DeviceRemoved(
430 const dbus::ObjectPath& object_path) {
431 for (DevicesMap::iterator iter = devices_.begin();
432 iter != devices_.end(); ++iter) {
433 BluetoothDeviceChromeOS* device_chromeos =
434 static_cast<BluetoothDeviceChromeOS*>(iter->second);
435 if (device_chromeos->object_path() == object_path) {
436 devices_.erase(iter);
437
438 FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_,
439 DeviceRemoved(this, device_chromeos));
440 delete device_chromeos;
441 return;
442 }
443 }
444 }
445
446 void BluetoothAdapterChromeOS::DevicePropertyChanged(
447 const dbus::ObjectPath& object_path,
448 const std::string& property_name) {
449 BluetoothDeviceChromeOS* device_chromeos = GetDeviceWithPath(object_path);
450 if (!device_chromeos)
451 return;
452
453 bluez::BluetoothDeviceClient::Properties* properties =
454 bluez::BluezDBusManager::Get()->GetBluetoothDeviceClient()->GetProperties(
455 object_path);
456
457 if (property_name == properties->bluetooth_class.name() ||
458 property_name == properties->address.name() ||
459 property_name == properties->alias.name() ||
460 property_name == properties->paired.name() ||
461 property_name == properties->trusted.name() ||
462 property_name == properties->connected.name() ||
463 property_name == properties->uuids.name() ||
464 property_name == properties->rssi.name() ||
465 property_name == properties->tx_power.name()) {
466 NotifyDeviceChanged(device_chromeos);
467 }
468
469 // When a device becomes paired, mark it as trusted so that the user does
470 // not need to approve every incoming connection
471 if (property_name == properties->paired.name() &&
472 properties->paired.value() && !properties->trusted.value()) {
473 device_chromeos->SetTrusted();
474 }
475
476 // UMA connection counting
477 if (property_name == properties->connected.name()) {
478 // PlayStation joystick tries to reconnect after disconnection from USB.
479 // If it is still not trusted, set it, so it becomes available on the
480 // list of known devices.
481 if (properties->connected.value() && device_chromeos->IsTrustable() &&
482 !properties->trusted.value())
483 device_chromeos->SetTrusted();
484
485 int count = 0;
486
487 for (DevicesMap::iterator iter = devices_.begin();
488 iter != devices_.end(); ++iter) {
489 if (iter->second->IsPaired() && iter->second->IsConnected())
490 ++count;
491 }
492
493 UMA_HISTOGRAM_COUNTS_100("Bluetooth.ConnectedDeviceCount", count);
494 }
495 }
496
497 void BluetoothAdapterChromeOS::InputPropertyChanged(
498 const dbus::ObjectPath& object_path,
499 const std::string& property_name) {
500 BluetoothDeviceChromeOS* device_chromeos = GetDeviceWithPath(object_path);
501 if (!device_chromeos)
502 return;
503
504 bluez::BluetoothInputClient::Properties* properties =
505 bluez::BluezDBusManager::Get()->GetBluetoothInputClient()->GetProperties(
506 object_path);
507
508 // Properties structure can be removed, which triggers a change in the
509 // BluetoothDevice::IsConnectable() property, as does a change in the
510 // actual reconnect_mode property.
511 if (!properties || property_name == properties->reconnect_mode.name()) {
512 NotifyDeviceChanged(device_chromeos);
513 }
514 }
515
516 void BluetoothAdapterChromeOS::Released() {
517 VLOG(1) << "Release";
518 if (!IsPresent())
519 return;
520 DCHECK(agent_.get());
521
522 // Called after we unregister the pairing agent, e.g. when changing I/O
523 // capabilities. Nothing much to be done right now.
524 }
525
526 void BluetoothAdapterChromeOS::RequestPinCode(
527 const dbus::ObjectPath& device_path,
528 const PinCodeCallback& callback) {
529 DCHECK(IsPresent());
530 DCHECK(agent_.get());
531 VLOG(1) << device_path.value() << ": RequestPinCode";
532
533 BluetoothPairingChromeOS* pairing = GetPairing(device_path);
534 if (!pairing) {
535 callback.Run(REJECTED, "");
536 return;
537 }
538
539 pairing->RequestPinCode(callback);
540 }
541
542 void BluetoothAdapterChromeOS::DisplayPinCode(
543 const dbus::ObjectPath& device_path,
544 const std::string& pincode) {
545 DCHECK(IsPresent());
546 DCHECK(agent_.get());
547 VLOG(1) << device_path.value() << ": DisplayPinCode: " << pincode;
548
549 BluetoothPairingChromeOS* pairing = GetPairing(device_path);
550 if (!pairing)
551 return;
552
553 pairing->DisplayPinCode(pincode);
554 }
555
556 void BluetoothAdapterChromeOS::RequestPasskey(
557 const dbus::ObjectPath& device_path,
558 const PasskeyCallback& callback) {
559 DCHECK(IsPresent());
560 DCHECK(agent_.get());
561 VLOG(1) << device_path.value() << ": RequestPasskey";
562
563 BluetoothPairingChromeOS* pairing = GetPairing(device_path);
564 if (!pairing) {
565 callback.Run(REJECTED, 0);
566 return;
567 }
568
569 pairing->RequestPasskey(callback);
570 }
571
572 void BluetoothAdapterChromeOS::DisplayPasskey(
573 const dbus::ObjectPath& device_path,
574 uint32 passkey,
575 uint16 entered) {
576 DCHECK(IsPresent());
577 DCHECK(agent_.get());
578 VLOG(1) << device_path.value() << ": DisplayPasskey: " << passkey
579 << " (" << entered << " entered)";
580
581 BluetoothPairingChromeOS* pairing = GetPairing(device_path);
582 if (!pairing)
583 return;
584
585 if (entered == 0)
586 pairing->DisplayPasskey(passkey);
587
588 pairing->KeysEntered(entered);
589 }
590
591 void BluetoothAdapterChromeOS::RequestConfirmation(
592 const dbus::ObjectPath& device_path,
593 uint32 passkey,
594 const ConfirmationCallback& callback) {
595 DCHECK(IsPresent());
596 DCHECK(agent_.get());
597 VLOG(1) << device_path.value() << ": RequestConfirmation: " << passkey;
598
599 BluetoothPairingChromeOS* pairing = GetPairing(device_path);
600 if (!pairing) {
601 callback.Run(REJECTED);
602 return;
603 }
604
605 pairing->RequestConfirmation(passkey, callback);
606 }
607
608 void BluetoothAdapterChromeOS::RequestAuthorization(
609 const dbus::ObjectPath& device_path,
610 const ConfirmationCallback& callback) {
611 DCHECK(IsPresent());
612 DCHECK(agent_.get());
613 VLOG(1) << device_path.value() << ": RequestAuthorization";
614
615 BluetoothPairingChromeOS* pairing = GetPairing(device_path);
616 if (!pairing) {
617 callback.Run(REJECTED);
618 return;
619 }
620
621 pairing->RequestAuthorization(callback);
622 }
623
624 void BluetoothAdapterChromeOS::AuthorizeService(
625 const dbus::ObjectPath& device_path,
626 const std::string& uuid,
627 const ConfirmationCallback& callback) {
628 DCHECK(IsPresent());
629 DCHECK(agent_.get());
630 VLOG(1) << device_path.value() << ": AuthorizeService: " << uuid;
631
632 BluetoothDeviceChromeOS* device_chromeos = GetDeviceWithPath(device_path);
633 if (!device_chromeos) {
634 callback.Run(CANCELLED);
635 return;
636 }
637
638 // We always set paired devices to Trusted, so the only reason that this
639 // method call would ever be called is in the case of a race condition where
640 // our "Set('Trusted', true)" method call is still pending in the Bluetooth
641 // daemon because it's busy handling the incoming connection.
642 if (device_chromeos->IsPaired()) {
643 callback.Run(SUCCESS);
644 return;
645 }
646
647 // TODO(keybuk): reject service authorizations when not paired, determine
648 // whether this is acceptable long-term.
649 LOG(WARNING) << "Rejecting service connection from unpaired device "
650 << device_chromeos->GetAddress() << " for UUID " << uuid;
651 callback.Run(REJECTED);
652 }
653
654 void BluetoothAdapterChromeOS::Cancel() {
655 DCHECK(IsPresent());
656 DCHECK(agent_.get());
657 VLOG(1) << "Cancel";
658 }
659
660 void BluetoothAdapterChromeOS::OnRegisterAgent() {
661 VLOG(1) << "Pairing agent registered, requesting to be made default";
662
663 bluez::BluezDBusManager::Get()
664 ->GetBluetoothAgentManagerClient()
665 ->RequestDefaultAgent(
666 dbus::ObjectPath(kAgentPath),
667 base::Bind(&BluetoothAdapterChromeOS::OnRequestDefaultAgent,
668 weak_ptr_factory_.GetWeakPtr()),
669 base::Bind(&BluetoothAdapterChromeOS::OnRequestDefaultAgentError,
670 weak_ptr_factory_.GetWeakPtr()));
671 }
672
673 void BluetoothAdapterChromeOS::OnRegisterAgentError(
674 const std::string& error_name,
675 const std::string& error_message) {
676 // Our agent being already registered isn't an error.
677 if (error_name == bluetooth_agent_manager::kErrorAlreadyExists)
678 return;
679
680 LOG(WARNING) << ": Failed to register pairing agent: "
681 << error_name << ": " << error_message;
682 }
683
684 void BluetoothAdapterChromeOS::OnRequestDefaultAgent() {
685 VLOG(1) << "Pairing agent now default";
686 }
687
688 void BluetoothAdapterChromeOS::OnRequestDefaultAgentError(
689 const std::string& error_name,
690 const std::string& error_message) {
691 LOG(WARNING) << ": Failed to make pairing agent default: "
692 << error_name << ": " << error_message;
693 }
694
695 void BluetoothAdapterChromeOS::OnRegisterAudioSink(
696 const device::BluetoothAdapter::AcquiredCallback& callback,
697 const device::BluetoothAudioSink::ErrorCallback& error_callback,
698 scoped_refptr<BluetoothAudioSink> audio_sink) {
699 if (!IsPresent()) {
700 VLOG(1) << "Failed to register audio sink, adapter not present";
701 error_callback.Run(BluetoothAudioSink::ERROR_INVALID_ADAPTER);
702 return;
703 }
704 DCHECK(audio_sink.get());
705 callback.Run(audio_sink);
706 }
707
708 BluetoothDeviceChromeOS*
709 BluetoothAdapterChromeOS::GetDeviceWithPath(
710 const dbus::ObjectPath& object_path) {
711 if (!IsPresent())
712 return nullptr;
713
714 for (DevicesMap::iterator iter = devices_.begin(); iter != devices_.end();
715 ++iter) {
716 BluetoothDeviceChromeOS* device_chromeos =
717 static_cast<BluetoothDeviceChromeOS*>(iter->second);
718 if (device_chromeos->object_path() == object_path)
719 return device_chromeos;
720 }
721
722 return nullptr;
723 }
724
725 BluetoothPairingChromeOS* BluetoothAdapterChromeOS::GetPairing(
726 const dbus::ObjectPath& object_path) {
727 DCHECK(IsPresent());
728 BluetoothDeviceChromeOS* device_chromeos = GetDeviceWithPath(object_path);
729 if (!device_chromeos) {
730 LOG(WARNING) << "Pairing Agent request for unknown device: "
731 << object_path.value();
732 return nullptr;
733 }
734
735 BluetoothPairingChromeOS* pairing = device_chromeos->GetPairing();
736 if (pairing)
737 return pairing;
738
739 // The device doesn't have its own pairing context, so this is an incoming
740 // pairing request that should use our best default delegate (if we have one).
741 BluetoothDevice::PairingDelegate* pairing_delegate = DefaultPairingDelegate();
742 if (!pairing_delegate)
743 return nullptr;
744
745 return device_chromeos->BeginPairing(pairing_delegate);
746 }
747
748 void BluetoothAdapterChromeOS::SetAdapter(const dbus::ObjectPath& object_path) {
749 DCHECK(!IsPresent());
750 DCHECK(!dbus_is_shutdown_);
751 object_path_ = object_path;
752
753 VLOG(1) << object_path_.value() << ": using adapter.";
754
755 VLOG(1) << "Registering pairing agent";
756 bluez::BluezDBusManager::Get()
757 ->GetBluetoothAgentManagerClient()
758 ->RegisterAgent(
759 dbus::ObjectPath(kAgentPath),
760 bluetooth_agent_manager::kKeyboardDisplayCapability,
761 base::Bind(&BluetoothAdapterChromeOS::OnRegisterAgent,
762 weak_ptr_factory_.GetWeakPtr()),
763 base::Bind(&BluetoothAdapterChromeOS::OnRegisterAgentError,
764 weak_ptr_factory_.GetWeakPtr()));
765
766 SetDefaultAdapterName();
767
768 bluez::BluetoothAdapterClient::Properties* properties =
769 bluez::BluezDBusManager::Get()
770 ->GetBluetoothAdapterClient()
771 ->GetProperties(object_path_);
772
773 PresentChanged(true);
774
775 if (properties->powered.value())
776 PoweredChanged(true);
777 if (properties->discoverable.value())
778 DiscoverableChanged(true);
779 if (properties->discovering.value())
780 DiscoveringChanged(true);
781
782 std::vector<dbus::ObjectPath> device_paths =
783 bluez::BluezDBusManager::Get()
784 ->GetBluetoothDeviceClient()
785 ->GetDevicesForAdapter(object_path_);
786
787 for (std::vector<dbus::ObjectPath>::iterator iter = device_paths.begin();
788 iter != device_paths.end(); ++iter) {
789 DeviceAdded(*iter);
790 }
791 }
792
793 void BluetoothAdapterChromeOS::SetDefaultAdapterName() {
794 DCHECK(IsPresent());
795
796 std::string alias;
797 switch (chromeos::GetDeviceType()) {
798 case DeviceType::kChromebase:
799 alias = "Chromebase";
800 break;
801 case DeviceType::kChromebit:
802 alias = "Chromebit";
803 break;
804 case DeviceType::kChromebook:
805 alias = "Chromebook";
806 break;
807 case DeviceType::kChromebox:
808 alias = "Chromebox";
809 break;
810 case DeviceType::kUnknown:
811 alias = "Chromebook";
812 break;
813 }
814
815 SetName(alias, base::Bind(&base::DoNothing), base::Bind(&base::DoNothing));
816 }
817
818 void BluetoothAdapterChromeOS::RemoveAdapter() {
819 DCHECK(IsPresent());
820 VLOG(1) << object_path_.value() << ": adapter removed.";
821
822 bluez::BluetoothAdapterClient::Properties* properties =
823 bluez::BluezDBusManager::Get()
824 ->GetBluetoothAdapterClient()
825 ->GetProperties(object_path_);
826
827 object_path_ = dbus::ObjectPath("");
828
829 if (properties->powered.value())
830 PoweredChanged(false);
831 if (properties->discoverable.value())
832 DiscoverableChanged(false);
833 if (properties->discovering.value())
834 DiscoveringChanged(false);
835
836 // Copy the devices list here and clear the original so that when we
837 // send DeviceRemoved(), GetDevices() returns no devices.
838 DevicesMap devices = devices_;
839 devices_.clear();
840
841 for (DevicesMap::iterator iter = devices.begin();
842 iter != devices.end(); ++iter) {
843 FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_,
844 DeviceRemoved(this, iter->second));
845 delete iter->second;
846 }
847
848 PresentChanged(false);
849 }
850
851 void BluetoothAdapterChromeOS::PoweredChanged(bool powered) {
852 FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_,
853 AdapterPoweredChanged(this, powered));
854 }
855
856 void BluetoothAdapterChromeOS::DiscoverableChanged(bool discoverable) {
857 FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_,
858 AdapterDiscoverableChanged(this, discoverable));
859 }
860
861 void BluetoothAdapterChromeOS::DiscoveringChanged(
862 bool discovering) {
863 // If the adapter stopped discovery due to a reason other than a request by
864 // us, reset the count to 0.
865 VLOG(1) << "Discovering changed: " << discovering;
866 if (!discovering && !discovery_request_pending_ &&
867 num_discovery_sessions_ > 0) {
868 VLOG(1) << "Marking sessions as inactive.";
869 num_discovery_sessions_ = 0;
870 MarkDiscoverySessionsAsInactive();
871 }
872 FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_,
873 AdapterDiscoveringChanged(this, discovering));
874 }
875
876 void BluetoothAdapterChromeOS::PresentChanged(bool present) {
877 FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_,
878 AdapterPresentChanged(this, present));
879 }
880
881 void BluetoothAdapterChromeOS::NotifyDeviceChanged(
882 BluetoothDeviceChromeOS* device) {
883 DCHECK(device);
884 DCHECK(device->adapter_ == this);
885
886 FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_,
887 DeviceChanged(this, device));
888 }
889
890 void BluetoothAdapterChromeOS::NotifyGattServiceAdded(
891 BluetoothRemoteGattServiceChromeOS* service) {
892 DCHECK_EQ(service->GetAdapter(), this);
893 DCHECK_EQ(
894 static_cast<BluetoothDeviceChromeOS*>(service->GetDevice())->adapter_,
895 this);
896
897 FOR_EACH_OBSERVER(BluetoothAdapter::Observer,
898 observers_,
899 GattServiceAdded(this, service->GetDevice(), service));
900 }
901
902 void BluetoothAdapterChromeOS::NotifyGattServiceRemoved(
903 BluetoothRemoteGattServiceChromeOS* service) {
904 DCHECK_EQ(service->GetAdapter(), this);
905 DCHECK_EQ(
906 static_cast<BluetoothDeviceChromeOS*>(service->GetDevice())->adapter_,
907 this);
908
909 FOR_EACH_OBSERVER(BluetoothAdapter::Observer,
910 observers_,
911 GattServiceRemoved(this, service->GetDevice(), service));
912 }
913
914 void BluetoothAdapterChromeOS::NotifyGattServiceChanged(
915 BluetoothRemoteGattServiceChromeOS* service) {
916 DCHECK_EQ(service->GetAdapter(), this);
917
918 FOR_EACH_OBSERVER(BluetoothAdapter::Observer,
919 observers_,
920 GattServiceChanged(this, service));
921 }
922
923 void BluetoothAdapterChromeOS::NotifyGattDiscoveryComplete(
924 BluetoothRemoteGattServiceChromeOS* service) {
925 DCHECK_EQ(service->GetAdapter(), this);
926
927 FOR_EACH_OBSERVER(BluetoothAdapter::Observer,
928 observers_,
929 GattDiscoveryCompleteForService(this, service));
930 }
931
932 void BluetoothAdapterChromeOS::NotifyGattCharacteristicAdded(
933 BluetoothRemoteGattCharacteristicChromeOS* characteristic) {
934 DCHECK_EQ(static_cast<BluetoothRemoteGattServiceChromeOS*>(
935 characteristic->GetService())->GetAdapter(),
936 this);
937
938 FOR_EACH_OBSERVER(BluetoothAdapter::Observer,
939 observers_,
940 GattCharacteristicAdded(this, characteristic));
941 }
942
943 void BluetoothAdapterChromeOS::NotifyGattCharacteristicRemoved(
944 BluetoothRemoteGattCharacteristicChromeOS* characteristic) {
945 DCHECK_EQ(static_cast<BluetoothRemoteGattServiceChromeOS*>(
946 characteristic->GetService())->GetAdapter(),
947 this);
948
949 FOR_EACH_OBSERVER(BluetoothAdapter::Observer,
950 observers_,
951 GattCharacteristicRemoved(this, characteristic));
952 }
953
954 void BluetoothAdapterChromeOS::NotifyGattDescriptorAdded(
955 BluetoothRemoteGattDescriptorChromeOS* descriptor) {
956 DCHECK_EQ(static_cast<BluetoothRemoteGattServiceChromeOS*>(
957 descriptor->GetCharacteristic()->GetService())->GetAdapter(),
958 this);
959
960 FOR_EACH_OBSERVER(BluetoothAdapter::Observer,
961 observers_,
962 GattDescriptorAdded(this, descriptor));
963 }
964
965 void BluetoothAdapterChromeOS::NotifyGattDescriptorRemoved(
966 BluetoothRemoteGattDescriptorChromeOS* descriptor) {
967 DCHECK_EQ(static_cast<BluetoothRemoteGattServiceChromeOS*>(
968 descriptor->GetCharacteristic()->GetService())->GetAdapter(),
969 this);
970
971 FOR_EACH_OBSERVER(BluetoothAdapter::Observer,
972 observers_,
973 GattDescriptorRemoved(this, descriptor));
974 }
975
976 void BluetoothAdapterChromeOS::NotifyGattCharacteristicValueChanged(
977 BluetoothRemoteGattCharacteristicChromeOS* characteristic,
978 const std::vector<uint8>& value) {
979 DCHECK_EQ(static_cast<BluetoothRemoteGattServiceChromeOS*>(
980 characteristic->GetService())->GetAdapter(),
981 this);
982
983 FOR_EACH_OBSERVER(
984 BluetoothAdapter::Observer,
985 observers_,
986 GattCharacteristicValueChanged(this, characteristic, value));
987 }
988
989 void BluetoothAdapterChromeOS::NotifyGattDescriptorValueChanged(
990 BluetoothRemoteGattDescriptorChromeOS* descriptor,
991 const std::vector<uint8>& value) {
992 DCHECK_EQ(static_cast<BluetoothRemoteGattServiceChromeOS*>(
993 descriptor->GetCharacteristic()->GetService())->GetAdapter(),
994 this);
995
996 FOR_EACH_OBSERVER(BluetoothAdapter::Observer,
997 observers_,
998 GattDescriptorValueChanged(this, descriptor, value));
999 }
1000
1001 void BluetoothAdapterChromeOS::UseProfile(
1002 const BluetoothUUID& uuid,
1003 const dbus::ObjectPath& device_path,
1004 const bluez::BluetoothProfileManagerClient::Options& options,
1005 bluez::BluetoothProfileServiceProvider::Delegate* delegate,
1006 const ProfileRegisteredCallback& success_callback,
1007 const ErrorCompletionCallback& error_callback) {
1008 DCHECK(delegate);
1009
1010 if (!IsPresent()) {
1011 VLOG(2) << "Adapter not present, erroring out";
1012 error_callback.Run("Adapter not present");
1013 return;
1014 }
1015
1016 if (profiles_.find(uuid) != profiles_.end()) {
1017 // TODO(jamuraa) check that the options are the same and error when they are
1018 // not.
1019 SetProfileDelegate(uuid, device_path, delegate, success_callback,
1020 error_callback);
1021 return;
1022 }
1023
1024 if (profile_queues_.find(uuid) == profile_queues_.end()) {
1025 BluetoothAdapterProfileChromeOS::Register(
1026 uuid, options,
1027 base::Bind(&BluetoothAdapterChromeOS::OnRegisterProfile, this, uuid),
1028 base::Bind(&BluetoothAdapterChromeOS::OnRegisterProfileError, this,
1029 uuid));
1030
1031 profile_queues_[uuid] = new std::vector<RegisterProfileCompletionPair>();
1032 }
1033
1034 profile_queues_[uuid]->push_back(std::make_pair(
1035 base::Bind(&BluetoothAdapterChromeOS::SetProfileDelegate, this, uuid,
1036 device_path, delegate, success_callback, error_callback),
1037 error_callback));
1038 }
1039
1040 void BluetoothAdapterChromeOS::ReleaseProfile(
1041 const dbus::ObjectPath& device_path,
1042 BluetoothAdapterProfileChromeOS* profile) {
1043 VLOG(2) << "Releasing Profile: " << profile->uuid().canonical_value()
1044 << " from " << device_path.value();
1045 profile->RemoveDelegate(
1046 device_path, base::Bind(&BluetoothAdapterChromeOS::RemoveProfile,
1047 weak_ptr_factory_.GetWeakPtr(), profile->uuid()));
1048 }
1049
1050 void BluetoothAdapterChromeOS::RemoveProfile(const BluetoothUUID& uuid) {
1051 VLOG(2) << "Remove Profile: " << uuid.canonical_value();
1052
1053 if (profiles_.find(uuid) != profiles_.end()) {
1054 delete profiles_[uuid];
1055 profiles_.erase(uuid);
1056 }
1057 }
1058
1059 void BluetoothAdapterChromeOS::OnRegisterProfile(
1060 const BluetoothUUID& uuid,
1061 scoped_ptr<BluetoothAdapterProfileChromeOS> profile) {
1062 profiles_[uuid] = profile.release();
1063
1064 if (profile_queues_.find(uuid) == profile_queues_.end())
1065 return;
1066
1067 for (auto& it : *profile_queues_[uuid])
1068 it.first.Run();
1069 delete profile_queues_[uuid];
1070 profile_queues_.erase(uuid);
1071 }
1072
1073 void BluetoothAdapterChromeOS::SetProfileDelegate(
1074 const BluetoothUUID& uuid,
1075 const dbus::ObjectPath& device_path,
1076 bluez::BluetoothProfileServiceProvider::Delegate* delegate,
1077 const ProfileRegisteredCallback& success_callback,
1078 const ErrorCompletionCallback& error_callback) {
1079 if (profiles_.find(uuid) == profiles_.end()) {
1080 error_callback.Run("Cannot find profile!");
1081 return;
1082 }
1083
1084 if (profiles_[uuid]->SetDelegate(device_path, delegate)) {
1085 success_callback.Run(profiles_[uuid]);
1086 return;
1087 }
1088 // Already set
1089 error_callback.Run(bluetooth_agent_manager::kErrorAlreadyExists);
1090 }
1091
1092 void BluetoothAdapterChromeOS::OnRegisterProfileError(
1093 const BluetoothUUID& uuid,
1094 const std::string& error_name,
1095 const std::string& error_message) {
1096 VLOG(2) << object_path_.value() << ": Failed to register profile: "
1097 << error_name << ": " << error_message;
1098 if (profile_queues_.find(uuid) == profile_queues_.end())
1099 return;
1100
1101 for (auto& it : *profile_queues_[uuid])
1102 it.second.Run(error_message);
1103
1104 delete profile_queues_[uuid];
1105 profile_queues_.erase(uuid);
1106 }
1107
1108 void BluetoothAdapterChromeOS::OnSetDiscoverable(
1109 const base::Closure& callback,
1110 const ErrorCallback& error_callback,
1111 bool success) {
1112 if (!IsPresent()) {
1113 error_callback.Run();
1114 return;
1115 }
1116
1117 // Set the discoverable_timeout property to zero so the adapter remains
1118 // discoverable forever.
1119 bluez::BluezDBusManager::Get()
1120 ->GetBluetoothAdapterClient()
1121 ->GetProperties(object_path_)
1122 ->discoverable_timeout.Set(
1123 0,
1124 base::Bind(&BluetoothAdapterChromeOS::OnPropertyChangeCompleted,
1125 weak_ptr_factory_.GetWeakPtr(), callback, error_callback));
1126 }
1127
1128 void BluetoothAdapterChromeOS::OnPropertyChangeCompleted(
1129 const base::Closure& callback,
1130 const ErrorCallback& error_callback,
1131 bool success) {
1132 if (IsPresent() && success) {
1133 callback.Run();
1134 } else {
1135 error_callback.Run();
1136 }
1137 }
1138
1139 void BluetoothAdapterChromeOS::AddDiscoverySession(
1140 BluetoothDiscoveryFilter* discovery_filter,
1141 const base::Closure& callback,
1142 const DiscoverySessionErrorCallback& error_callback) {
1143 if (!IsPresent()) {
1144 error_callback.Run(
1145 UMABluetoothDiscoverySessionOutcome::ADAPTER_NOT_PRESENT);
1146 return;
1147 }
1148 VLOG(1) << __func__;
1149 if (discovery_request_pending_) {
1150 // The pending request is either to stop a previous session or to start a
1151 // new one. Either way, queue this one.
1152 DCHECK(num_discovery_sessions_ == 1 || num_discovery_sessions_ == 0);
1153 VLOG(1) << "Pending request to start/stop device discovery. Queueing "
1154 << "request to start a new discovery session.";
1155 discovery_request_queue_.push(
1156 std::make_tuple(discovery_filter, callback, error_callback));
1157 return;
1158 }
1159
1160 // The adapter is already discovering.
1161 if (num_discovery_sessions_ > 0) {
1162 DCHECK(IsDiscovering());
1163 DCHECK(!discovery_request_pending_);
1164 num_discovery_sessions_++;
1165 SetDiscoveryFilter(BluetoothDiscoveryFilter::Merge(
1166 GetMergedDiscoveryFilter().get(), discovery_filter),
1167 callback, error_callback);
1168 return;
1169 }
1170
1171 // There are no active discovery sessions.
1172 DCHECK_EQ(num_discovery_sessions_, 0);
1173
1174 if (discovery_filter) {
1175 discovery_request_pending_ = true;
1176
1177 scoped_ptr<BluetoothDiscoveryFilter> df(new BluetoothDiscoveryFilter(
1178 BluetoothDiscoveryFilter::Transport::TRANSPORT_DUAL));
1179 df->CopyFrom(*discovery_filter);
1180 SetDiscoveryFilter(
1181 df.Pass(),
1182 base::Bind(&BluetoothAdapterChromeOS::OnPreSetDiscoveryFilter,
1183 weak_ptr_factory_.GetWeakPtr(), callback, error_callback),
1184 base::Bind(&BluetoothAdapterChromeOS::OnPreSetDiscoveryFilterError,
1185 weak_ptr_factory_.GetWeakPtr(), callback, error_callback));
1186 return;
1187 } else {
1188 current_filter_.reset();
1189 }
1190
1191 // This is the first request to start device discovery.
1192 discovery_request_pending_ = true;
1193 bluez::BluezDBusManager::Get()->GetBluetoothAdapterClient()->StartDiscovery(
1194 object_path_,
1195 base::Bind(&BluetoothAdapterChromeOS::OnStartDiscovery,
1196 weak_ptr_factory_.GetWeakPtr(), callback, error_callback),
1197 base::Bind(&BluetoothAdapterChromeOS::OnStartDiscoveryError,
1198 weak_ptr_factory_.GetWeakPtr(), callback, error_callback));
1199 }
1200
1201 void BluetoothAdapterChromeOS::RemoveDiscoverySession(
1202 BluetoothDiscoveryFilter* discovery_filter,
1203 const base::Closure& callback,
1204 const DiscoverySessionErrorCallback& error_callback) {
1205 if (!IsPresent()) {
1206 error_callback.Run(
1207 UMABluetoothDiscoverySessionOutcome::ADAPTER_NOT_PRESENT);
1208 return;
1209 }
1210
1211 VLOG(1) << __func__;
1212 // There are active sessions other than the one currently being removed.
1213 if (num_discovery_sessions_ > 1) {
1214 DCHECK(IsDiscovering());
1215 DCHECK(!discovery_request_pending_);
1216 num_discovery_sessions_--;
1217
1218 SetDiscoveryFilter(GetMergedDiscoveryFilterMasked(discovery_filter),
1219 callback, error_callback);
1220 return;
1221 }
1222
1223 // If there is a pending request to BlueZ, then queue this request.
1224 if (discovery_request_pending_) {
1225 VLOG(1) << "Pending request to start/stop device discovery. Queueing "
1226 << "request to stop discovery session.";
1227 error_callback.Run(
1228 UMABluetoothDiscoverySessionOutcome::REMOVE_WITH_PENDING_REQUEST);
1229 return;
1230 }
1231
1232 // There are no active sessions. Return error.
1233 if (num_discovery_sessions_ == 0) {
1234 // TODO(armansito): This should never happen once we have the
1235 // DiscoverySession API. Replace this case with an assert once it's
1236 // the deprecated methods have been removed. (See crbug.com/3445008).
1237 VLOG(1) << "No active discovery sessions. Returning error.";
1238 error_callback.Run(
1239 UMABluetoothDiscoverySessionOutcome::ACTIVE_SESSION_NOT_IN_ADAPTER);
1240 return;
1241 }
1242
1243 // There is exactly one active discovery session. Request BlueZ to stop
1244 // discovery.
1245 DCHECK_EQ(num_discovery_sessions_, 1);
1246 discovery_request_pending_ = true;
1247 bluez::BluezDBusManager::Get()->GetBluetoothAdapterClient()->StopDiscovery(
1248 object_path_, base::Bind(&BluetoothAdapterChromeOS::OnStopDiscovery,
1249 weak_ptr_factory_.GetWeakPtr(), callback),
1250 base::Bind(&BluetoothAdapterChromeOS::OnStopDiscoveryError,
1251 weak_ptr_factory_.GetWeakPtr(), error_callback));
1252 }
1253
1254 void BluetoothAdapterChromeOS::SetDiscoveryFilter(
1255 scoped_ptr<BluetoothDiscoveryFilter> discovery_filter,
1256 const base::Closure& callback,
1257 const DiscoverySessionErrorCallback& error_callback) {
1258 if (!IsPresent()) {
1259 error_callback.Run(UMABluetoothDiscoverySessionOutcome::ADAPTER_REMOVED);
1260 return;
1261 }
1262
1263 // If old and new filter are equal (null) then don't make request, just call
1264 // succes callback
1265 if (!current_filter_ && !discovery_filter.get()) {
1266 callback.Run();
1267 return;
1268 }
1269
1270 // If old and new filter are not null and equal then don't make request, just
1271 // call succes callback
1272 if (current_filter_ && discovery_filter &&
1273 current_filter_->Equals(*discovery_filter)) {
1274 callback.Run();
1275 return;
1276 }
1277
1278 current_filter_.reset(discovery_filter.release());
1279
1280 bluez::BluetoothAdapterClient::DiscoveryFilter dbus_discovery_filter;
1281
1282 if (current_filter_.get()) {
1283 uint16_t pathloss;
1284 int16_t rssi;
1285 uint8_t transport;
1286 std::set<device::BluetoothUUID> uuids;
1287
1288 if (current_filter_->GetPathloss(&pathloss))
1289 dbus_discovery_filter.pathloss.reset(new uint16_t(pathloss));
1290
1291 if (current_filter_->GetRSSI(&rssi))
1292 dbus_discovery_filter.rssi.reset(new int16_t(rssi));
1293
1294 transport = current_filter_->GetTransport();
1295 if (transport == BluetoothDiscoveryFilter::Transport::TRANSPORT_LE) {
1296 dbus_discovery_filter.transport.reset(new std::string("le"));
1297 } else if (transport ==
1298 BluetoothDiscoveryFilter::Transport::TRANSPORT_CLASSIC) {
1299 dbus_discovery_filter.transport.reset(new std::string("bredr"));
1300 } else if (transport ==
1301 BluetoothDiscoveryFilter::Transport::TRANSPORT_DUAL) {
1302 dbus_discovery_filter.transport.reset(new std::string("auto"));
1303 }
1304
1305 current_filter_->GetUUIDs(uuids);
1306 if (uuids.size()) {
1307 dbus_discovery_filter.uuids =
1308 scoped_ptr<std::vector<std::string>>(new std::vector<std::string>);
1309
1310 for (const auto& it : uuids)
1311 dbus_discovery_filter.uuids.get()->push_back(it.value());
1312 }
1313 }
1314
1315 bluez::BluezDBusManager::Get()
1316 ->GetBluetoothAdapterClient()
1317 ->SetDiscoveryFilter(
1318 object_path_, dbus_discovery_filter,
1319 base::Bind(&BluetoothAdapterChromeOS::OnSetDiscoveryFilter,
1320 weak_ptr_factory_.GetWeakPtr(), callback, error_callback),
1321 base::Bind(&BluetoothAdapterChromeOS::OnSetDiscoveryFilterError,
1322 weak_ptr_factory_.GetWeakPtr(), callback, error_callback));
1323 }
1324
1325 void BluetoothAdapterChromeOS::OnStartDiscovery(
1326 const base::Closure& callback,
1327 const DiscoverySessionErrorCallback& error_callback) {
1328 // Report success on the original request and increment the count.
1329 VLOG(1) << __func__;
1330 DCHECK(discovery_request_pending_);
1331 DCHECK_EQ(num_discovery_sessions_, 0);
1332 discovery_request_pending_ = false;
1333 num_discovery_sessions_++;
1334 if (IsPresent()) {
1335 callback.Run();
1336 } else {
1337 error_callback.Run(UMABluetoothDiscoverySessionOutcome::ADAPTER_REMOVED);
1338 }
1339
1340 // Try to add a new discovery session for each queued request.
1341 ProcessQueuedDiscoveryRequests();
1342 }
1343
1344 void BluetoothAdapterChromeOS::OnStartDiscoveryError(
1345 const base::Closure& callback,
1346 const DiscoverySessionErrorCallback& error_callback,
1347 const std::string& error_name,
1348 const std::string& error_message) {
1349 LOG(WARNING) << object_path_.value() << ": Failed to start discovery: "
1350 << error_name << ": " << error_message;
1351
1352 // Failed to start discovery. This can only happen if the count is at 0.
1353 DCHECK_EQ(num_discovery_sessions_, 0);
1354 DCHECK(discovery_request_pending_);
1355 discovery_request_pending_ = false;
1356
1357 // Discovery request may fail if discovery was previously initiated by Chrome,
1358 // but the session were invalidated due to the discovery state unexpectedly
1359 // changing to false and then back to true. In this case, report success.
1360 if (IsPresent() && error_name == bluetooth_device::kErrorInProgress &&
1361 IsDiscovering()) {
1362 VLOG(1) << "Discovery previously initiated. Reporting success.";
1363 num_discovery_sessions_++;
1364 callback.Run();
1365 } else {
1366 error_callback.Run(TranslateDiscoveryErrorToUMA(error_name));
1367 }
1368
1369 // Try to add a new discovery session for each queued request.
1370 ProcessQueuedDiscoveryRequests();
1371 }
1372
1373 void BluetoothAdapterChromeOS::OnStopDiscovery(const base::Closure& callback) {
1374 // Report success on the original request and decrement the count.
1375 VLOG(1) << __func__;
1376 DCHECK(discovery_request_pending_);
1377 DCHECK_EQ(num_discovery_sessions_, 1);
1378 discovery_request_pending_ = false;
1379 num_discovery_sessions_--;
1380 callback.Run();
1381
1382 current_filter_.reset();
1383
1384 // Try to add a new discovery session for each queued request.
1385 ProcessQueuedDiscoveryRequests();
1386 }
1387
1388 void BluetoothAdapterChromeOS::OnStopDiscoveryError(
1389 const DiscoverySessionErrorCallback& error_callback,
1390 const std::string& error_name,
1391 const std::string& error_message) {
1392 LOG(WARNING) << object_path_.value() << ": Failed to stop discovery: "
1393 << error_name << ": " << error_message;
1394
1395 // Failed to stop discovery. This can only happen if the count is at 1.
1396 DCHECK(discovery_request_pending_);
1397 DCHECK_EQ(num_discovery_sessions_, 1);
1398 discovery_request_pending_ = false;
1399 error_callback.Run(TranslateDiscoveryErrorToUMA(error_name));
1400
1401 // Try to add a new discovery session for each queued request.
1402 ProcessQueuedDiscoveryRequests();
1403 }
1404
1405 void BluetoothAdapterChromeOS::OnPreSetDiscoveryFilter(
1406 const base::Closure& callback,
1407 const DiscoverySessionErrorCallback& error_callback) {
1408 // This is the first request to start device discovery.
1409 DCHECK(discovery_request_pending_);
1410 DCHECK_EQ(num_discovery_sessions_, 0);
1411
1412 bluez::BluezDBusManager::Get()->GetBluetoothAdapterClient()->StartDiscovery(
1413 object_path_,
1414 base::Bind(&BluetoothAdapterChromeOS::OnStartDiscovery,
1415 weak_ptr_factory_.GetWeakPtr(), callback, error_callback),
1416 base::Bind(&BluetoothAdapterChromeOS::OnStartDiscoveryError,
1417 weak_ptr_factory_.GetWeakPtr(), callback, error_callback));
1418 }
1419
1420 void BluetoothAdapterChromeOS::OnPreSetDiscoveryFilterError(
1421 const base::Closure& callback,
1422 const DiscoverySessionErrorCallback& error_callback,
1423 UMABluetoothDiscoverySessionOutcome outcome) {
1424 LOG(WARNING) << object_path_.value()
1425 << ": Failed to pre set discovery filter.";
1426
1427 // Failed to start discovery. This can only happen if the count is at 0.
1428 DCHECK_EQ(num_discovery_sessions_, 0);
1429 DCHECK(discovery_request_pending_);
1430 discovery_request_pending_ = false;
1431
1432 error_callback.Run(outcome);
1433
1434 // Try to add a new discovery session for each queued request.
1435 ProcessQueuedDiscoveryRequests();
1436 }
1437
1438 void BluetoothAdapterChromeOS::OnSetDiscoveryFilter(
1439 const base::Closure& callback,
1440 const DiscoverySessionErrorCallback& error_callback) {
1441 // Report success on the original request and increment the count.
1442 VLOG(1) << __func__;
1443 if (IsPresent()) {
1444 callback.Run();
1445 } else {
1446 error_callback.Run(UMABluetoothDiscoverySessionOutcome::ADAPTER_REMOVED);
1447 }
1448 }
1449
1450 void BluetoothAdapterChromeOS::OnSetDiscoveryFilterError(
1451 const base::Closure& callback,
1452 const DiscoverySessionErrorCallback& error_callback,
1453 const std::string& error_name,
1454 const std::string& error_message) {
1455 LOG(WARNING) << object_path_.value()
1456 << ": Failed to set discovery filter: " << error_name << ": "
1457 << error_message;
1458
1459 UMABluetoothDiscoverySessionOutcome outcome =
1460 TranslateDiscoveryErrorToUMA(error_name);
1461 if (outcome == UMABluetoothDiscoverySessionOutcome::FAILED) {
1462 // bluez/doc/adapter-api.txt says "Failed" is returned from
1463 // SetDiscoveryFilter when the controller doesn't support the requested
1464 // transport.
1465 outcome = UMABluetoothDiscoverySessionOutcome::
1466 CHROMEOS_DBUS_FAILED_MAYBE_UNSUPPORTED_TRANSPORT;
1467 }
1468 error_callback.Run(outcome);
1469
1470 // Try to add a new discovery session for each queued request.
1471 ProcessQueuedDiscoveryRequests();
1472 }
1473
1474 void BluetoothAdapterChromeOS::ProcessQueuedDiscoveryRequests() {
1475 while (!discovery_request_queue_.empty()) {
1476 VLOG(1) << "Process queued discovery request.";
1477 DiscoveryParamTuple params = discovery_request_queue_.front();
1478 discovery_request_queue_.pop();
1479 AddDiscoverySession(std::get<0>(params), std::get<1>(params),
1480 std::get<2>(params));
1481
1482 // If the queued request resulted in a pending call, then let it
1483 // asynchonously process the remaining queued requests once the pending
1484 // call returns.
1485 if (discovery_request_pending_)
1486 return;
1487 }
1488 }
1489
1490 } // namespace chromeos
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698