diff options
Diffstat (limited to 'chrome/browser')
-rw-r--r-- | chrome/browser/device_orientation/accelerometer_mac.cc | 335 | ||||
-rw-r--r-- | chrome/browser/device_orientation/accelerometer_mac.h | 102 | ||||
-rw-r--r-- | chrome/browser/device_orientation/provider.cc | 12 |
3 files changed, 448 insertions, 1 deletions
diff --git a/chrome/browser/device_orientation/accelerometer_mac.cc b/chrome/browser/device_orientation/accelerometer_mac.cc new file mode 100644 index 0000000..eb0990710 --- /dev/null +++ b/chrome/browser/device_orientation/accelerometer_mac.cc @@ -0,0 +1,335 @@ +// Copyright (c) 2010 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. +// +// This file is based on the SMSLib library. +// +// SMSLib Sudden Motion Sensor Access Library +// Copyright (c) 2010 Suitable Systems +// All rights reserved. +// +// Developed by: Daniel Griscom +// Suitable Systems +// http://www.suitable.com +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal with the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in the +// documentation and/or other materials provided with the distribution. +// +// - Neither the names of Suitable Systems nor the names of its +// contributors may be used to endorse or promote products derived from +// this Software without specific prior written permission. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR +// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +// SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE. +// +// For more information about SMSLib, see +// <http://www.suitable.com/tools/smslib.html> +// or contact +// Daniel Griscom +// Suitable Systems +// 1 Centre Street, Suite 204 +// Wakefield, MA 01880 +// (781) 665-0053 + +#include "chrome/browser/device_orientation/accelerometer_mac.h" + +#include <math.h> // For isfinite. +#include <sys/sysctl.h> + +#include "base/logging.h" +#include "base/scoped_ptr.h" +#include "chrome/browser/device_orientation/orientation.h" + +namespace device_orientation { + +// Per-axis sensor data. +struct AccelerometerMac::AxisData { + // Non-zero if the axis is valid in this sensor. + int enabled; + + // Location in struct of first byte. + int index; + + // Number of bytes of the axis data. + int size; + + // Value meaning "zero g". + float zero_g; + + // (can be negative if the sensor axis is reversed). + float one_g; +}; + +// Sudden Motion Sensor descriptor. +struct AccelerometerMac::SensorDescriptor { + // Prefix of model to be tested. + const char* model_name; + + // Name of device to be read. + const char* service_name; + + // Kernel function index. + unsigned int function; + + // Size of record to be sent/received. + unsigned int record_size; + + // Description of three axes (x,y,z). + AxisData axes[3]; +}; + +// Supported sensor descriptors. Add entries here to enhance compatibility. +// All non-tested entries from SMSLib have been removed. +const AccelerometerMac::SensorDescriptor + AccelerometerMac::kSupportedSensors[] = { + // Tested by leandrogracia on a 15'' MacBook Pro. + { "MacBookPro5,4", "SMCMotionSensor", 5, 40, { + { 1, 0, 2, 0, 251 }, + { 1, 2, 2, 0, 251 }, + { 1, 4, 2, 0, 251 } + } }, + + // Tested by leandrogracia on a 13'' MacBook Pro. + { "MacBookPro5,5", "SMCMotionSensor", 5, 40, { + { 1, 0, 2, 0, -251 }, + { 1, 2, 2, 0, -251 }, + { 1, 4, 2, 0, 251 } + } }, + + // Generic MacBook accelerometer sensor data. + // Added for forward compatibility (there may be problems with inverted axes). + {"", "SMCMotionSensor", 5, 40, { + { 1, 0, 2, 0, -251 }, + { 1, 2, 2, 0, -251 }, + { 1, 4, 2, 0, 251 } + } } +}; + +// Create a AccelerometerMac object and return NULL if no valid sensor found. +DataFetcher* AccelerometerMac::Create() { + scoped_ptr<AccelerometerMac> accelerometer(new AccelerometerMac); + return accelerometer->Init() ? accelerometer.release() : NULL; +} + +AccelerometerMac::~AccelerometerMac() { + IOServiceClose(io_connection_); +} + +AccelerometerMac::AccelerometerMac() + : sensor_(NULL), + io_connection_(0) { +} + +// Retrieve per-axis accelerometer values. +// +// Axes and angles are defined according to the W3C DeviceOrientation Draft. +// See here: http://dev.w3.org/geo/api/spec-source-orientation.html +// +// Note: only beta and gamma angles are provided. Alpha is set to zero. +// +// Returns false in case of error or non-properly initialized object. +// +bool AccelerometerMac::GetOrientation(Orientation* orientation) { + DCHECK(sensor_); + + // Reset output record memory buffer. + std::fill(output_record_.begin(), output_record_.end(), 0x00); + + // Read record data from memory. + const size_t kInputSize = sensor_->record_size; + size_t output_size = sensor_->record_size; + + if (IOConnectCallStructMethod(io_connection_, sensor_->function, + static_cast<const char *>(&input_record_[0]), kInputSize, + &output_record_[0], &output_size) != KERN_SUCCESS) { + return false; + } + + // Calculate per-axis calibrated values. + float axis_value[3]; + + for (int i = 0; i < 3; ++i) { + int sensor_value = 0; + int size = sensor_->axes[i].size; + int index = sensor_->axes[i].index; + + // Important Note: little endian is assumed as this code is mac-only + // and PowerPC is currently not supported. + memcpy(&sensor_value, &output_record_[index], size); + + sensor_value = ExtendSign(sensor_value, size); + + // Correct value using the current calibration. + axis_value[i] = static_cast<float>(sensor_value - sensor_->axes[i].zero_g) / + sensor_->axes[i].one_g; + + // Make sure we reject any NaN or infinite values. + if (!isfinite(axis_value[i])) + return false; + + // Clamp value to the [-1, 1] range. + if (axis_value[i] < -1.0) + axis_value[i] = -1.0; + else if (axis_value[i] > 1.0) + axis_value[i] = 1.0; + } + + // Transform the accelerometer values to W3C draft angles. + // + // Accelerometer values are just dot products of the sensor axes + // by the gravity vector 'g' with the result for the z axis inverted. + // + // To understand this transformation calculate the 3rd row of the z-x-y + // Euler angles rotation matrix (because of the 'g' vector, only 3rd row + // affects to the result). Note that z-x-y matrix means R = Ry * Rx * Rz. + // Then, assume alpha = 0 and you get this: + // + // x_acc = sin(gamma) + // y_acc = - cos(gamma) * sin(beta) + // z_acc = cos(beta) * cos(gamma) + // + // After that the rest is just a bit of trigonometry. + // + // Also note that alpha can't be provided but it's assumed to be always zero. + // This is necessary in order to provide enough information to solve + // the equations. + // + const double kRad2deg = 180.0 / M_PI; + + orientation->alpha_ = 0.0; + orientation->beta_ = kRad2deg * atan2(-axis_value[1], axis_value[2]); + orientation->gamma_ = kRad2deg * asin(axis_value[0]); + + // Make sure that the interval boundaries comply with the specification. + if (orientation->beta_ >= 180.0) + orientation->beta_ -= 360.0; + if (orientation->gamma_ >= 90.0) + orientation->gamma_ -= 180.0; + + DCHECK_GE(orientation->beta_, -180.0); + DCHECK_LT(orientation->beta_, 180.0); + DCHECK_GE(orientation->gamma_, -90.0); + DCHECK_LT(orientation->gamma_, 90.0); + + orientation->can_provide_alpha_ = false; + orientation->can_provide_beta_ = true; + orientation->can_provide_gamma_ = true; + + return true; +} + +// Probe the local hardware looking for a supported sensor device +// and initialize an I/O connection to it. +bool AccelerometerMac::Init() { + // Allocate local variables for model name string (size from SMSLib). + static const int kNameSize = 32; + char local_model[kNameSize]; + + // Request model name to the kernel. + size_t name_size = kNameSize; + int params[2] = { CTL_HW, HW_MODEL }; + if (sysctl(params, 2, local_model, &name_size, NULL, 0) != 0) + return NULL; + + const SensorDescriptor* sensor_candidate = NULL; + + // Look for the current model in the supported sensor list. + io_object_t device = 0; + const int kNumSensors = arraysize(kSupportedSensors); + + for (int i = 0; i < kNumSensors; ++i) { + // Check if the supported sensor model name is a prefix + // of the local hardware model (empty names are accepted). + const char* p1 = kSupportedSensors[i].model_name; + for (const char* p2 = local_model; *p1 != '\0' && *p1 == *p2; ++p1, ++p2) + continue; + if (*p1 != '\0') + continue; + + // Local hardware found in the supported sensor list. + sensor_candidate = &kSupportedSensors[i]; + + // Get a dictionary of the services matching to the one in the sensor. + CFMutableDictionaryRef dict = + IOServiceMatching(sensor_candidate->service_name); + if (dict == NULL) + continue; + + // Get an iterator for the matching services. + io_iterator_t device_iterator; + if (IOServiceGetMatchingServices(kIOMasterPortDefault, dict, + &device_iterator) != KERN_SUCCESS) { + continue; + } + + // Get the first device in the list. + if ((device = IOIteratorNext(device_iterator)) == 0) + continue; + + // Try to open device. + kern_return_t result; + result = IOServiceOpen(device, mach_task_self(), 0, &io_connection_); + IOObjectRelease(device); + if (result != KERN_SUCCESS || io_connection_ == 0) + return false; + + // Local sensor service confirmed by IOKit. + sensor_ = sensor_candidate; + break; + } + + if (sensor_ == NULL) + return false; + + // Allocate and initialize input/output records. + input_record_.resize(sensor_->record_size, 0x01); + output_record_.resize(sensor_->record_size, 0x00); + + // Try to retrieve the current orientation. + Orientation test_orientation; + return GetOrientation(&test_orientation); +} + +// Extend the sign of an integer of less than 32 bits to a 32-bit integer. +int AccelerometerMac::ExtendSign(int value, size_t size) { + switch (size) { + case 1: + if (value & 0x00000080) + return value | 0xffffff00; + break; + + case 2: + if (value & 0x00008000) + return value | 0xffff0000; + break; + + case 3: + if (value & 0x00800000) + return value | 0xff000000; + break; + + default: + LOG(FATAL) << "Invalid integer size for sign extension: " << size; + } + + return value; +} + +} // namespace device_orientation diff --git a/chrome/browser/device_orientation/accelerometer_mac.h b/chrome/browser/device_orientation/accelerometer_mac.h new file mode 100644 index 0000000..873ff79 --- /dev/null +++ b/chrome/browser/device_orientation/accelerometer_mac.h @@ -0,0 +1,102 @@ +// Copyright (c) 2010 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. +// +// This file is based on the SMSLib library. +// +// SMSLib Sudden Motion Sensor Access Library +// Copyright (c) 2010 Suitable Systems +// All rights reserved. +// +// Developed by: Daniel Griscom +// Suitable Systems +// http://www.suitable.com +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal with the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimers. +// +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimers in the +// documentation and/or other materials provided with the distribution. +// +// - Neither the names of Suitable Systems nor the names of its +// contributors may be used to endorse or promote products derived from +// this Software without specific prior written permission. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR +// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +// SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE. +// +// For more information about SMSLib, see +// <http://www.suitable.com/tools/smslib.html> +// or contact +// Daniel Griscom +// Suitable Systems +// 1 Centre Street, Suite 204 +// Wakefield, MA 01880 +// (781) 665-0053 + +#ifndef CHROME_BROWSER_DEVICE_ORIENTATION_ACCELEROMETER_MAC_H_ +#define CHROME_BROWSER_DEVICE_ORIENTATION_ACCELEROMETER_MAC_H_ +#pragma once + +#include <vector> + +#include <IOKit/IOKitLib.h> + +#include "chrome/browser/device_orientation/data_fetcher.h" + +namespace device_orientation { + +// Provides an easy-to-use interface to retrieve data +// from the MacBook family accelerometer. +class AccelerometerMac : public DataFetcher { + public: + static DataFetcher* Create(); + + // Implement DataFetcher. + virtual bool GetOrientation(Orientation* orientation); + + virtual ~AccelerometerMac(); + + private: + AccelerometerMac(); + bool Init(); + + // Extend the sign of an integer of size bytes to a 32-bit one. + static int ExtendSign(int value, size_t size); + + struct SensorDescriptor; + struct AxisData; + + // List of supported sensors. + static const SensorDescriptor kSupportedSensors[]; + + // Local sensor if supported, else NULL. + const SensorDescriptor* sensor_; + + // IOKit connection to the local sensor. + io_connect_t io_connection_; + + // Input memory used for sensor I/O. + std::vector<char> input_record_; + + // Output memory used for sensor I/O. + std::vector<char> output_record_; +}; + +} // namespace device_orientation + +#endif // CHROME_BROWSER_DEVICE_ORIENTATION_ACCELEROMETER_MAC_H_ diff --git a/chrome/browser/device_orientation/provider.cc b/chrome/browser/device_orientation/provider.cc index d1d335b..0785acf 100644 --- a/chrome/browser/device_orientation/provider.cc +++ b/chrome/browser/device_orientation/provider.cc @@ -6,6 +6,11 @@ #include "base/logging.h" #include "chrome/browser/chrome_thread.h" + +#if defined(OS_MACOSX) +#include "chrome/browser/device_orientation/accelerometer_mac.h" +#endif + #include "chrome/browser/device_orientation/data_fetcher.h" #include "chrome/browser/device_orientation/provider_impl.h" @@ -14,7 +19,12 @@ namespace device_orientation { Provider* Provider::GetInstance() { if (!instance_) { DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); - const ProviderImpl::DataFetcherFactory default_factories[] = { NULL }; + const ProviderImpl::DataFetcherFactory default_factories[] = { +#if defined(OS_MACOSX) + AccelerometerMac::Create, +#endif + NULL + }; instance_ = new ProviderImpl(MessageLoop::current(), default_factories); } |