Cleanup: Pass std::string as const reference from pdf/
[chromium-blink-merge.git] / components / proximity_auth / proximity_monitor_impl.cc
blob432485c906599b3230477873863d3a755ebb8f89
1 // Copyright 2015 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.
5 #include "components/proximity_auth/proximity_monitor_impl.h"
7 #include <math.h>
9 #include "base/bind.h"
10 #include "base/location.h"
11 #include "base/thread_task_runner_handle.h"
12 #include "base/time/tick_clock.h"
13 #include "base/time/time.h"
14 #include "components/proximity_auth/logging/logging.h"
15 #include "components/proximity_auth/metrics.h"
16 #include "components/proximity_auth/proximity_monitor_observer.h"
17 #include "device/bluetooth/bluetooth_adapter.h"
18 #include "device/bluetooth/bluetooth_adapter_factory.h"
20 using device::BluetoothDevice;
22 namespace proximity_auth {
24 // The time to wait, in milliseconds, between proximity polling iterations.
25 const int kPollingTimeoutMs = 250;
27 // The RSSI threshold below which we consider the remote device to not be in
28 // proximity.
29 const int kRssiThreshold = -5;
31 // The weight of the most recent RSSI sample.
32 const double kRssiSampleWeight = 0.3;
34 ProximityMonitorImpl::ProximityMonitorImpl(const RemoteDevice& remote_device,
35 scoped_ptr<base::TickClock> clock,
36 ProximityMonitorObserver* observer)
37 : remote_device_(remote_device),
38 observer_(observer),
39 strategy_(Strategy::NONE),
40 remote_device_is_in_proximity_(false),
41 is_active_(false),
42 clock_(clock.Pass()),
43 polling_weak_ptr_factory_(this),
44 weak_ptr_factory_(this) {
45 if (device::BluetoothAdapterFactory::IsBluetoothAdapterAvailable()) {
46 device::BluetoothAdapterFactory::GetAdapter(
47 base::Bind(&ProximityMonitorImpl::OnAdapterInitialized,
48 weak_ptr_factory_.GetWeakPtr()));
49 } else {
50 PA_LOG(ERROR) << "[Proximity] Proximity monitoring unavailable: "
51 << "Bluetooth is unsupported on this platform.";
54 // TODO(isherman): Test prefs to set the strategy. Need to read from "Local
55 // State" prefs on the sign-in screen, and per-user prefs on the lock screen.
56 // TODO(isherman): Unlike in the JS app, destroy and recreate the proximity
57 // monitor when the connection state changes.
60 ProximityMonitorImpl::~ProximityMonitorImpl() {
63 void ProximityMonitorImpl::Start() {
64 is_active_ = true;
65 UpdatePollingState();
68 void ProximityMonitorImpl::Stop() {
69 is_active_ = false;
70 ClearProximityState();
71 UpdatePollingState();
74 ProximityMonitor::Strategy ProximityMonitorImpl::GetStrategy() const {
75 return strategy_;
78 bool ProximityMonitorImpl::IsUnlockAllowed() const {
79 return strategy_ == Strategy::NONE || remote_device_is_in_proximity_;
82 bool ProximityMonitorImpl::IsInRssiRange() const {
83 return (strategy_ != Strategy::NONE && rssi_rolling_average_ &&
84 *rssi_rolling_average_ > kRssiThreshold);
87 void ProximityMonitorImpl::RecordProximityMetricsOnAuthSuccess() {
88 double rssi_rolling_average = rssi_rolling_average_
89 ? *rssi_rolling_average_
90 : metrics::kUnknownProximityValue;
92 int last_transmit_power_delta =
93 last_transmit_power_reading_
94 ? (last_transmit_power_reading_->transmit_power -
95 last_transmit_power_reading_->max_transmit_power)
96 : metrics::kUnknownProximityValue;
98 // If no zero RSSI value has been read, then record an overflow.
99 base::TimeDelta time_since_last_zero_rssi;
100 if (last_zero_rssi_timestamp_)
101 time_since_last_zero_rssi = clock_->NowTicks() - *last_zero_rssi_timestamp_;
102 else
103 time_since_last_zero_rssi = base::TimeDelta::FromDays(100);
105 std::string remote_device_model = metrics::kUnknownDeviceModel;
106 if (remote_device_.name != remote_device_.bluetooth_address)
107 remote_device_model = remote_device_.name;
109 metrics::RecordAuthProximityRollingRssi(round(rssi_rolling_average));
110 metrics::RecordAuthProximityTransmitPowerDelta(last_transmit_power_delta);
111 metrics::RecordAuthProximityTimeSinceLastZeroRssi(time_since_last_zero_rssi);
112 metrics::RecordAuthProximityRemoteDeviceModelHash(remote_device_model);
115 void ProximityMonitorImpl::SetStrategy(Strategy strategy) {
116 if (strategy_ == strategy)
117 return;
118 strategy_ = strategy;
119 CheckForProximityStateChange();
120 UpdatePollingState();
123 ProximityMonitorImpl::TransmitPowerReading::TransmitPowerReading(
124 int transmit_power,
125 int max_transmit_power)
126 : transmit_power(transmit_power), max_transmit_power(max_transmit_power) {
129 bool ProximityMonitorImpl::TransmitPowerReading::IsInProximity() const {
130 return transmit_power < max_transmit_power;
133 void ProximityMonitorImpl::OnAdapterInitialized(
134 scoped_refptr<device::BluetoothAdapter> adapter) {
135 bluetooth_adapter_ = adapter;
136 UpdatePollingState();
139 void ProximityMonitorImpl::UpdatePollingState() {
140 if (ShouldPoll()) {
141 // If there is a polling iteration already scheduled, wait for it.
142 if (polling_weak_ptr_factory_.HasWeakPtrs())
143 return;
145 // Polling can re-entrantly call back into this method, so make sure to
146 // schedule the next polling iteration prior to executing the current one.
147 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
148 FROM_HERE,
149 base::Bind(&ProximityMonitorImpl::PerformScheduledUpdatePollingState,
150 polling_weak_ptr_factory_.GetWeakPtr()),
151 base::TimeDelta::FromMilliseconds(kPollingTimeoutMs));
152 Poll();
153 } else {
154 polling_weak_ptr_factory_.InvalidateWeakPtrs();
155 remote_device_is_in_proximity_ = false;
159 void ProximityMonitorImpl::PerformScheduledUpdatePollingState() {
160 polling_weak_ptr_factory_.InvalidateWeakPtrs();
161 UpdatePollingState();
164 bool ProximityMonitorImpl::ShouldPoll() const {
165 // Note: We poll even if the strategy is NONE so we can record measurements.
166 return is_active_ && bluetooth_adapter_;
169 void ProximityMonitorImpl::Poll() {
170 DCHECK(ShouldPoll());
172 BluetoothDevice* device =
173 bluetooth_adapter_->GetDevice(remote_device_.bluetooth_address);
175 if (!device) {
176 PA_LOG(ERROR) << "Unknown Bluetooth device with address "
177 << remote_device_.bluetooth_address;
178 ClearProximityState();
179 return;
181 if (!device->IsConnected()) {
182 PA_LOG(ERROR) << "Bluetooth device with address "
183 << remote_device_.bluetooth_address << " is not connected.";
184 ClearProximityState();
185 return;
188 device->GetConnectionInfo(base::Bind(&ProximityMonitorImpl::OnConnectionInfo,
189 weak_ptr_factory_.GetWeakPtr()));
192 void ProximityMonitorImpl::OnConnectionInfo(
193 const BluetoothDevice::ConnectionInfo& connection_info) {
194 if (!is_active_) {
195 PA_LOG(INFO) << "[Proximity] Got connection info after stopping";
196 return;
199 if (connection_info.rssi != BluetoothDevice::kUnknownPower &&
200 connection_info.transmit_power != BluetoothDevice::kUnknownPower &&
201 connection_info.max_transmit_power != BluetoothDevice::kUnknownPower) {
202 AddSample(connection_info);
203 } else {
204 PA_LOG(WARNING) << "[Proximity] Unkown values received from API: "
205 << connection_info.rssi << " "
206 << connection_info.transmit_power << " "
207 << connection_info.max_transmit_power;
208 rssi_rolling_average_.reset();
209 last_transmit_power_reading_.reset();
210 CheckForProximityStateChange();
214 void ProximityMonitorImpl::ClearProximityState() {
215 if (is_active_ && remote_device_is_in_proximity_)
216 observer_->OnProximityStateChanged();
218 remote_device_is_in_proximity_ = false;
219 rssi_rolling_average_.reset();
220 last_transmit_power_reading_.reset();
221 last_zero_rssi_timestamp_.reset();
224 void ProximityMonitorImpl::AddSample(
225 const BluetoothDevice::ConnectionInfo& connection_info) {
226 double weight = kRssiSampleWeight;
227 if (!rssi_rolling_average_) {
228 rssi_rolling_average_.reset(new double(connection_info.rssi));
229 } else {
230 *rssi_rolling_average_ =
231 weight * connection_info.rssi + (1 - weight) * (*rssi_rolling_average_);
233 last_transmit_power_reading_.reset(new TransmitPowerReading(
234 connection_info.transmit_power, connection_info.max_transmit_power));
236 // It's rare but possible for the RSSI to be positive briefly.
237 if (connection_info.rssi >= 0)
238 last_zero_rssi_timestamp_.reset(new base::TimeTicks(clock_->NowTicks()));
240 CheckForProximityStateChange();
243 void ProximityMonitorImpl::CheckForProximityStateChange() {
244 if (strategy_ == Strategy::NONE)
245 return;
247 bool is_now_in_proximity = false;
248 switch (strategy_) {
249 case Strategy::NONE:
250 return;
252 case Strategy::CHECK_RSSI:
253 is_now_in_proximity = IsInRssiRange();
254 break;
256 case Strategy::CHECK_TRANSMIT_POWER:
257 is_now_in_proximity = (last_transmit_power_reading_ &&
258 last_transmit_power_reading_->IsInProximity());
259 break;
262 if (remote_device_is_in_proximity_ != is_now_in_proximity) {
263 PA_LOG(INFO) << "[Proximity] Updated proximity state: "
264 << (is_now_in_proximity ? "proximate" : "distant");
265 remote_device_is_in_proximity_ = is_now_in_proximity;
266 observer_->OnProximityStateChanged();
270 } // namespace proximity_auth