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

ash / accelerometer / accel_gyro_samples_observer.cc [blame]

// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "ash/accelerometer/accel_gyro_samples_observer.h"

#include <utility>

#include "ash/accelerometer/accelerometer_constants.h"
#include "base/functional/bind.h"

namespace ash {

namespace {

constexpr int kTimeoutToleranceInMilliseconds = 500;

}  // namespace

AccelGyroSamplesObserver::AccelGyroSamplesObserver(
    int iio_device_id,
    mojo::Remote<chromeos::sensors::mojom::SensorDevice> sensor_device_remote,
    float scale,
    OnSampleUpdatedCallback on_sample_updated_callback,
    chromeos::sensors::mojom::DeviceType device_type,
    float frequency)
    : iio_device_id_(iio_device_id),
      sensor_device_remote_(std::move(sensor_device_remote)),
      scale_(scale),
      frequency_(frequency),
      device_type_(device_type),
      on_sample_updated_callback_(std::move(on_sample_updated_callback)) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(sensor_device_remote_.is_bound());
  DCHECK(device_type_ == chromeos::sensors::mojom::DeviceType::ACCEL||
         device_type_ == chromeos::sensors::mojom::DeviceType::ANGLVEL);
  sensor_device_remote_->GetAllChannelIds(
      base::BindOnce(&AccelGyroSamplesObserver::GetAllChannelIdsCallback,
                     weak_factory_.GetWeakPtr()));
}

AccelGyroSamplesObserver::~AccelGyroSamplesObserver() = default;

void AccelGyroSamplesObserver::SetEnabled(bool enabled) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (enabled_ == enabled)
    return;

  enabled_ = enabled;

  UpdateSensorDeviceFrequency();
}

void AccelGyroSamplesObserver::OnSampleUpdated(
    const base::flat_map<int32_t, int64_t>& sample) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (sample.size() != kNumberOfAxes) {
    LOG(ERROR) << "Invalid sample with size: " << sample.size();
    OnErrorOccurred(chromeos::sensors::mojom::ObserverErrorType::READ_FAILED);
    return;
  }

  auto it = sample.begin();
  std::vector<float> output_sample;
  for (size_t axes = 0; axes < kNumberOfAxes; ++axes) {
    if (axes != 0)
      ++it;

    if (it == sample.end() || it->first != channel_indices_[axes])
      it = sample.find(channel_indices_[axes]);

    if (it == sample.end()) {
      LOG(ERROR) << "Missing channel: " << kAccelerometerChannels[axes]
                 << " in sample";
      OnErrorOccurred(chromeos::sensors::mojom::ObserverErrorType::READ_FAILED);
      return;
    }

    output_sample.push_back(it->second * scale_);
  }

  on_sample_updated_callback_.Run(iio_device_id_, output_sample);
}

void AccelGyroSamplesObserver::OnErrorOccurred(
    chromeos::sensors::mojom::ObserverErrorType type) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  switch (type) {
    case chromeos::sensors::mojom::ObserverErrorType::ALREADY_STARTED:
      LOG(ERROR) << "Device " << iio_device_id_
                 << ": Another observer has already started to read samples";
      Reset();
      break;

    case chromeos::sensors::mojom::ObserverErrorType::FREQUENCY_INVALID:
      if (!enabled_)  // It's normal if this observer is not enabled
        break;

      LOG(ERROR) << "Device " << iio_device_id_
                 << ": Observer started with an invalid frequency";
      UpdateSensorDeviceFrequency();

      break;

    case chromeos::sensors::mojom::ObserverErrorType::NO_ENABLED_CHANNELS:
      LOG(ERROR) << "Device " << iio_device_id_
                 << ": Observer started with no channels enabled";
      if (sensor_device_remote_.is_bound()) {
        sensor_device_remote_->SetChannelsEnabled(
            std::vector<int32_t>(channel_indices_,
                                 channel_indices_ + kNumberOfAxes),
            /*enable=*/true,
            base::BindOnce(
                &AccelGyroSamplesObserver::SetChannelsEnabledCallback,
                weak_factory_.GetWeakPtr()));
      }

      break;

    case chromeos::sensors::mojom::ObserverErrorType::SET_FREQUENCY_IO_FAILED:
      LOG(ERROR) << "Device " << iio_device_id_
                 << ": Failed to set frequency to the physical device";
      break;

    case chromeos::sensors::mojom::ObserverErrorType::GET_FD_FAILED:
      LOG(ERROR) << "Device " << iio_device_id_
                 << ": Failed to get the device's fd to poll on";
      break;

    case chromeos::sensors::mojom::ObserverErrorType::READ_FAILED:
      LOG(ERROR) << "Device " << iio_device_id_ << ": Failed to read a sample";
      break;

    case chromeos::sensors::mojom::ObserverErrorType::READ_TIMEOUT:
      LOG(ERROR) << "Device " << iio_device_id_ << ": A read timed out";
      break;

    default:
      LOG(ERROR) << "Device " << iio_device_id_ << ": error "
                 << static_cast<int>(type);
      break;
  }
}

