File: sensor_provider.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (581 lines) | stat: -rw-r--r-- 18,240 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/sensor_info/sensor_provider.h"

#include <algorithm>
#include <cstddef>
#include <iterator>
#include <utility>

#include "ash/sensor_info/sensor_types.h"
#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/time/time.h"
#include "chromeos/components/sensors/ash/sensor_hal_dispatcher.h"
#include "chromeos/components/sensors/mojom/sensor.mojom.h"

namespace ash {

using ::chromeos::sensors::mojom::DeviceType;

namespace {

// Delay of the reconnection to Sensor Hal Dispatcher.
constexpr base::TimeDelta kDelayReconnect = base::Seconds(1);

// Timeout for getting lid_angle samples.
constexpr base::TimeDelta kLidAngleTimeout = base::Seconds(1);

constexpr double kReadFrequencyInHz = 100.0;

}  // namespace

SensorProvider::DeviceState::DeviceState() {
  for (int index = 0; index < static_cast<int>(SensorType::kSensorTypeCount);
       ++index) {
    present_.push_back(false);
  }
}

SensorProvider::DeviceState::~DeviceState() = default;

bool SensorProvider::DeviceState::AllSensorsFound() const {
  for (int index = 0; index < static_cast<int>(SensorType::kSensorTypeCount);
       ++index) {
    if (!present_[index]) {
      return false;
    }
  }
  return true;
}

void SensorProvider::DeviceState::Reset() {
  for (int index = 0; index < static_cast<int>(SensorType::kSensorTypeCount);
       ++index) {
    present_[index] = false;
  }
}

bool SensorProvider::DeviceState::CompareUpdate(SensorUpdate update) const {
  for (int index = 0; index < static_cast<int>(SensorType::kSensorTypeCount);
       ++index) {
    auto source = static_cast<SensorType>(index);
    if (!present_[index]) {
      if (update.has(source)) {
        LOG(ERROR) << "SensorUpdate has extra source: "
                   << static_cast<int>(source);
      }
      continue;
    }
    if (update.has(source)) {
      continue;
    }
    return false;
  }
  return true;
}

void SensorProvider::DeviceState::AddSource(SensorType source) {
  present_[static_cast<int>(source)] = true;
}

void SensorProvider::DeviceState::RemoveSource(SensorType source) {
  present_[static_cast<int>(source)] = false;
}

bool SensorProvider::DeviceState::GetSource(SensorType source) const {
  return present_[static_cast<int>(source)];
}

std::vector<bool> SensorProvider::DeviceState::GetStatesForTesting() const {
  return present_;
}

SensorProvider::SensorData::SensorData() = default;
SensorProvider::SensorData::~SensorData() = default;

SensorProvider::SensorProvider() {
  RegisterSensorClient();
}

SensorProvider::~SensorProvider() = default;

void SensorProvider::SetUpChannel(
    mojo::PendingRemote<chromeos::sensors::mojom::SensorService>
        pending_remote) {
  if (sensor_service_remote_.is_bound()) {
    LOG(ERROR) << "Ignoring the second Remote<SensorService>";
    return;
  }

  sensor_service_remote_.Bind(std::move(pending_remote));
  sensor_service_remote_.set_disconnect_handler(
      base::BindOnce(&SensorProvider::OnSensorServiceDisconnect,
                     weak_ptr_factory_.GetWeakPtr()));
  SetNewDevicesObserver();

  QueryDevices();
}

void SensorProvider::OnSensorServiceDisconnect() {
  LOG(ERROR) << "OnSensorServiceDisconnect";

  ResetSensorService();
}

std::vector<bool> SensorProvider::GetStateForTesting() {
  return current_state_.GetStatesForTesting();  // IN-TEST
}

void SensorProvider::OnNewDeviceAdded(int32_t iio_device_id,
                                      const std::vector<DeviceType>& types) {
  for (const auto& type : types) {
    if (type == DeviceType::ACCEL || type == DeviceType::ANGL ||
        type == DeviceType::ANGLVEL) {
      RegisterSensor(type, iio_device_id);
    }
  }
}

void SensorProvider::RegisterSensorClient() {
  auto* dispatcher = chromeos::sensors::SensorHalDispatcher::GetInstance();
  if (!dispatcher) {
    // In unit tests, SensorHalDispatcher is not initialized.
    return;
  }

  dispatcher->RegisterClient(sensor_hal_client_.BindNewPipeAndPassRemote());

  sensor_hal_client_.set_disconnect_handler(
      base::BindOnce(&SensorProvider::OnSensorHalClientFailure,
                     weak_ptr_factory_.GetWeakPtr()));
}

void SensorProvider::OnSensorHalClientFailure() {
  LOG(ERROR) << "OnSensorHalClientFailure";

  ResetSensorService();
  sensor_hal_client_.reset();
  // It's expected that SensorHalDispatcher will restart after failure,
  // so it's OK to retry forever here.
  base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&SensorProvider::RegisterSensorClient,
                     weak_ptr_factory_.GetWeakPtr()),
      kDelayReconnect);
}

