| OLD | NEW |
| (Empty) |
| 1 // Copyright 2016 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/generic_sensor/platform_sensor_reader_win.h" | |
| 6 | |
| 7 #include <Sensors.h> | |
| 8 | |
| 9 #include "base/callback.h" | |
| 10 #include "base/memory/ptr_util.h" | |
| 11 #include "base/threading/thread_task_runner_handle.h" | |
| 12 #include "base/time/time.h" | |
| 13 #include "base/win/iunknown_impl.h" | |
| 14 #include "base/win/scoped_propvariant.h" | |
| 15 #include "device/generic_sensor/generic_sensor_consts.h" | |
| 16 #include "device/generic_sensor/public/cpp/platform_sensor_configuration.h" | |
| 17 #include "device/generic_sensor/public/cpp/sensor_reading.h" | |
| 18 | |
| 19 namespace device { | |
| 20 | |
| 21 // Init params for the PlatformSensorReaderWin. | |
| 22 struct ReaderInitParams { | |
| 23 // ISensorDataReport::GetSensorValue is not const, therefore, report | |
| 24 // cannot be passed as const ref. | |
| 25 // ISensorDataReport& report - report that contains new sensor data. | |
| 26 // SensorReading& reading - out parameter that must be populated. | |
| 27 // Returns HRESULT - S_OK on success, otherwise error code. | |
| 28 using ReaderFunctor = base::Callback<HRESULT(ISensorDataReport& report, | |
| 29 SensorReading& reading)>; | |
| 30 SENSOR_TYPE_ID sensor_type_id; | |
| 31 ReaderFunctor reader_func; | |
| 32 unsigned long min_reporting_interval_ms = 0; | |
| 33 }; | |
| 34 | |
| 35 namespace { | |
| 36 | |
| 37 // Gets value from the report for provided key. | |
| 38 bool GetReadingValueForProperty(REFPROPERTYKEY key, | |
| 39 ISensorDataReport& report, | |
| 40 double* value) { | |
| 41 DCHECK(value); | |
| 42 base::win::ScopedPropVariant variant_value; | |
| 43 if (SUCCEEDED(report.GetSensorValue(key, variant_value.Receive()))) { | |
| 44 if (variant_value.get().vt == VT_R8) | |
| 45 *value = variant_value.get().dblVal; | |
| 46 else if (variant_value.get().vt == VT_R4) | |
| 47 *value = variant_value.get().fltVal; | |
| 48 else | |
| 49 return false; | |
| 50 return true; | |
| 51 } | |
| 52 | |
| 53 *value = 0; | |
| 54 return false; | |
| 55 } | |
| 56 | |
| 57 // Ambient light sensor reader initialization parameters. | |
| 58 std::unique_ptr<ReaderInitParams> CreateAmbientLightReaderInitParams() { | |
| 59 auto params = base::MakeUnique<ReaderInitParams>(); | |
| 60 params->sensor_type_id = SENSOR_TYPE_AMBIENT_LIGHT; | |
| 61 params->reader_func = | |
| 62 base::Bind([](ISensorDataReport& report, SensorReading& reading) { | |
| 63 double lux = 0.0; | |
| 64 if (!GetReadingValueForProperty(SENSOR_DATA_TYPE_LIGHT_LEVEL_LUX, | |
| 65 report, &lux)) { | |
| 66 return E_FAIL; | |
| 67 } | |
| 68 reading.values[0] = lux; | |
| 69 return S_OK; | |
| 70 }); | |
| 71 return params; | |
| 72 } | |
| 73 | |
| 74 // Accelerometer sensor reader initialization parameters. | |
| 75 std::unique_ptr<ReaderInitParams> CreateAccelerometerReaderInitParams() { | |
| 76 auto params = base::MakeUnique<ReaderInitParams>(); | |
| 77 params->sensor_type_id = SENSOR_TYPE_ACCELEROMETER_3D; | |
| 78 params->reader_func = | |
| 79 base::Bind([](ISensorDataReport& report, SensorReading& reading) { | |
| 80 double x = 0.0; | |
| 81 double y = 0.0; | |
| 82 double z = 0.0; | |
| 83 if (!GetReadingValueForProperty(SENSOR_DATA_TYPE_ACCELERATION_X_G, | |
| 84 report, &x) || | |
| 85 !GetReadingValueForProperty(SENSOR_DATA_TYPE_ACCELERATION_Y_G, | |
| 86 report, &y) || | |
| 87 !GetReadingValueForProperty(SENSOR_DATA_TYPE_ACCELERATION_Z_G, | |
| 88 report, &z)) { | |
| 89 return E_FAIL; | |
| 90 } | |
| 91 | |
| 92 // Windows uses coordinate system where Z axis points down from device | |
| 93 // screen, therefore, using right hand notation, we have to reverse | |
| 94 // sign for each axis. Values are converted from G/s^2 to m/s^2. | |
| 95 reading.values[0] = -x * kMeanGravity; | |
| 96 reading.values[1] = -y * kMeanGravity; | |
| 97 reading.values[2] = -z * kMeanGravity; | |
| 98 return S_OK; | |
| 99 }); | |
| 100 return params; | |
| 101 } | |
| 102 | |
| 103 // Gyroscope sensor reader initialization parameters. | |
| 104 std::unique_ptr<ReaderInitParams> CreateGyroscopeReaderInitParams() { | |
| 105 auto params = base::MakeUnique<ReaderInitParams>(); | |
| 106 params->sensor_type_id = SENSOR_TYPE_GYROMETER_3D; | |
| 107 params->reader_func = base::Bind([](ISensorDataReport& report, | |
| 108 SensorReading& reading) { | |
| 109 double x = 0.0; | |
| 110 double y = 0.0; | |
| 111 double z = 0.0; | |
| 112 if (!GetReadingValueForProperty( | |
| 113 SENSOR_DATA_TYPE_ANGULAR_VELOCITY_X_DEGREES_PER_SECOND, report, | |
| 114 &x) || | |
| 115 !GetReadingValueForProperty( | |
| 116 SENSOR_DATA_TYPE_ANGULAR_VELOCITY_Y_DEGREES_PER_SECOND, report, | |
| 117 &y) || | |
| 118 !GetReadingValueForProperty( | |
| 119 SENSOR_DATA_TYPE_ANGULAR_VELOCITY_Z_DEGREES_PER_SECOND, report, | |
| 120 &z)) { | |
| 121 return E_FAIL; | |
| 122 } | |
| 123 | |
| 124 // Windows uses coordinate system where Z axis points down from device | |
| 125 // screen, therefore, using right hand notation, we have to reverse | |
| 126 // sign for each axis. Values are converted from deg to rad. | |
| 127 reading.values[0] = -x * kRadiansInDegrees; | |
| 128 reading.values[1] = -y * kRadiansInDegrees; | |
| 129 reading.values[2] = -z * kRadiansInDegrees; | |
| 130 return S_OK; | |
| 131 }); | |
| 132 return params; | |
| 133 } | |
| 134 | |
| 135 // Magnetometer sensor reader initialization parameters. | |
| 136 std::unique_ptr<ReaderInitParams> CreateMagnetometerReaderInitParams() { | |
| 137 auto params = base::MakeUnique<ReaderInitParams>(); | |
| 138 params->sensor_type_id = SENSOR_TYPE_COMPASS_3D; | |
| 139 params->reader_func = | |
| 140 base::Bind([](ISensorDataReport& report, SensorReading& reading) { | |
| 141 double x = 0.0; | |
| 142 double y = 0.0; | |
| 143 double z = 0.0; | |
| 144 if (!GetReadingValueForProperty( | |
| 145 SENSOR_DATA_TYPE_MAGNETIC_FIELD_STRENGTH_X_MILLIGAUSS, report, | |
| 146 &x) || | |
| 147 !GetReadingValueForProperty( | |
| 148 SENSOR_DATA_TYPE_MAGNETIC_FIELD_STRENGTH_Y_MILLIGAUSS, report, | |
| 149 &y) || | |
| 150 !GetReadingValueForProperty( | |
| 151 SENSOR_DATA_TYPE_MAGNETIC_FIELD_STRENGTH_Z_MILLIGAUSS, report, | |
| 152 &z)) { | |
| 153 return E_FAIL; | |
| 154 } | |
| 155 | |
| 156 // Windows uses coordinate system where Z axis points down from device | |
| 157 // screen, therefore, using right hand notation, we have to reverse | |
| 158 // sign for each axis. Values are converted from Milligaus to | |
| 159 // Microtesla. | |
| 160 reading.values[0] = -x * kMicroteslaInMilligauss; | |
| 161 reading.values[1] = -y * kMicroteslaInMilligauss; | |
| 162 reading.values[2] = -z * kMicroteslaInMilligauss; | |
| 163 return S_OK; | |
| 164 }); | |
| 165 return params; | |
| 166 } | |
| 167 | |
| 168 // AbsoluteOrientation sensor reader initialization parameters. | |
| 169 std::unique_ptr<ReaderInitParams> CreateAbsoluteOrientationReaderInitParams() { | |
| 170 auto params = base::MakeUnique<ReaderInitParams>(); | |
| 171 params->sensor_type_id = SENSOR_TYPE_AGGREGATED_DEVICE_ORIENTATION; | |
| 172 params->reader_func = | |
| 173 base::Bind([](ISensorDataReport& report, SensorReading& reading) { | |
| 174 base::win::ScopedPropVariant quat_variant; | |
| 175 HRESULT hr = report.GetSensorValue(SENSOR_DATA_TYPE_QUATERNION, | |
| 176 quat_variant.Receive()); | |
| 177 if (FAILED(hr) || quat_variant.get().vt != (VT_VECTOR | VT_UI1) || | |
| 178 quat_variant.get().caub.cElems < 16) { | |
| 179 return E_FAIL; | |
| 180 } | |
| 181 | |
| 182 float* quat = reinterpret_cast<float*>(quat_variant.get().caub.pElems); | |
| 183 | |
| 184 // Windows uses coordinate system where Z axis points down from device | |
| 185 // screen, therefore, using right hand notation, we have to reverse | |
| 186 // sign for each quaternion component. | |
| 187 reading.values[0] = -quat[0]; // x*sin(Theta/2) | |
| 188 reading.values[1] = -quat[1]; // y*sin(Theta/2) | |
| 189 reading.values[2] = -quat[2]; // z*sin(Theta/2) | |
| 190 reading.values[3] = quat[3]; // cos(Theta/2) | |
| 191 return S_OK; | |
| 192 }); | |
| 193 return params; | |
| 194 } | |
| 195 | |
| 196 // Creates ReaderInitParams params structure. To implement support for new | |
| 197 // sensor types, new switch case should be added and appropriate fields must | |
| 198 // be set: | |
| 199 // sensor_type_id - GUID of the sensor supported by Windows. | |
| 200 // reader_func - Functor that is responsible to populate SensorReading from | |
| 201 // ISensorDataReport data. | |
| 202 std::unique_ptr<ReaderInitParams> CreateReaderInitParamsForSensor( | |
| 203 mojom::SensorType type) { | |
| 204 switch (type) { | |
| 205 case mojom::SensorType::AMBIENT_LIGHT: | |
| 206 return CreateAmbientLightReaderInitParams(); | |
| 207 case mojom::SensorType::ACCELEROMETER: | |
| 208 return CreateAccelerometerReaderInitParams(); | |
| 209 case mojom::SensorType::GYROSCOPE: | |
| 210 return CreateGyroscopeReaderInitParams(); | |
| 211 case mojom::SensorType::MAGNETOMETER: | |
| 212 return CreateMagnetometerReaderInitParams(); | |
| 213 case mojom::SensorType::ABSOLUTE_ORIENTATION: | |
| 214 return CreateAbsoluteOrientationReaderInitParams(); | |
| 215 default: | |
| 216 NOTIMPLEMENTED(); | |
| 217 return nullptr; | |
| 218 } | |
| 219 } | |
| 220 | |
| 221 } // namespace | |
| 222 | |
| 223 // Class that implements ISensorEvents and IUnknown interfaces and used | |
| 224 // by ISensor interface to dispatch state and data change events. | |
| 225 class EventListener : public ISensorEvents, public base::win::IUnknownImpl { | |
| 226 public: | |
| 227 explicit EventListener(PlatformSensorReaderWin* platform_sensor_reader) | |
| 228 : platform_sensor_reader_(platform_sensor_reader) { | |
| 229 DCHECK(platform_sensor_reader_); | |
| 230 } | |
| 231 | |
| 232 // IUnknown interface | |
| 233 ULONG STDMETHODCALLTYPE AddRef() override { return IUnknownImpl::AddRef(); } | |
| 234 ULONG STDMETHODCALLTYPE Release() override { return IUnknownImpl::Release(); } | |
| 235 | |
| 236 STDMETHODIMP QueryInterface(REFIID riid, void** ppv) override { | |
| 237 if (riid == __uuidof(ISensorEvents)) { | |
| 238 *ppv = static_cast<ISensorEvents*>(this); | |
| 239 AddRef(); | |
| 240 return S_OK; | |
| 241 } | |
| 242 return IUnknownImpl::QueryInterface(riid, ppv); | |
| 243 } | |
| 244 | |
| 245 protected: | |
| 246 ~EventListener() override = default; | |
| 247 | |
| 248 // ISensorEvents interface | |
| 249 STDMETHODIMP OnEvent(ISensor*, REFGUID, IPortableDeviceValues*) override { | |
| 250 return S_OK; | |
| 251 } | |
| 252 | |
| 253 STDMETHODIMP OnLeave(REFSENSOR_ID sensor_id) override { | |
| 254 // If event listener is active and sensor is disconnected, notify client | |
| 255 // about the error. | |
| 256 platform_sensor_reader_->SensorError(); | |
| 257 platform_sensor_reader_->StopSensor(); | |
| 258 return S_OK; | |
| 259 } | |
| 260 | |
| 261 STDMETHODIMP OnStateChanged(ISensor* sensor, SensorState state) override { | |
| 262 if (sensor == nullptr) | |
| 263 return E_INVALIDARG; | |
| 264 | |
| 265 if (state != SensorState::SENSOR_STATE_READY && | |
| 266 state != SensorState::SENSOR_STATE_INITIALIZING) { | |
| 267 platform_sensor_reader_->SensorError(); | |
| 268 platform_sensor_reader_->StopSensor(); | |
| 269 } | |
| 270 return S_OK; | |
| 271 } | |
| 272 | |
| 273 STDMETHODIMP OnDataUpdated(ISensor* sensor, | |
| 274 ISensorDataReport* report) override { | |
| 275 if (sensor == nullptr || report == nullptr) | |
| 276 return E_INVALIDARG; | |
| 277 | |
| 278 // To get precise timestamp, we need to get delta between timestamp | |
| 279 // provided in the report and current system time. Then the delta in | |
| 280 // milliseconds is substracted from current high resolution timestamp. | |
| 281 SYSTEMTIME report_time; | |
| 282 HRESULT hr = report->GetTimestamp(&report_time); | |
| 283 if (FAILED(hr)) | |
| 284 return hr; | |
| 285 | |
| 286 base::TimeTicks ticks_now = base::TimeTicks::Now(); | |
| 287 base::Time time_now = base::Time::NowFromSystemTime(); | |
| 288 | |
| 289 base::Time::Exploded exploded; | |
| 290 exploded.year = report_time.wYear; | |
| 291 exploded.month = report_time.wMonth; | |
| 292 exploded.day_of_week = report_time.wDayOfWeek; | |
| 293 exploded.day_of_month = report_time.wDay; | |
| 294 exploded.hour = report_time.wHour; | |
| 295 exploded.minute = report_time.wMinute; | |
| 296 exploded.second = report_time.wSecond; | |
| 297 exploded.millisecond = report_time.wMilliseconds; | |
| 298 | |
| 299 base::Time timestamp; | |
| 300 if (!base::Time::FromUTCExploded(exploded, ×tamp)) | |
| 301 return E_FAIL; | |
| 302 | |
| 303 base::TimeDelta delta = time_now - timestamp; | |
| 304 | |
| 305 SensorReading reading; | |
| 306 reading.timestamp = ((ticks_now - delta) - base::TimeTicks()).InSecondsF(); | |
| 307 | |
| 308 // Discard update events that have non-monotonically increasing timestamp. | |
| 309 if (last_sensor_reading_.timestamp > reading.timestamp) | |
| 310 return E_FAIL; | |
| 311 | |
| 312 hr = platform_sensor_reader_->SensorReadingChanged(*report, reading); | |
| 313 if (SUCCEEDED(hr)) | |
| 314 last_sensor_reading_ = reading; | |
| 315 return hr; | |
| 316 } | |
| 317 | |
| 318 private: | |
| 319 PlatformSensorReaderWin* const platform_sensor_reader_; | |
| 320 SensorReading last_sensor_reading_; | |
| 321 | |
| 322 DISALLOW_COPY_AND_ASSIGN(EventListener); | |
| 323 }; | |
| 324 | |
| 325 // static | |
| 326 std::unique_ptr<PlatformSensorReaderWin> PlatformSensorReaderWin::Create( | |
| 327 mojom::SensorType type, | |
| 328 base::win::ScopedComPtr<ISensorManager> sensor_manager) { | |
| 329 DCHECK(sensor_manager); | |
| 330 | |
| 331 auto params = CreateReaderInitParamsForSensor(type); | |
| 332 if (!params) | |
| 333 return nullptr; | |
| 334 | |
| 335 auto sensor = GetSensorForType(params->sensor_type_id, sensor_manager); | |
| 336 if (!sensor) | |
| 337 return nullptr; | |
| 338 | |
| 339 base::win::ScopedPropVariant min_interval; | |
| 340 HRESULT hr = sensor->GetProperty(SENSOR_PROPERTY_MIN_REPORT_INTERVAL, | |
| 341 min_interval.Receive()); | |
| 342 if (SUCCEEDED(hr) && min_interval.get().vt == VT_UI4) | |
| 343 params->min_reporting_interval_ms = min_interval.get().ulVal; | |
| 344 | |
| 345 GUID interests[] = {SENSOR_EVENT_STATE_CHANGED, SENSOR_EVENT_DATA_UPDATED}; | |
| 346 hr = sensor->SetEventInterest(interests, arraysize(interests)); | |
| 347 if (FAILED(hr)) | |
| 348 return nullptr; | |
| 349 | |
| 350 return base::WrapUnique( | |
| 351 new PlatformSensorReaderWin(sensor, std::move(params))); | |
| 352 } | |
| 353 | |
| 354 // static | |
| 355 base::win::ScopedComPtr<ISensor> PlatformSensorReaderWin::GetSensorForType( | |
| 356 REFSENSOR_TYPE_ID sensor_type, | |
| 357 base::win::ScopedComPtr<ISensorManager> sensor_manager) { | |
| 358 base::win::ScopedComPtr<ISensor> sensor; | |
| 359 base::win::ScopedComPtr<ISensorCollection> sensor_collection; | |
| 360 HRESULT hr = sensor_manager->GetSensorsByType( | |
| 361 sensor_type, sensor_collection.GetAddressOf()); | |
| 362 if (FAILED(hr) || !sensor_collection) | |
| 363 return sensor; | |
| 364 | |
| 365 ULONG count = 0; | |
| 366 hr = sensor_collection->GetCount(&count); | |
| 367 if (SUCCEEDED(hr) && count > 0) | |
| 368 sensor_collection->GetAt(0, sensor.GetAddressOf()); | |
| 369 return sensor; | |
| 370 } | |
| 371 | |
| 372 PlatformSensorReaderWin::PlatformSensorReaderWin( | |
| 373 base::win::ScopedComPtr<ISensor> sensor, | |
| 374 std::unique_ptr<ReaderInitParams> params) | |
| 375 : init_params_(std::move(params)), | |
| 376 task_runner_(base::ThreadTaskRunnerHandle::Get()), | |
| 377 sensor_active_(false), | |
| 378 client_(nullptr), | |
| 379 sensor_(sensor), | |
| 380 event_listener_(new EventListener(this)), | |
| 381 weak_factory_(this) { | |
| 382 DCHECK(init_params_); | |
| 383 DCHECK(!init_params_->reader_func.is_null()); | |
| 384 DCHECK(sensor_); | |
| 385 } | |
| 386 | |
| 387 void PlatformSensorReaderWin::SetClient(Client* client) { | |
| 388 base::AutoLock autolock(lock_); | |
| 389 // Can be null. | |
| 390 client_ = client; | |
| 391 } | |
| 392 | |
| 393 void PlatformSensorReaderWin::StopSensor() { | |
| 394 base::AutoLock autolock(lock_); | |
| 395 if (sensor_active_) { | |
| 396 sensor_->SetEventSink(nullptr); | |
| 397 sensor_active_ = false; | |
| 398 } | |
| 399 } | |
| 400 | |
| 401 PlatformSensorReaderWin::~PlatformSensorReaderWin() { | |
| 402 DCHECK(task_runner_->BelongsToCurrentThread()); | |
| 403 } | |
| 404 | |
| 405 bool PlatformSensorReaderWin::StartSensor( | |
| 406 const PlatformSensorConfiguration& configuration) { | |
| 407 base::AutoLock autolock(lock_); | |
| 408 | |
| 409 if (!SetReportingInterval(configuration)) | |
| 410 return false; | |
| 411 | |
| 412 if (!sensor_active_) { | |
| 413 task_runner_->PostTask( | |
| 414 FROM_HERE, base::Bind(&PlatformSensorReaderWin::ListenSensorEvent, | |
| 415 weak_factory_.GetWeakPtr())); | |
| 416 sensor_active_ = true; | |
| 417 } | |
| 418 | |
| 419 return true; | |
| 420 } | |
| 421 | |
| 422 void PlatformSensorReaderWin::ListenSensorEvent() { | |
| 423 // Set event listener. | |
| 424 if (FAILED(sensor_->SetEventSink(event_listener_.get()))) { | |
| 425 SensorError(); | |
| 426 StopSensor(); | |
| 427 } | |
| 428 } | |
| 429 | |
| 430 bool PlatformSensorReaderWin::SetReportingInterval( | |
| 431 const PlatformSensorConfiguration& configuration) { | |
| 432 base::win::ScopedComPtr<IPortableDeviceValues> props; | |
| 433 if (SUCCEEDED(props.CreateInstance(CLSID_PortableDeviceValues))) { | |
| 434 unsigned interval = | |
| 435 (1 / configuration.frequency()) * base::Time::kMillisecondsPerSecond; | |
| 436 | |
| 437 HRESULT hr = props->SetUnsignedIntegerValue( | |
| 438 SENSOR_PROPERTY_CURRENT_REPORT_INTERVAL, interval); | |
| 439 | |
| 440 if (SUCCEEDED(hr)) { | |
| 441 base::win::ScopedComPtr<IPortableDeviceValues> return_props; | |
| 442 hr = sensor_->SetProperties(props.Get(), return_props.GetAddressOf()); | |
| 443 return SUCCEEDED(hr); | |
| 444 } | |
| 445 } | |
| 446 return false; | |
| 447 } | |
| 448 | |
| 449 HRESULT PlatformSensorReaderWin::SensorReadingChanged( | |
| 450 ISensorDataReport& report, | |
| 451 SensorReading& reading) const { | |
| 452 if (!client_) | |
| 453 return E_FAIL; | |
| 454 | |
| 455 HRESULT hr = init_params_->reader_func.Run(report, reading); | |
| 456 if (SUCCEEDED(hr)) | |
| 457 client_->OnReadingUpdated(reading); | |
| 458 return hr; | |
| 459 } | |
| 460 | |
| 461 void PlatformSensorReaderWin::SensorError() { | |
| 462 if (client_) | |
| 463 client_->OnSensorError(); | |
| 464 } | |
| 465 | |
| 466 unsigned long PlatformSensorReaderWin::GetMinimalReportingIntervalMs() const { | |
| 467 return init_params_->min_reporting_interval_ms; | |
| 468 } | |
| 469 | |
| 470 } // namespace device | |
| OLD | NEW |