Upstream changes for NetworkQualityProvider
[chromium-blink-merge.git] / chromeos / accelerometer / accelerometer_reader.cc
blob04122ca09b90f18974d914382fba2a87a5721ce9
1 // Copyright 2014 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 "chromeos/accelerometer/accelerometer_reader.h"
7 #include <string>
9 #include "base/bind.h"
10 #include "base/files/file_util.h"
11 #include "base/location.h"
12 #include "base/memory/singleton.h"
13 #include "base/single_thread_task_runner.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/task_runner.h"
18 #include "base/task_runner_util.h"
19 #include "base/thread_task_runner_handle.h"
20 #include "base/threading/platform_thread.h"
21 #include "base/threading/sequenced_worker_pool.h"
23 namespace chromeos {
25 namespace {
27 // Paths to access necessary data from the accelerometer device.
28 const base::FilePath::CharType kAccelerometerTriggerPath[] =
29 FILE_PATH_LITERAL("/sys/bus/iio/devices/trigger0/trigger_now");
30 const base::FilePath::CharType kAccelerometerDevicePath[] =
31 FILE_PATH_LITERAL("/dev/cros-ec-accel");
32 const base::FilePath::CharType kAccelerometerIioBasePath[] =
33 FILE_PATH_LITERAL("/sys/bus/iio/devices/");
35 // File within the device in kAccelerometerIioBasePath containing the scale of
36 // the accelerometers.
37 const base::FilePath::CharType kScaleFileName[] = "in_accel_scale";
39 // This is the per source scale file in use on kernels older than 3.18. We
40 // should remove this when all devices having accelerometers are on kernel 3.18
41 // or later or have been patched to use new format: http://crbug.com/510831
42 const base::FilePath::CharType kSourceScaleNameFormatString[] =
43 "in_accel_%s_scale";
45 // The filename giving the path to read the scan index of each accelerometer
46 // axis.
47 const char kAccelerometerScanIndexPath[] =
48 "scan_elements/in_accel_%s_%s_index";
50 // The names of the accelerometers. Matches up with the enum AccelerometerSource
51 // in chromeos/accelerometer/accelerometer_types.h.
52 const char kAccelerometerNames[ACCELEROMETER_SOURCE_COUNT][5] = {"lid", "base"};
54 // The axes on each accelerometer.
55 const char kAccelerometerAxes[][2] = {"y", "x", "z"};
57 // The length required to read uint values from configuration files.
58 const size_t kMaxAsciiUintLength = 21;
60 // The size of individual values.
61 const size_t kDataSize = 2;
63 // The mean acceleration due to gravity on Earth in m/s^2.
64 const float kMeanGravity = 9.80665f;
66 // The number of accelerometers.
67 const int kNumberOfAccelerometers = 2;
69 // The number of axes for which there are acceleration readings.
70 const int kNumberOfAxes = 3;
72 // The size of data in one reading of the accelerometers.
73 const int kSizeOfReading = kDataSize * kNumberOfAccelerometers * kNumberOfAxes;
75 // Reads |path| to the unsigned int pointed to by |value|. Returns true on
76 // success or false on failure.
77 bool ReadFileToInt(const base::FilePath& path, int* value) {
78 std::string s;
79 DCHECK(value);
80 if (!base::ReadFileToString(path, &s, kMaxAsciiUintLength)) {
81 return false;
83 base::TrimWhitespaceASCII(s, base::TRIM_ALL, &s);
84 if (!base::StringToInt(s, value)) {
85 LOG(ERROR) << "Failed to parse \"" << s << "\" from " << path.value();
86 return false;
88 return true;
91 } // namespace
93 const int AccelerometerReader::kDelayBetweenReadsMs = 100;
95 // Work that runs on a base::TaskRunner. It determines the accelerometer
96 // configuartion, and reads the data. Upon a successful read it will notify
97 // all observers.
98 class AccelerometerFileReader
99 : public base::RefCountedThreadSafe<AccelerometerFileReader> {
100 public:
101 AccelerometerFileReader();
103 // Detects the accelerometer configuration, if an accelerometer is available
104 // triggers reads.
105 void Initialize(
106 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner);
108 // Attempts to read the accelerometer data. Upon a success, converts the raw
109 // reading to an AccelerometerUpdate and notifies observers. Triggers another
110 // read at the current sampling rate.
111 void Read();
113 // Add/Remove observers.
114 void AddObserver(AccelerometerReader::Observer* observer);
115 void RemoveObserver(AccelerometerReader::Observer* observer);
117 private:
118 friend class base::RefCountedThreadSafe<AccelerometerFileReader>;
120 // Configuration structure for accelerometer device.
121 struct ConfigurationData {
122 ConfigurationData();
123 ~ConfigurationData();
125 // Number of accelerometers on device.
126 size_t count;
128 // Length of accelerometer updates.
129 size_t length;
131 // Which accelerometers are present on device.
132 bool has[ACCELEROMETER_SOURCE_COUNT];
134 // Scale of accelerometers (i.e. raw value * scale = m/s^2).
135 float scale[ACCELEROMETER_SOURCE_COUNT][3];
137 // Index of each accelerometer axis in data stream.
138 int index[ACCELEROMETER_SOURCE_COUNT][3];
141 ~AccelerometerFileReader() {}
143 // Attempts to read the accelerometer data. Upon a success, converts the raw
144 // reading to an AccelerometerUpdate and notifies observers.
145 void ReadFileAndNotify();
147 // True if Initialize completed successfully, and there is an accelerometer
148 // file to read.
149 bool initialization_successful_;
151 // The accelerometer configuration.
152 ConfigurationData configuration_;
154 // The observers to notify of accelerometer updates.
155 scoped_refptr<base::ObserverListThreadSafe<AccelerometerReader::Observer>>
156 observers_;
158 // The task runner to use for blocking tasks.
159 scoped_refptr<base::SequencedTaskRunner> task_runner_;
161 // The last seen accelerometer data.
162 scoped_refptr<AccelerometerUpdate> update_;
164 DISALLOW_COPY_AND_ASSIGN(AccelerometerFileReader);
167 AccelerometerFileReader::AccelerometerFileReader()
168 : initialization_successful_(false),
169 observers_(
170 new base::ObserverListThreadSafe<AccelerometerReader::Observer>()) {
173 void AccelerometerFileReader::Initialize(
174 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner) {
175 DCHECK(
176 base::SequencedWorkerPool::GetSequenceTokenForCurrentThread().IsValid());
177 task_runner_ = sequenced_task_runner;
179 // Check for accelerometer symlink which will be created by the udev rules
180 // file on detecting the device.
181 base::FilePath device;
182 if (!base::ReadSymbolicLink(base::FilePath(kAccelerometerDevicePath),
183 &device)) {
184 return;
187 if (!base::PathExists(base::FilePath(kAccelerometerTriggerPath))) {
188 LOG(ERROR) << "Accelerometer trigger does not exist at"
189 << kAccelerometerTriggerPath;
190 return;
193 base::FilePath iio_path(base::FilePath(kAccelerometerIioBasePath).Append(
194 device));
196 // Read the scale for all axes.
197 int scale_divisor = 0;
198 bool per_source_scale =
199 !ReadFileToInt(iio_path.Append(kScaleFileName), &scale_divisor);
200 if (!per_source_scale && scale_divisor == 0) {
201 LOG(ERROR) << "Accelerometer " << kScaleFileName
202 << "has scale of 0 and will not be used.";
203 return;
206 // Read configuration of each accelerometer axis from each accelerometer from
207 // /sys/bus/iio/devices/iio:deviceX/.
208 for (size_t i = 0; i < arraysize(kAccelerometerNames); ++i) {
209 if (per_source_scale) {
210 configuration_.has[i] = false;
211 // Read scale of accelerometer.
212 std::string accelerometer_scale_path = base::StringPrintf(
213 kSourceScaleNameFormatString, kAccelerometerNames[i]);
214 if (!ReadFileToInt(iio_path.Append(accelerometer_scale_path.c_str()),
215 &scale_divisor)) {
216 continue;
218 if (scale_divisor == 0) {
219 LOG(ERROR) << "Accelerometer " << accelerometer_scale_path
220 << "has scale of 0 and will not be used.";
221 continue;
225 configuration_.has[i] = true;
226 for (size_t j = 0; j < arraysize(kAccelerometerAxes); ++j) {
227 configuration_.scale[i][j] = kMeanGravity / scale_divisor;
228 std::string accelerometer_index_path = base::StringPrintf(
229 kAccelerometerScanIndexPath, kAccelerometerAxes[j],
230 kAccelerometerNames[i]);
231 if (!ReadFileToInt(iio_path.Append(accelerometer_index_path.c_str()),
232 &(configuration_.index[i][j]))) {
233 configuration_.has[i] = false;
234 break;
237 if (configuration_.has[i])
238 configuration_.count++;
241 // Adjust the directions of accelerometers to match the AccelerometerUpdate
242 // type specified in chromeos/accelerometer/accelerometer_types.h.
243 configuration_.scale[ACCELEROMETER_SOURCE_SCREEN][0] *= -1.0f;
244 for (int i = 0; i < 3; ++i) {
245 configuration_.scale[ACCELEROMETER_SOURCE_ATTACHED_KEYBOARD][i] *= -1.0f;
248 // Verify indices are within bounds.
249 for (int i = 0; i < ACCELEROMETER_SOURCE_COUNT; ++i) {
250 if (!configuration_.has[i])
251 continue;
252 for (int j = 0; j < 3; ++j) {
253 if (configuration_.index[i][j] < 0 ||
254 configuration_.index[i][j] >=
255 3 * static_cast<int>(configuration_.count)) {
256 LOG(ERROR) << "Field index for " << kAccelerometerNames[i] << " "
257 << kAccelerometerAxes[j] << " axis out of bounds.";
258 return;
262 configuration_.length = kDataSize * 3 * configuration_.count;
263 initialization_successful_ = true;
264 Read();
267 void AccelerometerFileReader::Read() {
268 DCHECK(
269 base::SequencedWorkerPool::GetSequenceTokenForCurrentThread().IsValid());
270 ReadFileAndNotify();
271 task_runner_->PostNonNestableDelayedTask(
272 FROM_HERE, base::Bind(&AccelerometerFileReader::Read, this),
273 base::TimeDelta::FromMilliseconds(
274 AccelerometerReader::kDelayBetweenReadsMs));
277 void AccelerometerFileReader::AddObserver(
278 AccelerometerReader::Observer* observer) {
279 observers_->AddObserver(observer);
280 if (initialization_successful_) {
281 task_runner_->PostNonNestableTask(
282 FROM_HERE,
283 base::Bind(&AccelerometerFileReader::ReadFileAndNotify, this));
287 void AccelerometerFileReader::RemoveObserver(
288 AccelerometerReader::Observer* observer) {
289 observers_->RemoveObserver(observer);
292 void AccelerometerFileReader::ReadFileAndNotify() {
293 DCHECK(initialization_successful_);
294 char reading[kSizeOfReading];
296 // Initiate the trigger to read accelerometers simultaneously
297 int bytes_written = base::WriteFile(
298 base::FilePath(kAccelerometerTriggerPath), "1\n", 2);
299 if (bytes_written < 2) {
300 PLOG(ERROR) << "Accelerometer trigger failure: " << bytes_written;
301 return;
304 // Read resulting sample from /dev/cros-ec-accel.
305 int bytes_read = base::ReadFile(base::FilePath(kAccelerometerDevicePath),
306 reading, configuration_.length);
307 if (bytes_read < static_cast<int>(configuration_.length)) {
308 LOG(ERROR) << "Read " << bytes_read << " byte(s), expected "
309 << configuration_.length << " bytes from accelerometer";
310 return;
313 update_ = new AccelerometerUpdate();
315 for (int i = 0; i < ACCELEROMETER_SOURCE_COUNT; ++i) {
316 if (!configuration_.has[i])
317 continue;
319 int16* values = reinterpret_cast<int16*>(reading);
320 update_->Set(
321 static_cast<AccelerometerSource>(i),
322 values[configuration_.index[i][0]] * configuration_.scale[i][0],
323 values[configuration_.index[i][1]] * configuration_.scale[i][1],
324 values[configuration_.index[i][2]] * configuration_.scale[i][2]);
327 observers_->Notify(FROM_HERE,
328 &AccelerometerReader::Observer::OnAccelerometerUpdated,
329 update_);
332 AccelerometerFileReader::ConfigurationData::ConfigurationData() : count(0) {
333 for (int i = 0; i < ACCELEROMETER_SOURCE_COUNT; ++i) {
334 has[i] = false;
335 for (int j = 0; j < 3; ++j) {
336 scale[i][j] = 0;
337 index[i][j] = -1;
342 AccelerometerFileReader::ConfigurationData::~ConfigurationData() {
345 // static
346 AccelerometerReader* AccelerometerReader::GetInstance() {
347 return Singleton<AccelerometerReader>::get();
350 void AccelerometerReader::Initialize(
351 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner) {
352 DCHECK(sequenced_task_runner.get());
353 // Asynchronously detect and initialize the accelerometer to avoid delaying
354 // startup.
355 sequenced_task_runner->PostNonNestableTask(
356 FROM_HERE,
357 base::Bind(&AccelerometerFileReader::Initialize,
358 accelerometer_file_reader_.get(), sequenced_task_runner));
361 void AccelerometerReader::AddObserver(Observer* observer) {
362 accelerometer_file_reader_->AddObserver(observer);
365 void AccelerometerReader::RemoveObserver(Observer* observer) {
366 accelerometer_file_reader_->RemoveObserver(observer);
369 AccelerometerReader::AccelerometerReader()
370 : accelerometer_file_reader_(new AccelerometerFileReader()) {
373 AccelerometerReader::~AccelerometerReader() {
376 } // namespace chromeos