void SensorProvider::SetNewDevicesObserver() {
  DCHECK(sensor_service_remote_.is_bound());
  DCHECK(!new_devices_observer_.is_bound());
  if (current_state_.AllSensorsFound()) {
    // Don't need any further devices.
    return;
  }
  sensor_service_remote_->RegisterNewDevicesObserver(
      new_devices_observer_.BindNewPipeAndPassRemote());
  new_devices_observer_.set_disconnect_handler(
      base::BindOnce(&SensorProvider::OnNewDevicesObserverDisconnect,
                     weak_ptr_factory_.GetWeakPtr()));
}

void SensorProvider::OnNewDevicesObserverDisconnect() {
  LOG(ERROR)
      << "OnNewDevicesObserverDisconnect, resetting SensorService as IIO "
         "Service should be destructed and waiting for the relaunch of it.";
  ResetSensorService();
}

void SensorProvider::ResetSensorService() {
  new_devices_observer_.reset();
  sensor_service_remote_.reset();
  // Discard SensorData to prevent sensors removed while disconnected.
  ResetStates();
}

void SensorProvider::QueryDevices() {
  DCHECK(sensor_service_remote_.is_bound());
  // Get lid_angle sensors
  sensor_service_remote_->GetDeviceIds(
      DeviceType::ANGL, base::BindOnce(&SensorProvider::OnLidAngleIds,
                                       weak_ptr_factory_.GetWeakPtr()));
  // Get accelerometer sensors
  sensor_service_remote_->GetDeviceIds(
      DeviceType::ACCEL, base::BindOnce(&SensorProvider::OnAccelerometerIds,
                                        weak_ptr_factory_.GetWeakPtr()));
  // Get gyroscope sensors
  sensor_service_remote_->GetDeviceIds(
      DeviceType::ANGLVEL, base::BindOnce(&SensorProvider::OnGyroscopeIds,
                                          weak_ptr_factory_.GetWeakPtr()));
}

void SensorProvider::OnLidAngleIds(const std::vector<int32_t>& lid_angle_ids) {
  for (int32_t id : lid_angle_ids) {
    RegisterSensor(DeviceType::ANGL, id);
  }
}

void SensorProvider::OnAccelerometerIds(
    const std::vector<int32_t>& accelerometer_ids) {
  for (int32_t id : accelerometer_ids) {
    RegisterSensor(DeviceType::ACCEL, id);
  }
}

void SensorProvider::OnGyroscopeIds(const std::vector<int32_t>& gyroscope_ids) {
  for (int32_t id : gyroscope_ids) {
    RegisterSensor(DeviceType::ANGLVEL, id);
  }
}

