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"
10 #include "base/bind.h"
11 #include "base/files/file_enumerator.h"
12 #include "base/files/file_util.h"
13 #include "base/location.h"
14 #include "base/memory/singleton.h"
15 #include "base/single_thread_task_runner.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/task_runner.h"
20 #include "base/task_runner_util.h"
21 #include "base/thread_task_runner_handle.h"
22 #include "base/threading/platform_thread.h"
23 #include "base/threading/sequenced_worker_pool.h"
29 // Paths to access necessary data from the accelerometer device.
30 const base::FilePath::CharType kAccelerometerTriggerPath
[] =
31 FILE_PATH_LITERAL("/sys/bus/iio/devices/trigger0/trigger_now");
32 const base::FilePath::CharType kAccelerometerDevicePath
[] =
33 FILE_PATH_LITERAL("/dev/cros-ec-accel");
34 const base::FilePath::CharType kAccelerometerIioBasePath
[] =
35 FILE_PATH_LITERAL("/sys/bus/iio/devices/");
37 // This is the per source scale file in use on kernels older than 3.18. We
38 // should remove this when all devices having accelerometers are on kernel 3.18
39 // or later or have been patched to use new format: http://crbug.com/510831
40 const base::FilePath::CharType kLegacyScaleNameFormatString
[] =
43 // File within kAccelerometerDevicePath/device* which denotes a single scale to
44 // be used across all axes.
45 const base::FilePath::CharType kAccelerometerScaleFileName
[] = "scale";
47 // File within kAccelerometerDevicePath/device* which denotes the
48 // AccelerometerSource for the accelerometer.
49 const base::FilePath::CharType kAccelerometerLocationFileName
[] = "location";
51 // The filename giving the path to read the scan index of each accelerometer
53 const char kLegacyAccelerometerScanIndexPathFormatString
[] =
54 "scan_elements/in_accel_%s_%s_index";
56 // The filename giving the path to read the scan index of each accelerometer
57 // when they are separate device paths.
58 const char kAccelerometerScanIndexPathFormatString
[] =
59 "scan_elements/in_accel_%s_index";
61 // The names of the accelerometers. Matches up with the enum AccelerometerSource
62 // in chromeos/accelerometer/accelerometer_types.h.
63 const char kAccelerometerNames
[ACCELEROMETER_SOURCE_COUNT
][5] = {"lid", "base"};
65 // The axes on each accelerometer. The order was changed on kernel 3.18+.
66 const char kAccelerometerAxes
[][2] = {"x", "y", "z"};
67 const char kLegacyAccelerometerAxes
[][2] = {"y", "x", "z"};
69 // The length required to read uint values from configuration files.
70 const size_t kMaxAsciiUintLength
= 21;
72 // The size of individual values.
73 const size_t kDataSize
= 2;
75 // The mean acceleration due to gravity on Earth in m/s^2.
76 const float kMeanGravity
= 9.80665f
;
78 // The number of axes for which there are acceleration readings.
79 const int kNumberOfAxes
= 3;
81 // The size of data in one reading of the accelerometers.
82 const int kSizeOfReading
= kDataSize
* kNumberOfAxes
;
84 // Reads |path| to the unsigned int pointed to by |value|. Returns true on
85 // success or false on failure.
86 bool ReadFileToInt(const base::FilePath
& path
, int* value
) {
89 if (!base::ReadFileToString(path
, &s
, kMaxAsciiUintLength
)) {
92 base::TrimWhitespaceASCII(s
, base::TRIM_ALL
, &s
);
93 if (!base::StringToInt(s
, value
)) {
94 LOG(ERROR
) << "Failed to parse int \"" << s
<< "\" from " << path
.value();
100 // Reads |path| to the double pointed to by |value|. Returns true on success or
102 bool ReadFileToDouble(const base::FilePath
& path
, double* value
) {
105 if (!base::ReadFileToString(path
, &s
)) {
108 base::TrimWhitespaceASCII(s
, base::TRIM_ALL
, &s
);
109 if (!base::StringToDouble(s
, value
)) {
110 LOG(ERROR
) << "Failed to parse double \"" << s
<< "\" from "
119 const int AccelerometerReader::kDelayBetweenReadsMs
= 100;
121 // Work that runs on a base::TaskRunner. It determines the accelerometer
122 // configuartion, and reads the data. Upon a successful read it will notify
124 class AccelerometerFileReader
125 : public base::RefCountedThreadSafe
<AccelerometerFileReader
> {
127 AccelerometerFileReader();
129 // Detects the accelerometer configuration, if an accelerometer is available
132 scoped_refptr
<base::SequencedTaskRunner
> sequenced_task_runner
);
134 // Attempts to read the accelerometer data. Upon a success, converts the raw
135 // reading to an AccelerometerUpdate and notifies observers. Triggers another
136 // read at the current sampling rate.
139 // Add/Remove observers.
140 void AddObserver(AccelerometerReader::Observer
* observer
);
141 void RemoveObserver(AccelerometerReader::Observer
* observer
);
144 friend class base::RefCountedThreadSafe
<AccelerometerFileReader
>;
146 // Represents necessary information in order to read an accelerometer device.
148 // The full path to the accelerometer device to read.
151 // The accelerometer sources which can be read from |path|.
152 std::vector
<AccelerometerSource
> sources
;
155 // Configuration structure for accelerometer device.
156 struct ConfigurationData
{
158 ~ConfigurationData();
160 // Number of accelerometers on device.
163 // Which accelerometers are present on device.
164 bool has
[ACCELEROMETER_SOURCE_COUNT
];
166 // Scale of accelerometers (i.e. raw value * scale = m/s^2).
167 float scale
[ACCELEROMETER_SOURCE_COUNT
][3];
169 // Index of each accelerometer axis in data stream.
170 int index
[ACCELEROMETER_SOURCE_COUNT
][3];
172 // The information for each accelerometer device to be read. In kernel 3.18
173 // there is one per ACCELEROMETER_SOURCE_COUNT, on 3.14 there is only one.
174 std::vector
<ReadingData
> reading_data
;
177 ~AccelerometerFileReader() {}
179 // When accelerometers are presented as separate iio_devices this will perform
180 // the initialize for one of the devices, at the given |iio_path| and the
181 // symbolic link |name|. |location| is defined by AccelerometerSoure.
182 bool InitializeAccelerometer(const base::FilePath
& iio_path
,
183 const base::FilePath
& name
,
184 const std::string
& location
);
186 // TODO(jonross): Separate the initialization into separate files. Add a gyp
187 // rule to have them built for the appropriate kernels. (crbug.com/525658)
188 // When accelerometers are presented as a single iio_device this will perform
189 // the initialization for both of them.
190 bool InitializeLegacyAccelerometers(const base::FilePath
& iio_path
,
191 const base::FilePath
& name
);
193 // Attempts to read the accelerometer data. Upon a success, converts the raw
194 // reading to an AccelerometerUpdate and notifies observers.
195 void ReadFileAndNotify();
197 // True if Initialize completed successfully, and there is an accelerometer
199 bool initialization_successful_
;
201 // The accelerometer configuration.
202 ConfigurationData configuration_
;
204 // The observers to notify of accelerometer updates.
205 scoped_refptr
<base::ObserverListThreadSafe
<AccelerometerReader::Observer
>>
208 // The task runner to use for blocking tasks.
209 scoped_refptr
<base::SequencedTaskRunner
> task_runner_
;
211 // The last seen accelerometer data.
212 scoped_refptr
<AccelerometerUpdate
> update_
;
214 DISALLOW_COPY_AND_ASSIGN(AccelerometerFileReader
);
217 AccelerometerFileReader::AccelerometerFileReader()
218 : initialization_successful_(false),
220 new base::ObserverListThreadSafe
<AccelerometerReader::Observer
>()) {
223 void AccelerometerFileReader::Initialize(
224 scoped_refptr
<base::SequencedTaskRunner
> sequenced_task_runner
) {
226 base::SequencedWorkerPool::GetSequenceTokenForCurrentThread().IsValid());
227 task_runner_
= sequenced_task_runner
;
229 // Check for accelerometer symlink which will be created by the udev rules
230 // file on detecting the device.
231 base::FilePath device
;
233 if (base::IsDirectoryEmpty(base::FilePath(kAccelerometerDevicePath
))) {
234 LOG(ERROR
) << "Accelerometer device directory is empty at "
235 << kAccelerometerDevicePath
;
239 if (!base::PathExists(base::FilePath(kAccelerometerTriggerPath
))) {
240 LOG(ERROR
) << "Accelerometer trigger does not exist at"
241 << kAccelerometerTriggerPath
;
245 base::FileEnumerator
symlink_dir(base::FilePath(kAccelerometerDevicePath
),
246 false, base::FileEnumerator::FILES
);
247 bool legacy_cross_accel
= false;
248 for (base::FilePath name
= symlink_dir
.Next(); !name
.empty();
249 name
= symlink_dir
.Next()) {
250 base::FilePath iio_device
;
251 if (!base::ReadSymbolicLink(name
, &iio_device
)) {
252 LOG(ERROR
) << "Failed to read symbolic link " << kAccelerometerDevicePath
253 << "/" << name
.MaybeAsASCII() << "\n";
257 base::FilePath
iio_path(base::FilePath(kAccelerometerIioBasePath
)
258 .Append(iio_device
.BaseName()));
259 std::string location
;
260 legacy_cross_accel
= !base::ReadFileToString(
261 base::FilePath(iio_path
).Append(kAccelerometerLocationFileName
),
263 if (legacy_cross_accel
) {
264 if (!InitializeLegacyAccelerometers(iio_path
, name
))
267 base::TrimWhitespaceASCII(location
, base::TRIM_ALL
, &location
);
268 if (!InitializeAccelerometer(iio_path
, name
, location
))
273 // Verify indices are within bounds.
274 for (int i
= 0; i
< ACCELEROMETER_SOURCE_COUNT
; ++i
) {
275 if (!configuration_
.has
[i
])
277 for (int j
= 0; j
< 3; ++j
) {
278 if (configuration_
.index
[i
][j
] < 0 ||
279 configuration_
.index
[i
][j
] >=
280 3 * static_cast<int>(configuration_
.count
)) {
281 const char* axis
= legacy_cross_accel
? kLegacyAccelerometerAxes
[j
]
282 : kAccelerometerAxes
[j
];
283 LOG(ERROR
) << "Field index for " << kAccelerometerNames
[i
] << " "
284 << axis
<< " axis out of bounds.";
290 initialization_successful_
= true;
294 void AccelerometerFileReader::Read() {
296 base::SequencedWorkerPool::GetSequenceTokenForCurrentThread().IsValid());
298 task_runner_
->PostNonNestableDelayedTask(
299 FROM_HERE
, base::Bind(&AccelerometerFileReader::Read
, this),
300 base::TimeDelta::FromMilliseconds(
301 AccelerometerReader::kDelayBetweenReadsMs
));
304 void AccelerometerFileReader::AddObserver(
305 AccelerometerReader::Observer
* observer
) {
306 observers_
->AddObserver(observer
);
307 if (initialization_successful_
) {
308 task_runner_
->PostNonNestableTask(
310 base::Bind(&AccelerometerFileReader::ReadFileAndNotify
, this));
314 void AccelerometerFileReader::RemoveObserver(
315 AccelerometerReader::Observer
* observer
) {
316 observers_
->RemoveObserver(observer
);
319 bool AccelerometerFileReader::InitializeAccelerometer(
320 const base::FilePath
& iio_path
,
321 const base::FilePath
& name
,
322 const std::string
& location
) {
323 size_t config_index
= 0;
324 for (; config_index
< arraysize(kAccelerometerNames
); ++config_index
) {
325 if (location
== kAccelerometerNames
[config_index
])
329 if (config_index
>= arraysize(kAccelerometerNames
)) {
330 LOG(ERROR
) << "Unrecognized location: " << location
<< " for device "
331 << name
.MaybeAsASCII() << "\n";
336 if (!ReadFileToDouble(iio_path
.Append(kAccelerometerScaleFileName
), &scale
))
339 const int kNumberAxes
= arraysize(kAccelerometerAxes
);
340 for (size_t i
= 0; i
< kNumberAxes
; ++i
) {
341 std::string accelerometer_index_path
= base::StringPrintf(
342 kAccelerometerScanIndexPathFormatString
, kAccelerometerAxes
[i
]);
343 if (!ReadFileToInt(iio_path
.Append(accelerometer_index_path
.c_str()),
344 &(configuration_
.index
[config_index
][i
]))) {
345 LOG(ERROR
) << "Index file " << accelerometer_index_path
346 << " could not be parsed\n";
349 configuration_
.scale
[config_index
][i
] = scale
;
351 configuration_
.has
[config_index
] = true;
352 configuration_
.count
++;
354 ReadingData reading_data
;
356 base::FilePath(kAccelerometerDevicePath
).Append(name
.BaseName());
357 reading_data
.sources
.push_back(
358 static_cast<AccelerometerSource
>(config_index
));
360 configuration_
.reading_data
.push_back(reading_data
);
365 bool AccelerometerFileReader::InitializeLegacyAccelerometers(
366 const base::FilePath
& iio_path
,
367 const base::FilePath
& name
) {
368 ReadingData reading_data
;
370 base::FilePath(kAccelerometerDevicePath
).Append(name
.BaseName());
371 // Read configuration of each accelerometer axis from each accelerometer from
372 // /sys/bus/iio/devices/iio:deviceX/.
373 for (size_t i
= 0; i
< arraysize(kAccelerometerNames
); ++i
) {
374 configuration_
.has
[i
] = false;
375 // Read scale of accelerometer.
376 std::string accelerometer_scale_path
= base::StringPrintf(
377 kLegacyScaleNameFormatString
, kAccelerometerNames
[i
]);
378 // Read the scale for all axes.
379 int scale_divisor
= 0;
380 if (!ReadFileToInt(iio_path
.Append(accelerometer_scale_path
.c_str()),
384 if (scale_divisor
== 0) {
385 LOG(ERROR
) << "Accelerometer " << accelerometer_scale_path
386 << "has scale of 0 and will not be used.";
390 configuration_
.has
[i
] = true;
391 for (size_t j
= 0; j
< arraysize(kLegacyAccelerometerAxes
); ++j
) {
392 configuration_
.scale
[i
][j
] = kMeanGravity
/ scale_divisor
;
393 std::string accelerometer_index_path
= base::StringPrintf(
394 kLegacyAccelerometerScanIndexPathFormatString
,
395 kLegacyAccelerometerAxes
[j
], kAccelerometerNames
[i
]);
396 if (!ReadFileToInt(iio_path
.Append(accelerometer_index_path
.c_str()),
397 &(configuration_
.index
[i
][j
]))) {
398 configuration_
.has
[i
] = false;
399 LOG(ERROR
) << "Index file " << accelerometer_index_path
400 << " could not be parsed\n";
404 if (configuration_
.has
[i
]) {
405 configuration_
.count
++;
406 reading_data
.sources
.push_back(static_cast<AccelerometerSource
>(i
));
410 // Adjust the directions of accelerometers to match the AccelerometerUpdate
411 // type specified in chromeos/accelerometer/accelerometer_types.h.
412 configuration_
.scale
[ACCELEROMETER_SOURCE_SCREEN
][1] *= -1.0f
;
413 configuration_
.scale
[ACCELEROMETER_SOURCE_SCREEN
][2] *= -1.0f
;
415 configuration_
.reading_data
.push_back(reading_data
);
419 void AccelerometerFileReader::ReadFileAndNotify() {
420 DCHECK(initialization_successful_
);
422 // Initiate the trigger to read accelerometers simultaneously
423 int bytes_written
= base::WriteFile(
424 base::FilePath(kAccelerometerTriggerPath
), "1\n", 2);
425 if (bytes_written
< 2) {
426 PLOG(ERROR
) << "Accelerometer trigger failure: " << bytes_written
;
430 // Read resulting sample from /dev/cros-ec-accel.
431 update_
= new AccelerometerUpdate();
432 for (auto reading_data
: configuration_
.reading_data
) {
433 int reading_size
= reading_data
.sources
.size() * kSizeOfReading
;
434 DCHECK_GT(reading_size
, 0);
435 char reading
[reading_size
];
436 int bytes_read
= base::ReadFile(reading_data
.path
, reading
, reading_size
);
437 if (bytes_read
< reading_size
) {
438 LOG(ERROR
) << "Accelerometer Read " << bytes_read
<< " byte(s), expected "
439 << reading_size
<< " bytes from accelerometer "
440 << reading_data
.path
.MaybeAsASCII();
443 for (AccelerometerSource source
: reading_data
.sources
) {
444 DCHECK(configuration_
.has
[source
]);
445 int16
* values
= reinterpret_cast<int16
*>(reading
);
446 update_
->Set(source
, values
[configuration_
.index
[source
][0]] *
447 configuration_
.scale
[source
][0],
448 values
[configuration_
.index
[source
][1]] *
449 configuration_
.scale
[source
][1],
450 values
[configuration_
.index
[source
][2]] *
451 configuration_
.scale
[source
][2]);
455 observers_
->Notify(FROM_HERE
,
456 &AccelerometerReader::Observer::OnAccelerometerUpdated
,
460 AccelerometerFileReader::ConfigurationData::ConfigurationData() : count(0) {
461 for (int i
= 0; i
< ACCELEROMETER_SOURCE_COUNT
; ++i
) {
463 for (int j
= 0; j
< 3; ++j
) {
470 AccelerometerFileReader::ConfigurationData::~ConfigurationData() {
474 AccelerometerReader
* AccelerometerReader::GetInstance() {
475 return base::Singleton
<AccelerometerReader
>::get();
478 void AccelerometerReader::Initialize(
479 scoped_refptr
<base::SequencedTaskRunner
> sequenced_task_runner
) {
480 DCHECK(sequenced_task_runner
.get());
481 // Asynchronously detect and initialize the accelerometer to avoid delaying
483 sequenced_task_runner
->PostNonNestableTask(
485 base::Bind(&AccelerometerFileReader::Initialize
,
486 accelerometer_file_reader_
.get(), sequenced_task_runner
));
489 void AccelerometerReader::AddObserver(Observer
* observer
) {
490 accelerometer_file_reader_
->AddObserver(observer
);
493 void AccelerometerReader::RemoveObserver(Observer
* observer
) {
494 accelerometer_file_reader_
->RemoveObserver(observer
);
497 AccelerometerReader::AccelerometerReader()
498 : accelerometer_file_reader_(new AccelerometerFileReader()) {
501 AccelerometerReader::~AccelerometerReader() {
504 } // namespace chromeos