void AccelGyroSamplesObserver::Reset() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  LOG(ERROR) << "Resetting SamplesObserver: " << iio_device_id_;
  receiver_.reset();
  sensor_device_remote_.reset();
}

void AccelGyroSamplesObserver::GetAllChannelIdsCallback(
    const std::vector<std::string>& iio_channel_ids) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(sensor_device_remote_.is_bound());

  iio_channel_ids_ = std::move(iio_channel_ids);
  std::vector<std::string> channels;
  if (device_type_ == chromeos::sensors::mojom::DeviceType::ACCEL){
    for (uint i = 0; i < kNumberOfAxes; i++){
      channels.push_back(std::string(kAccelerometerChannels[i]));
    }
  } else{
    for (uint i = 0; i < kNumberOfAxes; i++){
      channels.push_back(std::string(kGyroscopeChannels[i]));
    }
  }
  for (size_t axis = 0; axis < kNumberOfAxes; ++axis) {
    bool found = false;
    for (size_t channel_index = 0; channel_index < iio_channel_ids_.size();
         ++channel_index) {
      if (iio_channel_ids_[channel_index].compare(channels[axis]) == 0) {
        found = true;
        channel_indices_[axis] = channel_index;
        break;
      }
    }

    if (!found) {
      LOG(ERROR) << "Missing channel: " << kAccelerometerChannels[axis];
      Reset();
      return;
    }
  }

  sensor_device_remote_->SetChannelsEnabled(
      std::vector<int32_t>(channel_indices_, channel_indices_ + kNumberOfAxes),
      /*enable=*/true,
      base::BindOnce(&AccelGyroSamplesObserver::SetChannelsEnabledCallback,
                     weak_factory_.GetWeakPtr()));

  StartReading();
}

void AccelGyroSamplesObserver::StartReading() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(sensor_device_remote_.is_bound());

  sensor_device_remote_->SetTimeout(kTimeoutToleranceInMilliseconds);

  sensor_device_remote_->StartReadingSamples(GetPendingRemote());
}

void AccelGyroSamplesObserver::UpdateSensorDeviceFrequency() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (!sensor_device_remote_.is_bound())
    return;

  sensor_device_remote_->SetFrequency(
      enabled_ ? frequency_ : 0.0,
      base::BindOnce(&AccelGyroSamplesObserver::SetFrequencyCallback,
                     weak_factory_.GetWeakPtr(), enabled_));
}

mojo::PendingRemote<chromeos::sensors::mojom::SensorDeviceSamplesObserver>
AccelGyroSamplesObserver::GetPendingRemote() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  auto pending_remote = receiver_.BindNewPipeAndPassRemote();

  receiver_.set_disconnect_handler(
      base::BindOnce(&AccelGyroSamplesObserver::OnObserverDisconnect,
                     weak_factory_.GetWeakPtr()));
  return pending_remote;
}

void AccelGyroSamplesObserver::OnObserverDisconnect() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  LOG(ERROR) << "OnObserverDisconnect error, assuming IIO Service crashes and "
                "waiting for its relaunch.";
  // Don't reset |sensor_device_remote_| so that AccelerometerProviderMojo can
  // get the disconnection.
  receiver_.reset();
}

void AccelGyroSamplesObserver::SetFrequencyCallback(bool enabled,
                                                    double result_frequency) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (enabled != enabled_) {
    // As the current configuration (required frequency) is different now,
    // ignore the result of this deprecated |SensorDevice::SetFrequency|.
    return;
  }

  if ((result_frequency > 0.0 && enabled_) ||
      (result_frequency == 0.0 && !enabled_)) {
    return;
  }

  LOG(ERROR) << "Failed to set frequency: " << result_frequency
             << " with the samples observer enabled: "
             << (enabled_ ? "true" : "false");
  Reset();
}

void AccelGyroSamplesObserver::SetChannelsEnabledCallback(
    const std::vector<int32_t>& failed_indices) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  for (int32_t index : failed_indices)
    LOG(ERROR) << "Failed to enable " << iio_channel_ids_[index];

  if (!failed_indices.empty())
    Reset();
}

}  // namespace ash