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/files/file_util.h"
11 #include "base/location.h"
12 #include "base/memory/singleton.h"
13 #include "base/message_loop/message_loop.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/threading/sequenced_worker_pool.h"
25 // Paths to access necessary data from the accelerometer device.
26 const base::FilePath::CharType kAccelerometerTriggerPath
[] =
27 FILE_PATH_LITERAL("/sys/bus/iio/devices/trigger0/trigger_now");
28 const base::FilePath::CharType kAccelerometerDevicePath
[] =
29 FILE_PATH_LITERAL("/dev/cros-ec-accel");
30 const base::FilePath::CharType kAccelerometerIioBasePath
[] =
31 FILE_PATH_LITERAL("/sys/bus/iio/devices/");
33 // File within the device in kAccelerometerIioBasePath containing the scale of
34 // the accelerometers.
35 const base::FilePath::CharType kScaleNameFormatString
[] = "in_accel_%s_scale";
37 // The filename giving the path to read the scan index of each accelerometer
39 const char kAccelerometerScanIndexPath
[] =
40 "scan_elements/in_accel_%s_%s_index";
42 // The names of the accelerometers. Matches up with the enum AccelerometerSource
43 // in ui/accelerometer/accelerometer_types.h.
44 const char kAccelerometerNames
[ui::ACCELEROMETER_SOURCE_COUNT
][5] = {
47 // The axes on each accelerometer.
48 const char kAccelerometerAxes
[][2] = {"y", "x", "z"};
50 // The length required to read uint values from configuration files.
51 const size_t kMaxAsciiUintLength
= 21;
53 // The size of individual values.
54 const size_t kDataSize
= 2;
56 // The time to wait between reading the accelerometer.
57 const int kDelayBetweenReadsMs
= 100;
59 // The mean acceleration due to gravity on Earth in m/s^2.
60 const float kMeanGravity
= 9.80665f
;
62 // The maximum deviation from the acceleration expected due to gravity under
63 // which to detect hinge angle and screen rotation in m/s^2
64 const float kDeviationFromGravityThreshold
= 1.0f
;
66 // Reads |path| to the unsigned int pointed to by |value|. Returns true on
67 // success or false on failure.
68 bool ReadFileToInt(const base::FilePath
& path
, int* value
) {
71 if (!base::ReadFileToString(path
, &s
, kMaxAsciiUintLength
)) {
74 base::TrimWhitespaceASCII(s
, base::TRIM_ALL
, &s
);
75 if (!base::StringToInt(s
, value
)) {
76 LOG(ERROR
) << "Failed to parse \"" << s
<< "\" from " << path
.value();
82 bool DetectAndReadAccelerometerConfiguration(
83 scoped_refptr
<AccelerometerReader::Configuration
> configuration
) {
84 // Check for accelerometer symlink which will be created by the udev rules
85 // file on detecting the device.
86 base::FilePath device
;
87 if (!base::ReadSymbolicLink(base::FilePath(kAccelerometerDevicePath
),
92 if (!base::PathExists(base::FilePath(kAccelerometerTriggerPath
))) {
93 LOG(ERROR
) << "Accelerometer trigger does not exist at"
94 << kAccelerometerTriggerPath
;
98 base::FilePath
iio_path(base::FilePath(kAccelerometerIioBasePath
).Append(
100 // Read configuration of each accelerometer axis from each accelerometer from
101 // /sys/bus/iio/devices/iio:deviceX/.
102 for (size_t i
= 0; i
< arraysize(kAccelerometerNames
); ++i
) {
103 // Read scale of accelerometer.
104 std::string accelerometer_scale_path
= base::StringPrintf(
105 kScaleNameFormatString
, kAccelerometerNames
[i
]);
107 if (!ReadFileToInt(iio_path
.Append(accelerometer_scale_path
.c_str()),
109 configuration
->data
.has
[i
] = false;
113 configuration
->data
.has
[i
] = true;
114 configuration
->data
.count
++;
115 for (size_t j
= 0; j
< arraysize(kAccelerometerAxes
); ++j
) {
116 configuration
->data
.scale
[i
][j
] = kMeanGravity
/ scale_divisor
;
117 std::string accelerometer_index_path
= base::StringPrintf(
118 kAccelerometerScanIndexPath
, kAccelerometerAxes
[j
],
119 kAccelerometerNames
[i
]);
120 if (!ReadFileToInt(iio_path
.Append(accelerometer_index_path
.c_str()),
121 &(configuration
->data
.index
[i
][j
]))) {
127 // Adjust the directions of accelerometers to match the AccelerometerUpdate
128 // type specified in ui/accelerometer/accelerometer_types.h.
129 configuration
->data
.scale
[ui::ACCELEROMETER_SOURCE_SCREEN
][0] *= -1.0f
;
130 for (int i
= 0; i
< 3; ++i
) {
131 configuration
->data
.scale
[ui::ACCELEROMETER_SOURCE_ATTACHED_KEYBOARD
][i
] *=
135 // Verify indices are within bounds.
136 for (int i
= 0; i
< ui::ACCELEROMETER_SOURCE_COUNT
; ++i
) {
137 if (!configuration
->data
.has
[i
])
139 for (int j
= 0; j
< 3; ++j
) {
140 if (configuration
->data
.index
[i
][j
] < 0 ||
141 configuration
->data
.index
[i
][j
] >=
142 3 * static_cast<int>(configuration
->data
.count
)) {
143 LOG(ERROR
) << "Field index for " << kAccelerometerNames
[i
] << " "
144 << kAccelerometerAxes
[j
] << " axis out of bounds.";
149 configuration
->data
.length
= kDataSize
* 3 * configuration
->data
.count
;
153 bool ReadAccelerometer(
154 scoped_refptr
<AccelerometerReader::Reading
> reading
,
156 // Initiate the trigger to read accelerometers simultaneously
157 int bytes_written
= base::WriteFile(
158 base::FilePath(kAccelerometerTriggerPath
), "1\n", 2);
159 if (bytes_written
< 2) {
160 PLOG(ERROR
) << "Accelerometer trigger failure: " << bytes_written
;
164 // Read resulting sample from /dev/cros-ec-accel.
165 int bytes_read
= base::ReadFile(base::FilePath(kAccelerometerDevicePath
),
166 reading
->data
, length
);
167 if (bytes_read
< static_cast<int>(length
)) {
168 LOG(ERROR
) << "Read " << bytes_read
<< " byte(s), expected "
169 << length
<< " bytes from accelerometer";
177 AccelerometerReader::ConfigurationData::ConfigurationData()
179 for (int i
= 0; i
< ui::ACCELEROMETER_SOURCE_COUNT
; ++i
) {
181 for (int j
= 0; j
< 3; ++j
) {
188 AccelerometerReader::ConfigurationData::~ConfigurationData() {
192 AccelerometerReader
* AccelerometerReader::GetInstance() {
193 return Singleton
<AccelerometerReader
>::get();
196 void AccelerometerReader::Initialize(
197 scoped_refptr
<base::TaskRunner
> blocking_task_runner
) {
198 DCHECK(blocking_task_runner
.get());
199 task_runner_
= blocking_task_runner
;
200 // Asynchronously detect and initialize the accelerometer to avoid delaying
202 base::PostTaskAndReplyWithResult(
203 task_runner_
.get(), FROM_HERE
,
204 base::Bind(&DetectAndReadAccelerometerConfiguration
, configuration_
),
205 base::Bind(&AccelerometerReader::OnInitialized
,
206 weak_factory_
.GetWeakPtr(), configuration_
));
209 void AccelerometerReader::AddObserver(Observer
* observer
) {
210 observers_
.AddObserver(observer
);
211 observer
->OnAccelerometerUpdated(update_
);
214 void AccelerometerReader::RemoveObserver(Observer
* observer
) {
215 observers_
.RemoveObserver(observer
);
218 bool AccelerometerReader::IsReadingStable(const ui::AccelerometerUpdate
& update
,
219 ui::AccelerometerSource source
) {
220 return update
.has(source
) &&
221 std::abs(update
.get(source
).Length() - kMeanGravity
) <=
222 kDeviationFromGravityThreshold
;
225 AccelerometerReader::AccelerometerReader()
226 : configuration_(new AccelerometerReader::Configuration()),
227 weak_factory_(this) {
230 AccelerometerReader::~AccelerometerReader() {
233 void AccelerometerReader::OnInitialized(
234 scoped_refptr
<AccelerometerReader::Configuration
> configuration
,
240 void AccelerometerReader::TriggerRead() {
241 DCHECK(!task_runner_
->RunsTasksOnCurrentThread());
243 scoped_refptr
<AccelerometerReader::Reading
> reading(
244 new AccelerometerReader::Reading());
245 base::PostTaskAndReplyWithResult(task_runner_
.get(),
247 base::Bind(&ReadAccelerometer
, reading
,
248 configuration_
->data
.length
),
249 base::Bind(&AccelerometerReader::OnDataRead
,
250 weak_factory_
.GetWeakPtr(),
254 void AccelerometerReader::OnDataRead(
255 scoped_refptr
<AccelerometerReader::Reading
> reading
,
257 DCHECK(!task_runner_
->RunsTasksOnCurrentThread());
260 for (int i
= 0; i
< ui::ACCELEROMETER_SOURCE_COUNT
; ++i
) {
261 if (!configuration_
->data
.has
[i
])
264 int16
* values
= reinterpret_cast<int16
*>(reading
->data
);
265 update_
.Set(static_cast<ui::AccelerometerSource
>(i
),
266 values
[configuration_
->data
.index
[i
][0]] *
267 configuration_
->data
.scale
[i
][0],
268 values
[configuration_
->data
.index
[i
][1]] *
269 configuration_
->data
.scale
[i
][1],
270 values
[configuration_
->data
.index
[i
][2]] *
271 configuration_
->data
.scale
[i
][2]);
273 FOR_EACH_OBSERVER(Observer
, observers_
, OnAccelerometerUpdated(update_
));
276 // Trigger another read after the current sampling delay.
277 base::MessageLoop::current()->PostDelayedTask(
279 base::Bind(&AccelerometerReader::TriggerRead
,
280 weak_factory_
.GetWeakPtr()),
281 base::TimeDelta::FromMilliseconds(kDelayBetweenReadsMs
));
284 } // namespace chromeos