bluetooth_system.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. // Copyright 2018 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. #include "services/device/bluetooth/bluetooth_system.h"
  5. #include <algorithm>
  6. #include <array>
  7. #include <memory>
  8. #include <string>
  9. #include <utility>
  10. #include <vector>
  11. #include "base/bind.h"
  12. #include "base/strings/string_util.h"
  13. #include "dbus/object_path.h"
  14. #include "device/bluetooth/bluetooth_device.h"
  15. #include "device/bluetooth/dbus/bluetooth_adapter_client.h"
  16. #include "device/bluetooth/dbus/bluetooth_admin_policy_client.h"
  17. #include "device/bluetooth/dbus/bluetooth_device_client.h"
  18. #include "device/bluetooth/dbus/bluez_dbus_manager.h"
  19. #include "device/bluetooth/public/cpp/bluetooth_address.h"
  20. #include "mojo/public/cpp/bindings/self_owned_receiver.h"
  21. #include "third_party/abseil-cpp/absl/types/optional.h"
  22. namespace device {
  23. namespace {
  24. bool GetDeviceIsBlockedByPolicy(const dbus::ObjectPath& device_path) {
  25. bluez::BluetoothAdminPolicyClient::Properties* properties =
  26. bluez::BluezDBusManager::Get()
  27. ->GetAlternateBluetoothAdminPolicyClient()
  28. ->GetProperties(device_path);
  29. if (!properties)
  30. return false;
  31. if (!properties->is_blocked_by_policy.is_valid())
  32. return false;
  33. return properties->is_blocked_by_policy.value();
  34. }
  35. } // namespace
  36. void BluetoothSystem::Create(
  37. mojo::PendingReceiver<mojom::BluetoothSystem> receiver,
  38. mojo::PendingRemote<mojom::BluetoothSystemClient> client) {
  39. mojo::MakeSelfOwnedReceiver(
  40. std::make_unique<BluetoothSystem>(std::move(client)),
  41. std::move(receiver));
  42. }
  43. BluetoothSystem::BluetoothSystem(
  44. mojo::PendingRemote<mojom::BluetoothSystemClient> client)
  45. : client_(std::move(client)) {
  46. GetBluetoothAdapterClient()->AddObserver(this);
  47. std::vector<dbus::ObjectPath> object_paths =
  48. GetBluetoothAdapterClient()->GetAdapters();
  49. if (object_paths.empty())
  50. return;
  51. active_adapter_ = object_paths[0];
  52. auto* properties =
  53. GetBluetoothAdapterClient()->GetProperties(active_adapter_.value());
  54. state_ = properties->powered.value() ? State::kPoweredOn : State::kPoweredOff;
  55. }
  56. BluetoothSystem::~BluetoothSystem() = default;
  57. void BluetoothSystem::AdapterAdded(const dbus::ObjectPath& object_path) {
  58. if (active_adapter_)
  59. return;
  60. active_adapter_ = object_path;
  61. UpdateStateAndNotifyIfNecessary();
  62. }
  63. void BluetoothSystem::AdapterRemoved(const dbus::ObjectPath& object_path) {
  64. DCHECK(active_adapter_);
  65. if (active_adapter_.value() != object_path)
  66. return;
  67. active_adapter_ = absl::nullopt;
  68. std::vector<dbus::ObjectPath> object_paths =
  69. GetBluetoothAdapterClient()->GetAdapters();
  70. for (const auto& new_object_path : object_paths) {
  71. // The removed adapter is still included in GetAdapters().
  72. if (new_object_path == object_path)
  73. continue;
  74. active_adapter_ = new_object_path;
  75. break;
  76. }
  77. UpdateStateAndNotifyIfNecessary();
  78. }
  79. void BluetoothSystem::AdapterPropertyChanged(
  80. const dbus::ObjectPath& object_path,
  81. const std::string& property_name) {
  82. // AdapterPropertyChanged is called for each property in the adapter before
  83. // AdapterAdded is called. Immediately return in this case.
  84. if (!active_adapter_)
  85. return;
  86. if (active_adapter_.value() != object_path)
  87. return;
  88. auto* properties =
  89. GetBluetoothAdapterClient()->GetProperties(active_adapter_.value());
  90. if (properties->powered.name() == property_name)
  91. UpdateStateAndNotifyIfNecessary();
  92. else if (properties->discovering.name() == property_name)
  93. client_->OnScanStateChanged(GetScanStateFromActiveAdapter());
  94. }
  95. void BluetoothSystem::GetState(GetStateCallback callback) {
  96. std::move(callback).Run(state_);
  97. }
  98. void BluetoothSystem::SetPowered(bool powered, SetPoweredCallback callback) {
  99. switch (state_) {
  100. case State::kUnsupported:
  101. case State::kUnavailable:
  102. std::move(callback).Run(SetPoweredResult::kFailedBluetoothUnavailable);
  103. return;
  104. case State::kTransitioning:
  105. std::move(callback).Run(SetPoweredResult::kFailedInProgress);
  106. return;
  107. case State::kPoweredOff:
  108. case State::kPoweredOn:
  109. break;
  110. }
  111. if ((state_ == State::kPoweredOn) == powered) {
  112. std::move(callback).Run(SetPoweredResult::kSuccess);
  113. return;
  114. }
  115. DCHECK_NE(state_, State::kTransitioning);
  116. state_ = State::kTransitioning;
  117. client_->OnStateChanged(state_);
  118. GetBluetoothAdapterClient()
  119. ->GetProperties(active_adapter_.value())
  120. ->powered.Set(
  121. powered,
  122. base::BindOnce(&BluetoothSystem::OnSetPoweredFinished,
  123. weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  124. }
  125. void BluetoothSystem::GetScanState(GetScanStateCallback callback) {
  126. switch (state_) {
  127. case State::kUnsupported:
  128. case State::kUnavailable:
  129. std::move(callback).Run(ScanState::kNotScanning);
  130. return;
  131. case State::kPoweredOff:
  132. // The Scan State when the adapter is Off should always be
  133. // kNotScanning, but the underlying layer makes no guarantees of this.
  134. // To avoid hiding a bug in the underlying layer, get the state from
  135. // the adapter even if it's Off.
  136. case State::kTransitioning:
  137. case State::kPoweredOn:
  138. break;
  139. }
  140. std::move(callback).Run(GetScanStateFromActiveAdapter());
  141. }
  142. void BluetoothSystem::StartScan(StartScanCallback callback) {
  143. switch (state_) {
  144. case State::kUnsupported:
  145. case State::kUnavailable:
  146. case State::kPoweredOff:
  147. case State::kTransitioning:
  148. std::move(callback).Run(StartScanResult::kFailedBluetoothUnavailable);
  149. return;
  150. case State::kPoweredOn:
  151. break;
  152. }
  153. GetBluetoothAdapterClient()->StartDiscovery(
  154. active_adapter_.value(),
  155. base::BindOnce(&BluetoothSystem::OnStartDiscovery,
  156. weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  157. }
  158. void BluetoothSystem::StopScan(StopScanCallback callback) {
  159. switch (state_) {
  160. case State::kUnsupported:
  161. case State::kUnavailable:
  162. case State::kPoweredOff:
  163. case State::kTransitioning:
  164. std::move(callback).Run(StopScanResult::kFailedBluetoothUnavailable);
  165. return;
  166. case State::kPoweredOn:
  167. break;
  168. }
  169. GetBluetoothAdapterClient()->StopDiscovery(
  170. active_adapter_.value(),
  171. base::BindOnce(&BluetoothSystem::OnStopDiscovery,
  172. weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  173. }
  174. void BluetoothSystem::GetAvailableDevices(
  175. GetAvailableDevicesCallback callback) {
  176. switch (state_) {
  177. case State::kUnsupported:
  178. case State::kUnavailable:
  179. case State::kPoweredOff:
  180. case State::kTransitioning:
  181. std::move(callback).Run({});
  182. return;
  183. case State::kPoweredOn:
  184. break;
  185. }
  186. std::vector<dbus::ObjectPath> device_paths =
  187. GetBluetoothDeviceClient()->GetDevicesForAdapter(active_adapter_.value());
  188. std::vector<mojom::BluetoothDeviceInfoPtr> devices;
  189. for (const auto& device_path : device_paths) {
  190. auto* properties = GetBluetoothDeviceClient()->GetProperties(device_path);
  191. std::array<uint8_t, 6> parsed_address;
  192. if (!ParseBluetoothAddress(properties->address.value(), parsed_address)) {
  193. LOG(WARNING) << "Failed to parse device address '"
  194. << properties->address.value() << "' for "
  195. << device_path.value();
  196. continue;
  197. }
  198. auto device_info = mojom::BluetoothDeviceInfo::New();
  199. device_info->address = std::move(parsed_address);
  200. device_info->name = properties->name.is_valid()
  201. ? absl::make_optional(properties->name.value())
  202. : absl::nullopt;
  203. device_info->connection_state =
  204. properties->connected.value()
  205. ? mojom::BluetoothDeviceInfo::ConnectionState::kConnected
  206. : mojom::BluetoothDeviceInfo::ConnectionState::kNotConnected;
  207. device_info->is_paired = properties->paired.value();
  208. device_info->is_blocked_by_policy = GetDeviceIsBlockedByPolicy(device_path);
  209. // TODO(ortuno): Get the DeviceType from the device Class and Appearance.
  210. devices.push_back(std::move(device_info));
  211. }
  212. std::move(callback).Run(std::move(devices));
  213. }
  214. bluez::BluetoothAdapterClient* BluetoothSystem::GetBluetoothAdapterClient() {
  215. // Use AlternateBluetoothAdapterClient to avoid interfering with users of the
  216. // regular BluetoothAdapterClient.
  217. return bluez::BluezDBusManager::Get()->GetAlternateBluetoothAdapterClient();
  218. }
  219. bluez::BluetoothDeviceClient* BluetoothSystem::GetBluetoothDeviceClient() {
  220. // Use AlternateBluetoothDeviceClient to avoid interfering with users of the
  221. // regular BluetoothDeviceClient.
  222. return bluez::BluezDBusManager::Get()->GetAlternateBluetoothDeviceClient();
  223. }
  224. void BluetoothSystem::UpdateStateAndNotifyIfNecessary() {
  225. State old_state = state_;
  226. if (active_adapter_) {
  227. auto* properties =
  228. GetBluetoothAdapterClient()->GetProperties(active_adapter_.value());
  229. state_ =
  230. properties->powered.value() ? State::kPoweredOn : State::kPoweredOff;
  231. } else {
  232. state_ = State::kUnavailable;
  233. }
  234. if (old_state != state_)
  235. client_->OnStateChanged(state_);
  236. }
  237. BluetoothSystem::ScanState BluetoothSystem::GetScanStateFromActiveAdapter() {
  238. bool discovering = GetBluetoothAdapterClient()
  239. ->GetProperties(active_adapter_.value())
  240. ->discovering.value();
  241. return discovering ? ScanState::kScanning : ScanState::kNotScanning;
  242. }
  243. void BluetoothSystem::OnSetPoweredFinished(SetPoweredCallback callback,
  244. bool succeeded) {
  245. if (!succeeded) {
  246. // We change |state_| to `kTransitioning` before trying to set 'powered'. If
  247. // the call to set 'powered' fails, then we need to change it back to
  248. // `kPoweredOn` or `kPoweredOff` depending on the `active_adapter_` state.
  249. UpdateStateAndNotifyIfNecessary();
  250. }
  251. std::move(callback).Run(succeeded ? SetPoweredResult::kSuccess
  252. : SetPoweredResult::kFailedUnknownReason);
  253. }
  254. void BluetoothSystem::OnStartDiscovery(
  255. StartScanCallback callback,
  256. const absl::optional<bluez::BluetoothAdapterClient::Error>& error) {
  257. // TODO(https://crbug.com/897996): Use the name and message in |error| to
  258. // return more specific error codes.
  259. std::move(callback).Run(error ? StartScanResult::kFailedUnknownReason
  260. : StartScanResult::kSuccess);
  261. }
  262. void BluetoothSystem::OnStopDiscovery(
  263. StopScanCallback callback,
  264. const absl::optional<bluez::BluetoothAdapterClient::Error>& error) {
  265. // TODO(https://crbug.com/897996): Use the name and message in |error| to
  266. // return more specific error codes.
  267. std::move(callback).Run(error ? StopScanResult::kFailedUnknownReason
  268. : StopScanResult::kSuccess);
  269. }
  270. } // namespace device