void SensorProvider::RegisterSensor(DeviceType device_type, int32_t id) {
  auto& sensor = sensors_[id][device_type];

  if (sensor.ignored) {
    // Something went wrong in the previous initialization. Ignoring this
    // sensor.
    return;
  }

  if (sensor.remote.is_bound()) {
    // Has already been registered.
    return;
  }
  DCHECK(!sensor.samples_observer.get())
      << "Registering a sensor for device id " << id << " type " << device_type
      << "when there already exists one.";
  if (!sensor_service_remote_.is_bound()) {
    // Something went wrong. Skipping here.
    LOG(ERROR) << "SensorService is not initialized.";
    return;
  }

  sensor_service_remote_->GetDevice(id,
                                    sensor.remote.BindNewPipeAndPassReceiver());
  sensor.remote.set_disconnect_with_reason_handler(
      base::BindOnce(&SensorProvider::OnSensorRemoteDisconnect,
                     weak_ptr_factory_.GetWeakPtr(), device_type, id));
  if (device_type == DeviceType::ANGL) {
    // Samples from ANGL range from 0-180 (which means lid_angle degree), so set
    // scale to 1.
    // Location of lid_angle device is meaningless, so set to kOther.
    sensor.location = SensorLocation::kOther;
    sensor.scale = 1.0;
    if (base::Contains(type_to_sensor_id_, SensorType::kLidAngle)) {
      LOG(WARNING) << "Duplicated location source "
                   << "id_angle"
                   << " of sensor id: " << id << ", and sensor id: "
                   << type_to_sensor_id_[SensorType::kLidAngle];
      IgnoreSensor(device_type, id);
      return;
    }
    current_state_.AddSource(SensorType::kLidAngle);
    type_to_sensor_id_[SensorType::kLidAngle] = id;
  }
  std::vector<std::string> attr_names;
  if (!sensor.location.has_value()) {
    attr_names.push_back(chromeos::sensors::mojom::kLocation);
  }
  if (!sensor.scale.has_value()) {
    attr_names.push_back(chromeos::sensors::mojom::kScale);
  }
  if (attr_names.empty() || device_type == DeviceType::ANGL) {
    // Create the observer directly if the attributes have already been
    // retrieved. Won't create SamplesObserver for lid_angle sensor.
    CreateSensorSamplesObserver(device_type, id);

    return;
  }

  sensor.remote->GetAttributes(
      attr_names,
      base::BindOnce(&SensorProvider::OnAttributes,
                     weak_ptr_factory_.GetWeakPtr(), device_type, id));
}

void SensorProvider::OnSensorRemoteDisconnect(DeviceType device_type,
                                              int32_t id,
                                              uint32_t custom_reason_code,
                                              const std::string& description) {
  auto& sensor = sensors_[id][device_type];
  auto reason =
      static_cast<chromeos::sensors::mojom::SensorDeviceDisconnectReason>(
          custom_reason_code);
  LOG(WARNING) << "OnSensorRemoteDisconnect: " << id << ", reason: " << reason
               << ", description: " << description;

  switch (reason) {
    case chromeos::sensors::mojom::SensorDeviceDisconnectReason::
        IIOSERVICE_CRASHED:
      ResetSensorService();
      break;

    case chromeos::sensors::mojom::SensorDeviceDisconnectReason::DEVICE_REMOVED:
      // This sensor is not in use.
      if (sensor.ignored || !sensor.location.has_value() ||
          !sensor.scale.has_value()) {
        sensors_[id].erase(device_type);
      } else {
        // Reset usages & states, and restart the mojo devices initialization.
        ResetStates();
      }
      break;
  }
}

void SensorProvider::ResetStates() {
  current_state_.Reset();
  sensors_.clear();
  type_to_sensor_id_.clear();
  update_.Reset();
  if (sensor_service_remote_.is_bound()) {
    QueryDevices();
  }
}

