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/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/sequenced_worker_pool.h"
26 // Paths to access necessary data from the accelerometer device.
27 const base::FilePath::CharType kAccelerometerTriggerPath
[] =
28 FILE_PATH_LITERAL("/sys/bus/iio/devices/trigger0/trigger_now");
29 const base::FilePath::CharType kAccelerometerDevicePath
[] =
30 FILE_PATH_LITERAL("/dev/cros-ec-accel");
31 const base::FilePath::CharType kAccelerometerIioBasePath
[] =
32 FILE_PATH_LITERAL("/sys/bus/iio/devices/");
34 // File within the device in kAccelerometerIioBasePath containing the scale of
35 // the accelerometers.
36 const base::FilePath::CharType kScaleNameFormatString
[] = "in_accel_%s_scale";
38 // The filename giving the path to read the scan index of each accelerometer
40 const char kAccelerometerScanIndexPath
[] =
41 "scan_elements/in_accel_%s_%s_index";
43 // The names of the accelerometers. Matches up with the enum AccelerometerSource
44 // in chromeos/accelerometer/accelerometer_types.h.
45 const char kAccelerometerNames
[ACCELEROMETER_SOURCE_COUNT
][5] = {"lid", "base"};
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 mean acceleration due to gravity on Earth in m/s^2.
57 const float kMeanGravity
= 9.80665f
;
59 // Reads |path| to the unsigned int pointed to by |value|. Returns true on
60 // success or false on failure.
61 bool ReadFileToInt(const base::FilePath
& path
, int* value
) {
64 if (!base::ReadFileToString(path
, &s
, kMaxAsciiUintLength
)) {
67 base::TrimWhitespaceASCII(s
, base::TRIM_ALL
, &s
);
68 if (!base::StringToInt(s
, value
)) {
69 LOG(ERROR
) << "Failed to parse \"" << s
<< "\" from " << path
.value();
75 bool DetectAndReadAccelerometerConfiguration(
76 scoped_refptr
<AccelerometerReader::Configuration
> configuration
) {
77 // Check for accelerometer symlink which will be created by the udev rules
78 // file on detecting the device.
79 base::FilePath device
;
80 if (!base::ReadSymbolicLink(base::FilePath(kAccelerometerDevicePath
),
85 if (!base::PathExists(base::FilePath(kAccelerometerTriggerPath
))) {
86 LOG(ERROR
) << "Accelerometer trigger does not exist at"
87 << kAccelerometerTriggerPath
;
91 base::FilePath
iio_path(base::FilePath(kAccelerometerIioBasePath
).Append(
93 // Read configuration of each accelerometer axis from each accelerometer from
94 // /sys/bus/iio/devices/iio:deviceX/.
95 for (size_t i
= 0; i
< arraysize(kAccelerometerNames
); ++i
) {
96 // Read scale of accelerometer.
97 std::string accelerometer_scale_path
= base::StringPrintf(
98 kScaleNameFormatString
, kAccelerometerNames
[i
]);
100 if (!ReadFileToInt(iio_path
.Append(accelerometer_scale_path
.c_str()),
102 configuration
->data
.has
[i
] = false;
106 configuration
->data
.has
[i
] = true;
107 configuration
->data
.count
++;
108 for (size_t j
= 0; j
< arraysize(kAccelerometerAxes
); ++j
) {
109 configuration
->data
.scale
[i
][j
] = kMeanGravity
/ scale_divisor
;
110 std::string accelerometer_index_path
= base::StringPrintf(
111 kAccelerometerScanIndexPath
, kAccelerometerAxes
[j
],
112 kAccelerometerNames
[i
]);
113 if (!ReadFileToInt(iio_path
.Append(accelerometer_index_path
.c_str()),
114 &(configuration
->data
.index
[i
][j
]))) {
120 // Adjust the directions of accelerometers to match the AccelerometerUpdate
121 // type specified in chromeos/accelerometer/accelerometer_types.h.
122 configuration
->data
.scale
[ACCELEROMETER_SOURCE_SCREEN
][0] *= -1.0f
;
123 for (int i
= 0; i
< 3; ++i
) {
124 configuration
->data
.scale
[ACCELEROMETER_SOURCE_ATTACHED_KEYBOARD
][i
] *=
128 // Verify indices are within bounds.
129 for (int i
= 0; i
< ACCELEROMETER_SOURCE_COUNT
; ++i
) {
130 if (!configuration
->data
.has
[i
])
132 for (int j
= 0; j
< 3; ++j
) {
133 if (configuration
->data
.index
[i
][j
] < 0 ||
134 configuration
->data
.index
[i
][j
] >=
135 3 * static_cast<int>(configuration
->data
.count
)) {
136 LOG(ERROR
) << "Field index for " << kAccelerometerNames
[i
] << " "
137 << kAccelerometerAxes
[j
] << " axis out of bounds.";
142 configuration
->data
.length
= kDataSize
* 3 * configuration
->data
.count
;
146 bool ReadAccelerometer(
147 scoped_refptr
<AccelerometerReader::Reading
> reading
,
149 // Initiate the trigger to read accelerometers simultaneously
150 int bytes_written
= base::WriteFile(
151 base::FilePath(kAccelerometerTriggerPath
), "1\n", 2);
152 if (bytes_written
< 2) {
153 PLOG(ERROR
) << "Accelerometer trigger failure: " << bytes_written
;
157 // Read resulting sample from /dev/cros-ec-accel.
158 int bytes_read
= base::ReadFile(base::FilePath(kAccelerometerDevicePath
),
159 reading
->data
, length
);
160 if (bytes_read
< static_cast<int>(length
)) {
161 LOG(ERROR
) << "Read " << bytes_read
<< " byte(s), expected "
162 << length
<< " bytes from accelerometer";
170 const int AccelerometerReader::kDelayBetweenReadsMs
= 100;
172 AccelerometerReader::ConfigurationData::ConfigurationData()
174 for (int i
= 0; i
< ACCELEROMETER_SOURCE_COUNT
; ++i
) {
176 for (int j
= 0; j
< 3; ++j
) {
183 AccelerometerReader::ConfigurationData::~ConfigurationData() {
187 AccelerometerReader
* AccelerometerReader::GetInstance() {
188 return Singleton
<AccelerometerReader
>::get();
191 void AccelerometerReader::Initialize(
192 scoped_refptr
<base::TaskRunner
> blocking_task_runner
) {
193 DCHECK(blocking_task_runner
.get());
194 task_runner_
= blocking_task_runner
;
195 // Asynchronously detect and initialize the accelerometer to avoid delaying
197 base::PostTaskAndReplyWithResult(
198 task_runner_
.get(), FROM_HERE
,
199 base::Bind(&DetectAndReadAccelerometerConfiguration
, configuration_
),
200 base::Bind(&AccelerometerReader::OnInitialized
,
201 weak_factory_
.GetWeakPtr(), configuration_
));
204 void AccelerometerReader::AddObserver(Observer
* observer
) {
205 observers_
->AddObserver(observer
);
207 observer
->OnAccelerometerUpdated(update_
.get());
210 void AccelerometerReader::RemoveObserver(Observer
* observer
) {
211 observers_
->RemoveObserver(observer
);
214 AccelerometerReader::AccelerometerReader()
215 : configuration_(new AccelerometerReader::Configuration()),
216 observers_(new base::ObserverListThreadSafe
<Observer
>()),
217 weak_factory_(this) {
220 AccelerometerReader::~AccelerometerReader() {
223 void AccelerometerReader::OnInitialized(
224 scoped_refptr
<AccelerometerReader::Configuration
> configuration
,
230 void AccelerometerReader::TriggerRead() {
231 DCHECK(!task_runner_
->RunsTasksOnCurrentThread());
233 scoped_refptr
<AccelerometerReader::Reading
> reading(
234 new AccelerometerReader::Reading());
235 base::PostTaskAndReplyWithResult(task_runner_
.get(),
237 base::Bind(&ReadAccelerometer
, reading
,
238 configuration_
->data
.length
),
239 base::Bind(&AccelerometerReader::OnDataRead
,
240 weak_factory_
.GetWeakPtr(),
244 void AccelerometerReader::OnDataRead(
245 scoped_refptr
<AccelerometerReader::Reading
> reading
,
247 DCHECK(!task_runner_
->RunsTasksOnCurrentThread());
250 update_
= new AccelerometerUpdate();
251 for (int i
= 0; i
< ACCELEROMETER_SOURCE_COUNT
; ++i
) {
252 if (!configuration_
->data
.has
[i
])
255 int16
* values
= reinterpret_cast<int16
*>(reading
->data
);
256 update_
->Set(static_cast<AccelerometerSource
>(i
),
257 values
[configuration_
->data
.index
[i
][0]] *
258 configuration_
->data
.scale
[i
][0],
259 values
[configuration_
->data
.index
[i
][1]] *
260 configuration_
->data
.scale
[i
][1],
261 values
[configuration_
->data
.index
[i
][2]] *
262 configuration_
->data
.scale
[i
][2]);
264 // TODO(jonross): move this to the blocking thread (crbug.com/461433)
265 observers_
->Notify(FROM_HERE
, &Observer::OnAccelerometerUpdated
, update_
);
268 // Trigger another read after the current sampling delay.
269 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
271 base::Bind(&AccelerometerReader::TriggerRead
, weak_factory_
.GetWeakPtr()),
272 base::TimeDelta::FromMilliseconds(kDelayBetweenReadsMs
));
275 } // namespace chromeos