Supervised user whitelists: Cleanup
[chromium-blink-merge.git] / chromeos / accelerometer / accelerometer_reader.cc
blobfe8422c1ca6ec0965361c6a8a379858538f0d9f8
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/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"
21 namespace chromeos {
23 namespace {
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
38 // axis.
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) {
61 std::string s;
62 DCHECK(value);
63 if (!base::ReadFileToString(path, &s, kMaxAsciiUintLength)) {
64 return false;
66 base::TrimWhitespaceASCII(s, base::TRIM_ALL, &s);
67 if (!base::StringToInt(s, value)) {
68 LOG(ERROR) << "Failed to parse \"" << s << "\" from " << path.value();
69 return false;
71 return true;
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),
80 &device)) {
81 return false;
84 if (!base::PathExists(base::FilePath(kAccelerometerTriggerPath))) {
85 LOG(ERROR) << "Accelerometer trigger does not exist at"
86 << kAccelerometerTriggerPath;
87 return false;
90 base::FilePath iio_path(base::FilePath(kAccelerometerIioBasePath).Append(
91 device));
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]);
98 int scale_divisor;
99 if (!ReadFileToInt(iio_path.Append(accelerometer_scale_path.c_str()),
100 &scale_divisor)) {
101 configuration->data.has[i] = false;
102 continue;
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]))) {
114 return false;
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] *=
124 -1.0f;
127 // Verify indices are within bounds.
128 for (int i = 0; i < ACCELEROMETER_SOURCE_COUNT; ++i) {
129 if (!configuration->data.has[i])
130 continue;
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.";
137 return false;
141 configuration->data.length = kDataSize * 3 * configuration->data.count;
142 return true;
145 bool ReadAccelerometer(
146 scoped_refptr<AccelerometerReader::Reading> reading,
147 size_t length) {
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;
153 return false;
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";
162 return false;
164 return true;
167 } // namespace
169 const int AccelerometerReader::kDelayBetweenReadsMs = 100;
171 AccelerometerReader::ConfigurationData::ConfigurationData()
172 : count(0) {
173 for (int i = 0; i < ACCELEROMETER_SOURCE_COUNT; ++i) {
174 has[i] = false;
175 for (int j = 0; j < 3; ++j) {
176 scale[i][j] = 0;
177 index[i][j] = -1;
182 AccelerometerReader::ConfigurationData::~ConfigurationData() {
185 // static
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
195 // startup.
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);
205 if (update_)
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,
224 bool success) {
225 if (success)
226 TriggerRead();
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(),
235 FROM_HERE,
236 base::Bind(&ReadAccelerometer, reading,
237 configuration_->data.length),
238 base::Bind(&AccelerometerReader::OnDataRead,
239 weak_factory_.GetWeakPtr(),
240 reading));
243 void AccelerometerReader::OnDataRead(
244 scoped_refptr<AccelerometerReader::Reading> reading,
245 bool success) {
246 DCHECK(!task_runner_->RunsTasksOnCurrentThread());
248 if (success) {
249 update_ = new AccelerometerUpdate();
250 for (int i = 0; i < ACCELEROMETER_SOURCE_COUNT; ++i) {
251 if (!configuration_->data.has[i])
252 continue;
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(
269 FROM_HERE,
270 base::Bind(&AccelerometerReader::TriggerRead,
271 weak_factory_.GetWeakPtr()),
272 base::TimeDelta::FromMilliseconds(kDelayBetweenReadsMs));
275 } // namespace chromeos