void SensorProvider::IgnoreSensor(DeviceType device_type, int32_t id) {
  auto& sensor = sensors_[id][device_type];

  LOG(WARNING) << "Ignoring sensor with id: " << id
               << " device_type:" << device_type;

  sensor.ignored = true;
  sensor.remote.reset();
  sensor.samples_observer.reset();
}

void SensorProvider::EnableSensorReading() {
  sensor_read_on_ = true;
  EnableSensorReadingInternal();
}

void SensorProvider::EnableSensorReadingInternal() {
  // Starts Sensor Reading if all sensors are ready.
  if (sensor_read_on_ && CheckSensorSamplesObserver()) {
    GetLidAngleUpdate();
    for (auto& sensor : sensors_) {
      for (auto& type : sensor.second) {
        if (!type.second.samples_observer.get()) {
          continue;
        }
        type.second.samples_observer->SetEnabled(true);
      }
    }
  }
}

void SensorProvider::StopSensorReading() {
  for (auto& sensor : sensors_) {
    for (auto& type : sensor.second) {
      if (!type.second.samples_observer.get()) {
        continue;
      }
      type.second.samples_observer->SetEnabled(false);
    }
  }
  sensor_read_on_ = false;
}

void SensorProvider::CreateSensorSamplesObserver(DeviceType device_type,
                                                 int32_t id) {
  auto& sensor = sensors_[id][device_type];
  DCHECK(sensor.remote.is_bound());
  DCHECK(!sensor.ignored);
  DCHECK(sensor.scale.has_value() && sensor.location.has_value());
  if (device_type == DeviceType::ACCEL || device_type == DeviceType::ANGLVEL) {
    sensor.samples_observer = std::make_unique<AccelGyroSamplesObserver>(
        id, std::move(sensor.remote), sensor.scale.value(),
        base::BindRepeating(&SensorProvider::OnSampleUpdatedCallback,
                            weak_ptr_factory_.GetWeakPtr(), device_type),
        device_type, kReadFrequencyInHz);
  }
  EnableSensorReadingInternal();
}

bool SensorProvider::CheckSensorSamplesObserver() {
  for (auto& sensor_id : sensors_) {
    for (auto& [type, sensor_data] : sensor_id.second) {
      if (type == DeviceType::ANGL || sensor_data.ignored) {
        continue;
      }
      if (!sensor_data.samples_observer.get()) {
        return false;
      }
    }
  }
  return true;
}

void SensorProvider::OnAttributes(
    DeviceType device_type,
    int32_t id,
    const std::vector<std::optional<std::string>>& values) {
  auto& sensor = sensors_[id][device_type];
  DCHECK(sensor.remote.is_bound());
  auto val_it = values.begin();
  SensorType source;
  if (!sensor.location.has_value()) {
    if (val_it == values.end()) {
      LOG(ERROR) << "values doesn't contain location attribute.";
      IgnoreSensor(device_type, id);
      return;
    }

    if (!val_it->has_value()) {
      LOG(WARNING) << "No location attribute for sensor with id: " << id;
      IgnoreSensor(device_type, id);
      return;
    }

    auto* it = std::ranges::find(kLocationStrings, val_it->value());
    if (it == std::end(kLocationStrings)) {
      LOG(WARNING) << "Unrecognized location: " << val_it->value()
                   << " for device with id: " << id;
      IgnoreSensor(device_type, id);
      return;
    }

    SensorLocation location = static_cast<SensorLocation>(
        std::distance(std::begin(kLocationStrings), it));
    sensor.location = location;
    if (device_type == DeviceType::ACCEL) {
      if (location == SensorLocation::kBase) {
        source = SensorType::kAccelerometerBase;
      } else {
        source = SensorType::kAccelerometerLid;
      }
    } else {
      if (location == SensorLocation::kBase) {
        source = SensorType::kGyroscopeBase;
      } else {
        source = SensorType::kGyroscopeLid;
      }
    }
    if (base::Contains(type_to_sensor_id_, source)) {
      LOG(WARNING) << "Duplicated location source " << static_cast<int>(source)
                   << " of sensor id: " << id
                   << ", and sensor id: " << type_to_sensor_id_[source];
      IgnoreSensor(device_type, id);
      return;
    }
    val_it++;
  }

  if (!sensor.scale.has_value()) {
    if (val_it == values.end()) {
      LOG(ERROR) << "values doesn't contain scale attribute.";
      IgnoreSensor(device_type, id);
      return;
    }

    double scale = 0.0;
    if (!val_it->has_value() ||
        !base::StringToDouble(val_it->value(), &scale)) {
      LOG(ERROR) << "Invalid scale: " << val_it->value_or("")
                 << ", for accel with id: " << id;
      IgnoreSensor(device_type, id);
      return;
    }
    sensor.scale = scale;
  }

  DCHECK(!sensor.ignored);
  current_state_.AddSource(source);
  type_to_sensor_id_[source] = id;
  CreateSensorSamplesObserver(device_type, id);
}

