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 chromeos/accelerometer/accelerometer_types.h.
44 const char kAccelerometerNames
[ACCELEROMETER_SOURCE_COUNT
][5] = {"lid", "base"};
46 // The axes on each accelerometer.
47 const char kAccelerometerAxes
[][2] = {"y", "x", "z"};
49 // The length required to read uint values from configuration files.
50 const size_t kMaxAsciiUintLength
= 21;
52 // The size of individual values.
53 const size_t kDataSize
= 2;
55 // The mean acceleration due to gravity on Earth in m/s^2.
56 const float kMeanGravity
= 9.80665f
;
58 // Reads |path| to the unsigned int pointed to by |value|. Returns true on
59 // success or false on failure.
60 bool ReadFileToInt(const base::FilePath
& path
, int* value
) {
63 if (!base::ReadFileToString(path
, &s
, kMaxAsciiUintLength
)) {
66 base::TrimWhitespaceASCII(s
, base::TRIM_ALL
, &s
);
67 if (!base::StringToInt(s
, value
)) {
68 LOG(ERROR
) << "Failed to parse \"" << s
<< "\" from " << path
.value();
74 bool DetectAndReadAccelerometerConfiguration(
75 scoped_refptr
<AccelerometerReader::Configuration
> configuration
) {
76 // Check for accelerometer symlink which will be created by the udev rules
77 // file on detecting the device.
78 base::FilePath device
;
79 if (!base::ReadSymbolicLink(base::FilePath(kAccelerometerDevicePath
),
84 if (!base::PathExists(base::FilePath(kAccelerometerTriggerPath
))) {
85 LOG(ERROR
) << "Accelerometer trigger does not exist at"
86 << kAccelerometerTriggerPath
;
90 base::FilePath
iio_path(base::FilePath(kAccelerometerIioBasePath
).Append(
92 // Read configuration of each accelerometer axis from each accelerometer from
93 // /sys/bus/iio/devices/iio:deviceX/.
94 for (size_t i
= 0; i
< arraysize(kAccelerometerNames
); ++i
) {
95 // Read scale of accelerometer.
96 std::string accelerometer_scale_path
= base::StringPrintf(
97 kScaleNameFormatString
, kAccelerometerNames
[i
]);
99 if (!ReadFileToInt(iio_path
.Append(accelerometer_scale_path
.c_str()),
101 configuration
->data
.has
[i
] = false;
105 configuration
->data
.has
[i
] = true;
106 configuration
->data
.count
++;
107 for (size_t j
= 0; j
< arraysize(kAccelerometerAxes
); ++j
) {
108 configuration
->data
.scale
[i
][j
] = kMeanGravity
/ scale_divisor
;
109 std::string accelerometer_index_path
= base::StringPrintf(
110 kAccelerometerScanIndexPath
, kAccelerometerAxes
[j
],
111 kAccelerometerNames
[i
]);
112 if (!ReadFileToInt(iio_path
.Append(accelerometer_index_path
.c_str()),
113 &(configuration
->data
.index
[i
][j
]))) {
119 // Adjust the directions of accelerometers to match the AccelerometerUpdate
120 // type specified in chromeos/accelerometer/accelerometer_types.h.
121 configuration
->data
.scale
[ACCELEROMETER_SOURCE_SCREEN
][0] *= -1.0f
;
122 for (int i
= 0; i
< 3; ++i
) {
123 configuration
->data
.scale
[ACCELEROMETER_SOURCE_ATTACHED_KEYBOARD
][i
] *=
127 // Verify indices are within bounds.
128 for (int i
= 0; i
< ACCELEROMETER_SOURCE_COUNT
; ++i
) {
129 if (!configuration
->data
.has
[i
])
131 for (int j
= 0; j
< 3; ++j
) {
132 if (configuration
->data
.index
[i
][j
] < 0 ||
133 configuration
->data
.index
[i
][j
] >=
134 3 * static_cast<int>(configuration
->data
.count
)) {
135 LOG(ERROR
) << "Field index for " << kAccelerometerNames
[i
] << " "
136 << kAccelerometerAxes
[j
] << " axis out of bounds.";
141 configuration
->data
.length
= kDataSize
* 3 * configuration
->data
.count
;
145 bool ReadAccelerometer(
146 scoped_refptr
<AccelerometerReader::Reading
> reading
,
148 // Initiate the trigger to read accelerometers simultaneously
149 int bytes_written
= base::WriteFile(
150 base::FilePath(kAccelerometerTriggerPath
), "1\n", 2);
151 if (bytes_written
< 2) {
152 PLOG(ERROR
) << "Accelerometer trigger failure: " << bytes_written
;
156 // Read resulting sample from /dev/cros-ec-accel.
157 int bytes_read
= base::ReadFile(base::FilePath(kAccelerometerDevicePath
),
158 reading
->data
, length
);
159 if (bytes_read
< static_cast<int>(length
)) {
160 LOG(ERROR
) << "Read " << bytes_read
<< " byte(s), expected "
161 << length
<< " bytes from accelerometer";
169 const int AccelerometerReader::kDelayBetweenReadsMs
= 100;
171 AccelerometerReader::ConfigurationData::ConfigurationData()
173 for (int i
= 0; i
< ACCELEROMETER_SOURCE_COUNT
; ++i
) {
175 for (int j
= 0; j
< 3; ++j
) {
182 AccelerometerReader::ConfigurationData::~ConfigurationData() {
186 AccelerometerReader
* AccelerometerReader::GetInstance() {
187 return Singleton
<AccelerometerReader
>::get();
190 void AccelerometerReader::Initialize(
191 scoped_refptr
<base::TaskRunner
> blocking_task_runner
) {
192 DCHECK(blocking_task_runner
.get());
193 task_runner_
= blocking_task_runner
;
194 // Asynchronously detect and initialize the accelerometer to avoid delaying
196 base::PostTaskAndReplyWithResult(
197 task_runner_
.get(), FROM_HERE
,
198 base::Bind(&DetectAndReadAccelerometerConfiguration
, configuration_
),
199 base::Bind(&AccelerometerReader::OnInitialized
,
200 weak_factory_
.GetWeakPtr(), configuration_
));
203 void AccelerometerReader::AddObserver(Observer
* observer
) {
204 observers_
->AddObserver(observer
);
206 observer
->OnAccelerometerUpdated(update_
.get());
209 void AccelerometerReader::RemoveObserver(Observer
* observer
) {
210 observers_
->RemoveObserver(observer
);
213 AccelerometerReader::AccelerometerReader()
214 : configuration_(new AccelerometerReader::Configuration()),
215 observers_(new ObserverListThreadSafe
<Observer
>()),
216 weak_factory_(this) {
219 AccelerometerReader::~AccelerometerReader() {
222 void AccelerometerReader::OnInitialized(
223 scoped_refptr
<AccelerometerReader::Configuration
> configuration
,
229 void AccelerometerReader::TriggerRead() {
230 DCHECK(!task_runner_
->RunsTasksOnCurrentThread());
232 scoped_refptr
<AccelerometerReader::Reading
> reading(
233 new AccelerometerReader::Reading());
234 base::PostTaskAndReplyWithResult(task_runner_
.get(),
236 base::Bind(&ReadAccelerometer
, reading
,
237 configuration_
->data
.length
),
238 base::Bind(&AccelerometerReader::OnDataRead
,
239 weak_factory_
.GetWeakPtr(),
243 void AccelerometerReader::OnDataRead(
244 scoped_refptr
<AccelerometerReader::Reading
> reading
,
246 DCHECK(!task_runner_
->RunsTasksOnCurrentThread());
249 update_
= new AccelerometerUpdate();
250 for (int i
= 0; i
< ACCELEROMETER_SOURCE_COUNT
; ++i
) {
251 if (!configuration_
->data
.has
[i
])
254 int16
* values
= reinterpret_cast<int16
*>(reading
->data
);
255 update_
->Set(static_cast<AccelerometerSource
>(i
),
256 values
[configuration_
->data
.index
[i
][0]] *
257 configuration_
->data
.scale
[i
][0],
258 values
[configuration_
->data
.index
[i
][1]] *
259 configuration_
->data
.scale
[i
][1],
260 values
[configuration_
->data
.index
[i
][2]] *
261 configuration_
->data
.scale
[i
][2]);
263 // TODO(jonross): move this to the blocking thread (crbug.com/461433)
264 observers_
->Notify(FROM_HERE
, &Observer::OnAccelerometerUpdated
, update_
);
267 // Trigger another read after the current sampling delay.
268 base::MessageLoop::current()->PostDelayedTask(
270 base::Bind(&AccelerometerReader::TriggerRead
,
271 weak_factory_
.GetWeakPtr()),
272 base::TimeDelta::FromMilliseconds(kDelayBetweenReadsMs
));
275 } // namespace chromeos