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

Side by Side Diff: chrome/browser/device_orientation/accelerometer_mac.cc

Issue 3187025: Adding MacBook Pro accelerometer support. (Closed)
Patch Set: Created 10 years, 4 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 unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright (c) 2010 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.
4 //
5 // This file is based on the SMSLib library.
6 //
7 // SMSLib Sudden Motion Sensor Access Library
8 // Copyright (c) 2010 Suitable Systems
9 // All rights reserved.
10 //
11 // Developed by: Daniel Griscom
12 // Suitable Systems
13 // http://www.suitable.com
14 //
15 // Permission is hereby granted, free of charge, to any person obtaining a
16 // copy of this software and associated documentation files (the
17 // "Software"), to deal with the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
22 //
23 // - Redistributions of source code must retain the above copyright notice,
24 // this list of conditions and the following disclaimers.
25 //
26 // - Redistributions in binary form must reproduce the above copyright
27 // notice, this list of conditions and the following disclaimers in the
28 // documentation and/or other materials provided with the distribution.
29 //
30 // - Neither the names of Suitable Systems nor the names of its
31 // contributors may be used to endorse or promote products derived from
32 // this Software without specific prior written permission.
33 //
34 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
35 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
36 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
37 // IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR
38 // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
39 // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
40 // SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE.
41 //
42 // For more information about SMSLib, see
43 // <http://www.suitable.com/tools/smslib.html>
44 // or contact
45 // Daniel Griscom
46 // Suitable Systems
47 // 1 Centre Street, Suite 204
48 // Wakefield, MA 01880
49 // (781) 665-0053
50
51 #include "chrome/browser/device_orientation/accelerometer_mac.h"
52
53 #include <math.h> // For isfinite.
54 #include <sys/sysctl.h>
55
56 #include "base/logging.h"
57 #include "base/scoped_ptr.h"
58 #include "chrome/browser/device_orientation/orientation.h"
59
60 namespace device_orientation {
61
62 // Per-axis sensor data.
63 struct AccelerometerMac::AxisData {
64 // Non-zero if the axis is valid in this sensor.
65 int enabled;
66
67 // Location in struct of first byte.
68 int index;
69
70 // Number of bytes of the axis data.
71 int size;
72
73 // Value meaning "zero g".
74 float zero_g;
75
76 // (can be negative if the sensor axis is reversed).
77 float one_g;
78 };
79
80 // Sudden Motion Sensor descriptor.
81 struct AccelerometerMac::SensorDescriptor {
82 // Prefix of model to be tested.
83 const char* model_name;
84
85 // Name of device to be read.
86 const char* service_name;
87
88 // Kernel function index.
89 unsigned int function;
90
91 // Size of record to be sent/received.
92 unsigned int record_size;
93
94 // Description of three axes (x,y,z).
95 AxisData axes[3];
96 };
97
98 // Supported sensor descriptors. Add entries here to enhance compatibility.
99 // All non-tested entries from SMSLib have been removed.
100 const AccelerometerMac::SensorDescriptor
101 AccelerometerMac::kSupportedSensors[] = {
102 // Tested by leandrogracia on a 15'' MacBook Pro.
103 { "MacBookPro5,4", "SMCMotionSensor", 5, 40, {
104 { 1, 0, 2, 0, 251 },
105 { 1, 2, 2, 0, 251 },
106 { 1, 4, 2, 0, 251 }
107 } },
108
109 // Tested by leandrogracia on a 13'' MacBook Pro.
110 { "MacBookPro5,5", "SMCMotionSensor", 5, 40, {
111 { 1, 0, 2, 0, -251 },
112 { 1, 2, 2, 0, -251 },
113 { 1, 4, 2, 0, 251 }
114 } },
115
116 // Generic MacBook accelerometer sensor data.
117 // Added for forward compatibility (there may be problems with inverted axes).
118 {"", "SMCMotionSensor", 5, 40, {
119 { 1, 0, 2, 0, -251 },
120 { 1, 2, 2, 0, -251 },
121 { 1, 4, 2, 0, 251 }
122 } }
123 };
124
125 // Create a AccelerometerMac object and return NULL if no valid sensor found.
126 DataFetcher* AccelerometerMac::Create() {
127 scoped_ptr<AccelerometerMac> accelerometer(new AccelerometerMac);
128 return accelerometer->Init() ? accelerometer.release() : NULL;
129 }
130
131 AccelerometerMac::~AccelerometerMac() {
132 IOServiceClose(io_connection_);
133 }
134
135 AccelerometerMac::AccelerometerMac()
136 : sensor_(NULL),
137 io_connection_(0) {
138 }
139
140 // Retrieve per-axis accelerometer values.
141 //
142 // Axes and angles are defined according to the W3C DeviceOrientation Draft.
143 // See here: http://dev.w3.org/geo/api/spec-source-orientation.html
144 //
145 // Note: only beta and gamma angles are provided. Alpha is set to zero.
146 //
147 // Returns false in case of error or non-properly initialized object.
148 //
149 bool AccelerometerMac::GetOrientation(Orientation* orientation) {
150 DCHECK(sensor_);
151
152 // Reset output record memory buffer.
153 std::fill(output_record_.begin(), output_record_.end(), 0x00);
154
155 // Read record data from memory.
156 const size_t kInputSize = sensor_->record_size;
157 size_t output_size = sensor_->record_size;
158
159 if (IOConnectCallStructMethod(io_connection_, sensor_->function,
160 static_cast<const char *>(&input_record_[0]), kInputSize,
161 &output_record_[0], &output_size) != KERN_SUCCESS) {
162 return false;
163 }
164
165 // Calculate per-axis calibrated values.
166 float axis_value[3];
167
168 for (int i = 0; i < 3; ++i) {
169 int sensor_value = 0;
170 int size = sensor_->axes[i].size;
171 int index = sensor_->axes[i].index;
172
173 // Important Note: little endian is assumed as this code is mac-only
174 // and PowerPC is currently not supported.
175 memcpy(&sensor_value, &output_record_[index], size);
176
177 sensor_value = ExtendSign(sensor_value, size);
178
179 // Correct value using the current calibration.
180 axis_value[i] = static_cast<float>(sensor_value - sensor_->axes[i].zero_g) /
181 sensor_->axes[i].one_g;
182
183 // Make sure we reject any NaN or infinite values.
184 if (!isfinite(axis_value[i]))
185 return false;
186
187 // Clamp value to the [-1, 1] range.
188 if (axis_value[i] < -1.0)
189 axis_value[i] = -1.0;
190 else if (axis_value[i] > 1.0)
191 axis_value[i] = 1.0;
192 }
193
194 // Transform the accelerometer values to W3C draft angles.
195 //
196 // Accelerometer values are just dot products of the sensor axes
197 // by the gravity vector 'g' with the result for the z axis inverted.
198 //
199 // To understand this transformation calculate the 3rd row of the z-x-y
200 // Euler angles rotation matrix (because of the 'g' vector, only 3rd row
201 // affects to the result). Note that z-x-y matrix means R = Ry * Rx * Rz.
202 // Then, assume alpha = 0 and you get this:
203 //
204 // x_acc = sin(gamma)
205 // y_acc = - cos(gamma) * sin(beta)
206 // z_acc = cos(beta) * cos(gamma)
207 //
208 // After that the rest is just a bit of trigonometry.
209 //
210 // Also note that alpha can't be provided but it's assumed to be always zero.
211 // This is necessary in order to provide enough information to solve
212 // the equations.
213 //
214 const double kRad2deg = 180.0 / M_PI;
215
216 orientation->alpha_ = 0.0;
217 orientation->beta_ = kRad2deg * atan2(-axis_value[1], axis_value[2]);
218 orientation->gamma_ = kRad2deg * asin(axis_value[0]);
219
220 // Make sure that the interval boundaries comply with the specification.
221 if (orientation->beta_ >= 180.0)
222 orientation->beta_ -= 360.0;
223 if (orientation->gamma_ >= 90.0)
224 orientation->gamma_ -= 180.0;
225
226 DCHECK_GE(orientation->beta_, -180.0);
227 DCHECK_LT(orientation->beta_, 180.0);
228 DCHECK_GE(orientation->gamma_, -90.0);
229 DCHECK_LT(orientation->gamma_, 90.0);
230
231 orientation->can_provide_alpha_ = false;
232 orientation->can_provide_beta_ = true;
233 orientation->can_provide_gamma_ = true;
234
235 return true;
236 }
237
238 // Probe the local hardware looking for a supported sensor device
239 // and initialize an I/O connection to it.
240 bool AccelerometerMac::Init() {
241 // Allocate local variables for model name string (size from SMSLib).
242 static const int kNameSize = 32;
243 char local_model[kNameSize];
244
245 // Request model name to the kernel.
246 size_t name_size = kNameSize;
247 int params[2] = { CTL_HW, HW_MODEL };
248 if (sysctl(params, 2, local_model, &name_size, NULL, 0) != 0)
249 return NULL;
250
251 const SensorDescriptor* sensor_candidate = NULL;
252
253 // Look for the current model in the supported sensor list.
254 io_object_t device = 0;
255 const int kNumSensors = arraysize(kSupportedSensors);
256
257 for (int i = 0; i < kNumSensors; ++i) {
258 // Check if the supported sensor model name is a prefix
259 // of the local hardware model (empty names are accepted).
260 const char* p1 = kSupportedSensors[i].model_name;
261 for (const char* p2 = local_model; *p1 != '\0' && *p1 == *p2; ++p1, ++p2)
262 continue;
263 if (*p1 != '\0')
264 continue;
265
266 // Local hardware found in the supported sensor list.
267 sensor_candidate = &kSupportedSensors[i];
268
269 // Get a dictionary of the services matching to the one in the sensor.
270 CFMutableDictionaryRef dict =
271 IOServiceMatching(sensor_candidate->service_name);
272 if (dict == NULL)
273 continue;
274
275 // Get an iterator for the matching services.
276 io_iterator_t device_iterator;
277 if (IOServiceGetMatchingServices(kIOMasterPortDefault, dict,
278 &device_iterator) != KERN_SUCCESS) {
279 continue;
280 }
281
282 // Get the first device in the list.
283 if ((device = IOIteratorNext(device_iterator)) == 0)
284 continue;
285
286 // Try to open device.
287 kern_return_t result;
288 result = IOServiceOpen(device, mach_task_self(), 0, &io_connection_);
289 IOObjectRelease(device);
290 if (result != KERN_SUCCESS || io_connection_ == 0)
291 return false;
292
293 // Local sensor service confirmed by IOKit.
294 sensor_ = sensor_candidate;
295 break;
296 }
297
298 if (sensor_ == NULL)
299 return false;
300
301 // Allocate and initialize input/output records.
302 input_record_.resize(sensor_->record_size, 0x01);
303 output_record_.resize(sensor_->record_size, 0x00);
304
305 // Try to retrieve the current orientation.
306 Orientation test_orientation;
307 return GetOrientation(&test_orientation);
308 }
309
310 // Extend the sign of an integer of less than 32 bits to a 32-bit integer.
311 int AccelerometerMac::ExtendSign(int value, size_t size) {
312 switch (size) {
313 case 1:
314 if (value & 0x00000080)
315 return value | 0xffffff00;
316 break;
317
318 case 2:
319 if (value & 0x00008000)
320 return value | 0xffff0000;
321 break;
322
323 case 3:
324 if (value & 0x00800000)
325 return value | 0xff000000;
326 break;
327
328 default:
329 LOG(FATAL) << "Invalid integer size for sign extension: " << size;
330 }
331
332 return value;
333 }
334
335 } // namespace device_orientation
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698