void SensorProvider::GetLidAngleUpdate() {
  if (current_state_.GetSource(SensorType::kLidAngle) &&
      !update_.has(SensorType::kLidAngle)) {
    sensors_[type_to_sensor_id_[SensorType::kLidAngle]][DeviceType::ANGL]
        .remote->GetChannelsAttributes(
            {0}, {"raw"},
            base::BindRepeating(&SensorProvider::OnLidAngleValue,
                                weak_ptr_factory_.GetWeakPtr()));
  }
}

void SensorProvider::OnSampleUpdatedCallback(DeviceType device_type,
                                             int iio_device_id,
                                             std::vector<float> sample) {
  DCHECK_EQ(sample.size(), kNumberOfAxes);
  SensorType key;
  bool find = false;
  for (auto& i : type_to_sensor_id_) {
    if (i.second == iio_device_id) {
      key = i.first;
      if ((key == SensorType::kAccelerometerBase ||
           key == SensorType::kAccelerometerLid) &&
          device_type == DeviceType::ACCEL) {
        find = true;
        break;
      } else if ((key == SensorType::kGyroscopeBase ||
                  key == SensorType::kGyroscopeLid) &&
                 device_type == DeviceType::ANGLVEL) {
        find = true;
        break;
      }
    }
  }
  if (!find) {
    LOG(ERROR) << "Couldn't find the the SensorType that matches DeviceType: "
               << device_type << " and device_id: " << iio_device_id;
    return;
  }

  update_.Set(key, sample[0], sample[1], sample[2]);

  if (!current_state_.CompareUpdate(update_)) {
    // Wait for other sensors to be updated.
    return;
  }

  NotifySensorUpdated(update_);
}

void SensorProvider::OnLidAngleValue(
    const std::vector<std::optional<std::string>>& values) {
  if (values[0].has_value()) {
    int angle;
    if (base::StringToInt(values[0].value(), &angle)) {
      update_.Set(SensorType::kLidAngle, angle);
      if (current_state_.CompareUpdate(update_)) {
        NotifySensorUpdated(update_);
      }
      return;
    }

    LOG(ERROR) << "Failed to convert lid angle sample into integer.";
  } else {
    LOG(ERROR) << "Lid Angle device couldn't get angle return.";
  }

  base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&SensorProvider::GetLidAngleUpdate,
                     weak_ptr_factory_.GetWeakPtr()),
      kLidAngleTimeout);
}

void SensorProvider::NotifySensorUpdated(SensorUpdate update) {
  for (auto& observer : observers_) {
    observer.OnSensorUpdated(update);
  }
  update_.Reset();

  GetLidAngleUpdate();
}

void SensorProvider::AddObserver(SensorObserver* observer) {
  observers_.AddObserver(observer);
}

void SensorProvider::RemoveObserver(SensorObserver* observer) {
  observers_.RemoveObserver(observer);
}
}  // namespace ash