Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(379)

Unified Diff: chromeos/accelerometer/accelerometer_reader.cc

Issue 200643005: Read and expose accelerometer values from cros-ec-accel trigger. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Comments, update to use udev symlink to determine device name. Created 6 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: chromeos/accelerometer/accelerometer_reader.cc
diff --git a/chromeos/accelerometer/accelerometer_reader.cc b/chromeos/accelerometer/accelerometer_reader.cc
new file mode 100644
index 0000000000000000000000000000000000000000..3129750b2da345594e5a0b0291428e4c4988ef75
--- /dev/null
+++ b/chromeos/accelerometer/accelerometer_reader.cc
@@ -0,0 +1,207 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chromeos/accelerometer/accelerometer_reader.h"
+
+#include "base/bind.h"
+#include "base/file_util.h"
+#include "base/location.h"
+#include "base/message_loop/message_loop.h"
+#include "base/strings/safe_sprintf.h"
+#include "base/strings/string_number_conversions.h"
+#include "base/strings/string_util.h"
+#include "base/task_runner_util.h"
+#include "base/threading/sequenced_worker_pool.h"
+#include "content/public/browser/browser_thread.h"
+
+namespace chromeos {
+
+namespace {
+
+// Paths to access necessary data from the accelerometer device.
+const base::FilePath::CharType kAccelerometerTriggerPath[] =
+ FILE_PATH_LITERAL("/sys/bus/iio/devices/trigger0/trigger_now");
+const base::FilePath::CharType kAccelerometerDevicePath[] =
+ FILE_PATH_LITERAL("/dev/cros-ec-accel");
+const base::FilePath::CharType kAccelerometerIioBasePath[] =
+ FILE_PATH_LITERAL("/sys/bus/iio/devices/");
+
+// Files containing the scales of the accelerometers.
Daniel Erat 2014/03/26 22:26:14 nit: mention that these are files within kAccelero
flackr 2014/03/27 15:21:07 Done.
+const base::FilePath::CharType kAccelerometerBaseScalePath[] =
+ FILE_PATH_LITERAL("in_accel_base_scale");
+const base::FilePath::CharType kAccelerometerLidScalePath[] =
+ FILE_PATH_LITERAL("in_accel_lid_scale");
+
+// The filename giving the path to read the scan index of each accelerometer
+// axis.
+const char kAccelerometerScanIndexPath[] =
+ "scan_elements/in_accel_%s_%s_index";
+
+// The maximum length string needed to store the accelerometer scan index path.
+// i.e. kAccelerometerScanIndexPath with the longest of kAccelerometerNames and
+// kAccelerometerAxes filled in. This cannot be computed as it then fails to
+// find a template match to SafeSPrintf in AccelerometerReader::Initialize for
+// the array sized to the computed value.
+const size_t kMaxAccelerometerScanIndexPathLength = 37;
+
+// The names of the accelerometers and axes in the order we want to read them.
+const char kAccelerometerNames[][5] = {"base", "lid"};
+const char kAccelerometerAxes[][2] = {"x", "y", "z"};
+const size_t kTriggerDataLength =
+ 2 * arraysize(kAccelerometerNames) * arraysize(kAccelerometerAxes);
+
+// The length required to read uint values from configuration files.
+const unsigned int kMaxAsciiUintLength = 21;
Daniel Erat 2014/03/26 22:26:14 nit: s/unsigned int/size_t/
flackr 2014/03/27 15:21:07 Done.
+
+// The time to wait between reading the accelerometer.
+const unsigned int kDelayBetweenReadsMilliseconds = 100;
Daniel Erat 2014/03/26 22:26:14 nit: just use int here, maybe also s/Milliseconds/
flackr 2014/03/27 15:21:07 Done.
+
+// Reads |path| to the unsigned int pointed to by |value|. Returns true on
+// success or false on failure.
+bool ReadFileToUint(const base::FilePath& path, unsigned int* value) {
+ std::string s;
+ DCHECK(value);
+ if (!base::ReadFileToString(path,
+ &s, kMaxAsciiUintLength)) {
Daniel Erat 2014/03/26 22:26:14 nit: can you unwrap this line?
flackr 2014/03/27 15:21:07 Done.
+ LOG(ERROR) << "Failed to read " << path.value();
+ return false;
+ }
+ base::TrimString(s, "\r\n", &s);
Daniel Erat 2014/03/26 22:26:14 nit: base::TrimWhitespace(s, base::TRIM_ALL, &s)?
flackr 2014/03/27 15:21:07 Done.
+ if (!base::StringToUint(s, value)) {
+ LOG(ERROR) << "Failed to parse \"" << s << "\" from " << path.value();
+ return false;
+ }
+ return true;
+}
+
+} // namespace
+
+using content::BrowserThread;
+
+AccelerometerReader::AccelerometerReader(AccelerometerDelegate* delegate)
+ : delegate_(delegate),
+ has_accelerometer_(false),
+ weak_factory_(this) {
+ // Asynchronously detect and initialize the accelerometer to avoid delaying
+ // startup.
+ base::PostTaskAndReplyWithResult(
+ BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior(
flackr 2014/03/26 19:06:48 Is there a better way to post a non-blocking task
Daniel Erat 2014/03/26 22:26:14 i think that the blocking pool is the right place
+ base::SequencedWorkerPool::SKIP_ON_SHUTDOWN).get(),
Daniel Erat 2014/03/26 22:26:14 if you don't need the SKIP_ON_SHUTDOWN semantics (
flackr 2014/03/27 15:21:07 Done.
+ FROM_HERE,
+ base::Bind(&AccelerometerReader::Initialize,
+ base::Unretained(this)),
Daniel Erat 2014/03/26 22:26:14 pass weak_ptrs instead to make sure that these tas
flackr 2014/03/27 15:21:07 Had to avoid return values because weak_ptrs_can_o
Daniel Erat 2014/03/27 15:37:51 ah, that's unfortunate.
+ base::Bind(&AccelerometerReader::OnInitialized,
+ base::Unretained(this)));
+}
+
+AccelerometerReader::~AccelerometerReader() {
+}
+
+bool AccelerometerReader::Initialize() {
Daniel Erat 2014/03/26 22:26:14 nit: DCHECK(BrowserThread::GetBlockingPool()->Runs
flackr 2014/03/27 15:21:07 Done.
+ // Check for accelerometer symlink which will be created by the udev rules
+ // file on detecting the device.
+ base::FilePath device;
+ if (!base::ReadSymbolicLink(base::FilePath(kAccelerometerDevicePath),
+ &device)) {
Daniel Erat 2014/03/26 22:26:14 just to check: this is expected for devices that d
flackr 2014/03/27 15:21:07 Yes.
+ return false;
+ }
+
+ if (!base::PathExists(base::FilePath(kAccelerometerTriggerPath))) {
+ LOG(ERROR) << "Accelerometer trigger does not exist.";
Daniel Erat 2014/03/26 22:26:14 nit: include kAccelerometerTriggerPath in the erro
flackr 2014/03/27 15:21:07 Done.
+ return false;
+ }
+
+ base::FilePath iio_path(base::FilePath(kAccelerometerIioBasePath).Append(
+ device));
+ // Read accelerometer scales
+ if (!ReadFileToUint(iio_path.Append(kAccelerometerBaseScalePath),
+ &accelerometer_base_scale_)) {
+ return false;
Daniel Erat 2014/03/26 22:26:14 nit: log an error and include kAccelerometerBaseSc
flackr 2014/03/27 15:21:07 For here and following uses, errors are already lo
Daniel Erat 2014/03/27 15:37:51 sure, sounds fine.
+ }
+ if (!ReadFileToUint(iio_path.Append(kAccelerometerLidScalePath),
+ &accelerometer_lid_scale_)) {
+ return false;
Daniel Erat 2014/03/26 22:26:14 nit: log an error and include kAccelerometerLidSca
flackr 2014/03/27 15:21:07 See comment above.
+ }
+
+ // Read indices of each accelerometer axis from each accelerometer from
+ // /sys/bus/iio/devices/iio:deviceX/scan_elements/in_accel_{x,y,z}_%s_index
+ for (size_t i = 0; i < arraysize(kAccelerometerNames); ++i) {
+ for (size_t j = 0; j < arraysize(kAccelerometerAxes); ++j) {
+ char accelerometer_index_path[kMaxAccelerometerScanIndexPathLength];
+ unsigned int index = 0;
+ base::strings::SafeSPrintf(accelerometer_index_path,
Daniel Erat 2014/03/26 22:26:14 can you just use an std::string in conjunction wit
flackr 2014/03/27 15:21:07 Done.
+ kAccelerometerScanIndexPath, kAccelerometerAxes[j],
+ kAccelerometerNames[i]);
+ if (!ReadFileToUint(iio_path.Append(accelerometer_index_path),
+ &index)) {
+ return false;
Daniel Erat 2014/03/26 22:26:14 nit: log an error and include the path name in the
flackr 2014/03/27 15:21:07 See comment above.
+ }
+ accelerometer_index_.push_back(index);
Daniel Erat 2014/03/26 22:26:14 do bounds-checking here to ensure that a buggy/mal
flackr 2014/03/27 15:21:07 Done.
+ }
+ }
+ return true;
+}
+
+void AccelerometerReader::OnInitialized(bool success) {
Daniel Erat 2014/03/26 22:26:14 nit: DCHECK(BrowserThread::CurrentlyOn(BrowserThre
flackr 2014/03/27 15:21:07 Done.
+ has_accelerometer_ = success;
+ if (has_accelerometer_)
+ TriggerRead();
+}
+
+void AccelerometerReader::TriggerRead() {
Daniel Erat 2014/03/26 22:26:14 nit: DCHECK(BrowserThread::CurrentlyOn(BrowserThre
flackr 2014/03/27 15:21:07 Done.
+ base::PostTaskAndReplyWithResult(
+ BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior(
+ base::SequencedWorkerPool::SKIP_ON_SHUTDOWN).get(),
+ FROM_HERE,
+ base::Bind(&AccelerometerReader::ReadAccelerometer,
+ base::Unretained(this)),
+ base::Bind(&AccelerometerReader::OnDataRead,
+ base::Unretained(this)));
Daniel Erat 2014/03/26 22:26:14 same comments here as above
flackr 2014/03/27 15:21:07 Done.
+}
+
+bool AccelerometerReader::ReadAccelerometer() {
Daniel Erat 2014/03/26 22:26:14 nit: DCHECK(BrowserThread::GetBlockingPool()->Runs
flackr 2014/03/27 15:21:07 Done.
+ // Initiate the trigger to read accelerometers simultaneously
+ int bytesWritten = base::WriteFile(
Daniel Erat 2014/03/26 22:26:14 s/bytesWritten/bytes_written/
flackr 2014/03/27 15:21:07 Done.
+ base::FilePath(kAccelerometerTriggerPath), "1\n", 2);
+ if (bytesWritten < 2) {
+ LOG(ERROR) << "Accelerometer trigger failure: " << bytesWritten;
Daniel Erat 2014/03/26 22:26:14 nit: PLOG(ERROR)
flackr 2014/03/27 15:21:07 Done.
+ return false;
+ }
+
+ // Read resulting sample from /dev/cros-ec-accel.
+ char data[kTriggerDataLength];
+ int bytesRead = base::ReadFile(base::FilePath(kAccelerometerDevicePath),
Daniel Erat 2014/03/26 22:26:14 s/bytesRead/bytes_read/
flackr 2014/03/27 15:21:07 Done.
+ data, kTriggerDataLength);
Daniel Erat 2014/03/26 22:26:14 just out of curiosity: have you timed this? how lo
flackr 2014/03/27 15:21:07 I haven't timed it yet, but I can do this. I belie
+ if (bytesRead < static_cast<int>(kTriggerDataLength)) {
+ LOG(ERROR) << "Read " << bytesRead << " bytes, expected "
Daniel Erat 2014/03/26 22:26:14 nit: s/bytes/byte(s)/
flackr 2014/03/27 15:21:07 Done.
+ << kTriggerDataLength << " bytes from accelerometer";
+ return false;
+ }
+
+ base_accelerometer_.set_x(*((int16*)data + accelerometer_index_[0]));
Daniel Erat 2014/03/26 22:26:14 nit: use reinterpret_cast<int16*> instead of c-sty
flackr 2014/03/27 15:21:07 Done.
+ base_accelerometer_.set_y(*((int16*)data + accelerometer_index_[1]));
+ base_accelerometer_.set_z(*((int16*)data + accelerometer_index_[2]));
+ base_accelerometer_.Scale(1.0f / accelerometer_base_scale_);
+
+ lid_accelerometer_.set_x(*((int16*)data + accelerometer_index_[3]));
+ lid_accelerometer_.set_y(*((int16*)data + accelerometer_index_[4]));
+ lid_accelerometer_.set_z(*((int16*)data + accelerometer_index_[5]));
+ lid_accelerometer_.Scale(1.0f / accelerometer_lid_scale_);
Daniel Erat 2014/03/26 22:26:14 i'm a bit concerned that a future change could add
flackr 2014/03/27 15:21:07 I added a comment to this effect (in the header),
+ return true;
+}
+
+void AccelerometerReader::OnDataRead(bool success) {
Daniel Erat 2014/03/26 22:26:14 nit: DCHECK(BrowserThread::CurrentlyOn(BrowserThre
flackr 2014/03/27 15:21:07 Done.
+ // If successful, notify the AccelerometerDelegate.
+ if (success)
+ delegate_->OnAccelerometerRead(base_accelerometer_, lid_accelerometer_);
+
+ // Trigger another read after the current sampling delay.
+ base::MessageLoop::current()->PostDelayedTask(
+ FROM_HERE,
+ base::Bind(&AccelerometerReader::TriggerRead,
+ weak_factory_.GetWeakPtr()),
+ base::TimeDelta::FromMilliseconds(kDelayBetweenReadsMilliseconds));
+}
+
+} // namespace chromeos

Powered by Google App Engine
This is Rietveld 408576698