blob: 62d3e6af77977069cf3457d6eb5d9d42fa8997f0 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.content.Context;
20import android.hardware.Sensor;
21import android.hardware.SensorEvent;
22import android.hardware.SensorEventListener;
23import android.hardware.SensorManager;
24import android.util.Config;
25import android.util.Log;
Jeff Brown4519f072011-01-23 13:16:01 -080026import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027
28/**
29 * A special helper class used by the WindowManager
30 * for receiving notifications from the SensorManager when
31 * the orientation of the device has changed.
Dianne Hackborne5439f22010-10-02 16:53:50 -070032 *
33 * NOTE: If changing anything here, please run the API demo
34 * "App/Activity/Screen Orientation" to ensure that all orientation
35 * modes still work correctly.
36 *
Jeff Brown4519f072011-01-23 13:16:01 -080037 * You can also visualize the behavior of the WindowOrientationListener by
38 * enabling the window orientation listener log using the Development Settings
39 * in the Dev Tools application (Development.apk)
40 * and running frameworks/base/tools/orientationplot/orientationplot.py.
41 *
42 * More information about how to tune this algorithm in
43 * frameworks/base/tools/orientationplot/README.txt.
44 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045 * @hide
46 */
47public abstract class WindowOrientationListener {
48 private static final String TAG = "WindowOrientationListener";
Suchi Amalapurapud9328512010-01-04 16:18:06 -080049 private static final boolean DEBUG = false;
Suchi Amalapurapu63104ed2009-12-15 14:06:08 -080050 private static final boolean localLOGV = DEBUG || Config.DEBUG;
Jeff Brown4519f072011-01-23 13:16:01 -080051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052 private SensorManager mSensorManager;
Jeff Brown4519f072011-01-23 13:16:01 -080053 private boolean mEnabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054 private int mRate;
55 private Sensor mSensor;
Suchi Amalapurapu63104ed2009-12-15 14:06:08 -080056 private SensorEventListenerImpl mSensorEventListener;
Jeff Brown4519f072011-01-23 13:16:01 -080057 boolean mLogEnabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058
59 /**
60 * Creates a new WindowOrientationListener.
61 *
62 * @param context for the WindowOrientationListener.
63 */
64 public WindowOrientationListener(Context context) {
Jeff Brown4519f072011-01-23 13:16:01 -080065 this(context, SensorManager.SENSOR_DELAY_UI);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 }
67
68 /**
69 * Creates a new WindowOrientationListener.
70 *
71 * @param context for the WindowOrientationListener.
72 * @param rate at which sensor events are processed (see also
73 * {@link android.hardware.SensorManager SensorManager}). Use the default
74 * value of {@link android.hardware.SensorManager#SENSOR_DELAY_NORMAL
75 * SENSOR_DELAY_NORMAL} for simple screen orientation change detection.
Steve Howard1ba101f2010-02-23 14:30:13 -080076 *
Jeff Brown4519f072011-01-23 13:16:01 -080077 * This constructor is private since no one uses it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 */
Steve Howard1ba101f2010-02-23 14:30:13 -080079 private WindowOrientationListener(Context context, int rate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
81 mRate = rate;
82 mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
83 if (mSensor != null) {
84 // Create listener only if sensors do exist
Steve Howard5f531ae2010-08-05 17:14:53 -070085 mSensorEventListener = new SensorEventListenerImpl(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 }
87 }
88
89 /**
90 * Enables the WindowOrientationListener so it will monitor the sensor and call
91 * {@link #onOrientationChanged} when the device orientation changes.
92 */
93 public void enable() {
94 if (mSensor == null) {
95 Log.w(TAG, "Cannot detect sensors. Not enabled");
96 return;
97 }
98 if (mEnabled == false) {
99 if (localLOGV) Log.d(TAG, "WindowOrientationListener enabled");
100 mSensorManager.registerListener(mSensorEventListener, mSensor, mRate);
101 mEnabled = true;
102 }
103 }
104
105 /**
106 * Disables the WindowOrientationListener.
107 */
108 public void disable() {
109 if (mSensor == null) {
110 Log.w(TAG, "Cannot detect sensors. Invalid disable");
111 return;
112 }
113 if (mEnabled == true) {
114 if (localLOGV) Log.d(TAG, "WindowOrientationListener disabled");
115 mSensorManager.unregisterListener(mSensorEventListener);
116 mEnabled = false;
117 }
118 }
119
Jeff Brown4519f072011-01-23 13:16:01 -0800120 /**
121 * Gets the current orientation.
122 * @param lastRotation
123 * @return
124 */
Steve Howard5eb49582010-08-16 11:41:58 -0700125 public int getCurrentRotation(int lastRotation) {
Suchi Amalapurapu63104ed2009-12-15 14:06:08 -0800126 if (mEnabled) {
Steve Howard5eb49582010-08-16 11:41:58 -0700127 return mSensorEventListener.getCurrentRotation(lastRotation);
Suchi Amalapurapu63104ed2009-12-15 14:06:08 -0800128 }
Steve Howard5eb49582010-08-16 11:41:58 -0700129 return lastRotation;
Dianne Hackborne4fbd622009-03-27 18:09:16 -0700130 }
Steve Howard5f531ae2010-08-05 17:14:53 -0700131
132 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 * Returns true if sensor is enabled and false otherwise
134 */
135 public boolean canDetectOrientation() {
136 return mSensor != null;
137 }
Steve Howard1ba101f2010-02-23 14:30:13 -0800138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 /**
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -0700140 * Called when the rotation view of the device has changed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 *
Steve Howard1ba101f2010-02-23 14:30:13 -0800142 * @param rotation The new orientation of the device, one of the Surface.ROTATION_* constants.
143 * @see Surface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 */
Jeff Brown4519f072011-01-23 13:16:01 -0800145 public abstract void onOrientationChanged(int rotation);
146
147 /**
148 * Enables or disables the window orientation listener logging for use with
149 * the orientationplot.py tool.
150 * Logging is usually enabled via Development Settings. (See class comments.)
151 * @param enable True to enable logging.
152 */
153 public void setLogEnabled(boolean enable) {
154 mLogEnabled = enable;
155 }
156
157 /**
158 * This class filters the raw accelerometer data and tries to detect actual changes in
159 * orientation. This is a very ill-defined problem so there are a lot of tweakable parameters,
160 * but here's the outline:
161 *
162 * - Low-pass filter the accelerometer vector in cartesian coordinates. We do it in
163 * cartesian space because the orientation calculations are sensitive to the
164 * absolute magnitude of the acceleration. In particular, there are singularities
165 * in the calculation as the magnitude approaches 0. By performing the low-pass
166 * filtering early, we can eliminate high-frequency impulses systematically.
167 *
168 * - Convert the acceleromter vector from cartesian to spherical coordinates.
169 * Since we're dealing with rotation of the device, this is the sensible coordinate
170 * system to work in. The zenith direction is the Z-axis, the direction the screen
171 * is facing. The radial distance is referred to as the magnitude below.
172 * The elevation angle is referred to as the "tilt" below.
173 * The azimuth angle is referred to as the "orientation" below (and the azimuth axis is
174 * the Y-axis).
175 * See http://en.wikipedia.org/wiki/Spherical_coordinate_system for reference.
176 *
177 * - If the tilt angle is too close to horizontal (near 90 or -90 degrees), do nothing.
178 * The orientation angle is not meaningful when the device is nearly horizontal.
179 * The tilt angle thresholds are set differently for each orientation and different
180 * limits are applied when the device is facing down as opposed to when it is facing
181 * forward or facing up.
182 *
183 * - When the orientation angle reaches a certain threshold, consider transitioning
184 * to the corresponding orientation. These thresholds have some hysteresis built-in
185 * to avoid oscillations between adjacent orientations.
186 *
187 * - Use the magnitude to judge the confidence of the orientation.
188 * Under ideal conditions, the magnitude should equal to that of gravity. When it
189 * differs significantly, we know the device is under external acceleration and
190 * we can't trust the data.
191 *
192 * - Use the tilt angle to judge the confidence of the orientation.
193 * When the tilt angle is high in absolute value then the device is nearly flat
194 * so small physical movements produce large changes in orientation angle.
195 * This can be the case when the device is being picked up from a table.
196 *
197 * - Use the orientation angle to judge the confidence of the orientation.
198 * The close the orientation angle is to the canonical orientation angle, the better.
199 *
200 * - Based on the aggregate confidence, we determine how long we want to wait for
201 * the new orientation to settle. This is accomplished by integrating the confidence
202 * for each orientation over time. When a threshold integration sum is reached
203 * then we actually change orientations.
204 *
205 * Details are explained inline.
206 */
207 static final class SensorEventListenerImpl implements SensorEventListener {
208 // We work with all angles in degrees in this class.
209 private static final float RADIANS_TO_DEGREES = (float) (180 / Math.PI);
210
211 // Indices into SensorEvent.values for the accelerometer sensor.
212 private static final int ACCELEROMETER_DATA_X = 0;
213 private static final int ACCELEROMETER_DATA_Y = 1;
214 private static final int ACCELEROMETER_DATA_Z = 2;
215
216 // Rotation constants.
217 // These are the same as Surface rotation constants with the addition of a 5th
218 // unknown state when we are not confident about the proporsed orientation.
219 // One important property of these constants is that they are equal to the
220 // orientation angle itself divided by 90. We use this fact to map
221 // back and forth between orientation angles and rotation values.
222 private static final int ROTATION_UNKNOWN = -1;
223 //private static final int ROTATION_0 = Surface.ROTATION_0; // 0
224 //private static final int ROTATION_90 = Surface.ROTATION_90; // 1
225 //private static final int ROTATION_180 = Surface.ROTATION_180; // 2
226 //private static final int ROTATION_270 = Surface.ROTATION_270; // 3
227
228 private final WindowOrientationListener mOrientationListener;
229
230 private int mRotation = ROTATION_UNKNOWN;
231
232 /* State for first order low-pass filtering of accelerometer data.
233 * See http://en.wikipedia.org/wiki/Low-pass_filter#Discrete-time_realization for
234 * signal processing background.
235 */
236
237 private long mLastTimestamp = Long.MAX_VALUE; // in nanoseconds
238 private float mLastFilteredX, mLastFilteredY, mLastFilteredZ;
239
240 // The maximum sample inter-arrival time in milliseconds.
241 // If the acceleration samples are further apart than this amount in time, we reset the
242 // state of the low-pass filter and orientation properties. This helps to handle
243 // boundary conditions when the device is turned on, wakes from suspend or there is
244 // a significant gap in samples.
245 private static final float MAX_FILTER_DELTA_TIME_MS = 1000;
246
247 // The acceleration filter cutoff frequency.
248 // This is the frequency at which signals are attenuated by 3dB (half the passband power).
249 // Each successive octave beyond this frequency is attenuated by an additional 6dB.
250 //
251 // We choose the cutoff frequency such that impulses and vibrational noise
252 // (think car dock) is suppressed. However, this filtering does not eliminate
253 // all possible sources of orientation ambiguity so we also rely on a dynamic
254 // settle time for establishing a new orientation. Filtering adds latency
255 // inversely proportional to the cutoff frequency so we don't want to make
256 // it too small or we can lose hundreds of milliseconds of responsiveness.
257 private static final float FILTER_CUTOFF_FREQUENCY_HZ = 1f;
258 private static final float FILTER_TIME_CONSTANT_MS = (float)(500.0f
259 / (Math.PI * FILTER_CUTOFF_FREQUENCY_HZ)); // t = 1 / (2pi * Fc) * 1000ms
260
261 // The filter gain.
262 // We choose a value slightly less than unity to avoid numerical instabilities due
263 // to floating-point error accumulation.
264 private static final float FILTER_GAIN = 0.999f;
265
266 /* State for orientation detection. */
267
268 // Thresholds for minimum and maximum allowable deviation from gravity.
269 //
270 // If the device is undergoing external acceleration (being bumped, in a car
271 // that is turning around a corner or a plane taking off) then the magnitude
272 // may be substantially more or less than gravity. This can skew our orientation
273 // detection by making us think that up is pointed in a different direction.
274 //
275 // Conversely, if the device is in freefall, then there will be no gravity to
276 // measure at all. This is problematic because we cannot detect the orientation
277 // without gravity to tell us which way is up. A magnitude near 0 produces
278 // singularities in the tilt and orientation calculations.
279 //
280 // In both cases, we postpone choosing an orientation.
281 private static final float MIN_ACCELERATION_MAGNITUDE =
282 SensorManager.STANDARD_GRAVITY * 0.5f;
283 private static final float MAX_ACCELERATION_MAGNITUDE =
284 SensorManager.STANDARD_GRAVITY * 1.5f;
285
286 // Maximum absolute tilt angle at which to consider orientation data. Beyond this (i.e.
287 // when screen is facing the sky or ground), we completely ignore orientation data.
288 private static final int MAX_TILT = 75;
289
290 // The tilt angle range in degrees for each orientation.
291 // Beyond these tilt angles, we don't even consider transitioning into the
292 // specified orientation. We place more stringent requirements on unnatural
293 // orientations than natural ones to make it less likely to accidentally transition
294 // into those states.
295 // The first value of each pair is negative so it applies a limit when the device is
296 // facing down (overhead reading in bed).
297 // The second value of each pair is positive so it applies a limit when the device is
298 // facing up (resting on a table).
299 // The ideal tilt angle is 0 (when the device is vertical) so the limits establish
300 // how close to vertical the device must be in order to change orientation.
301 private static final int[][] TILT_TOLERANCE = new int[][] {
302 /* ROTATION_0 */ { -20, 75 },
303 /* ROTATION_90 */ { -20, 70 },
304 /* ROTATION_180 */ { -20, 65 },
305 /* ROTATION_270 */ { -20, 70 }
306 };
307
308 // The gap angle in degrees between adjacent orientation angles for hysteresis.
309 // This creates a "dead zone" between the current orientation and a proposed
310 // adjacent orientation. No orientation proposal is made when the orientation
311 // angle is within the gap between the current orientation and the adjacent
312 // orientation.
313 private static final int ADJACENT_ORIENTATION_ANGLE_GAP = 30;
314
315 // The confidence scale factors for angle, tilt and magnitude.
316 // When the distance between the actual value and the ideal value is the
317 // specified delta, orientation transitions will take twice as long as they would
318 // in the ideal case. Increasing or decreasing the delta has an exponential effect
319 // on each factor's influence over the transition time.
320
321 // Transition takes 2x longer when angle is 30 degrees from ideal orientation angle.
322 private static final float ORIENTATION_ANGLE_CONFIDENCE_SCALE =
323 confidenceScaleFromDelta(30);
324
325 // Transition takes 2x longer when tilt is 45 degrees from vertical.
326 private static final float TILT_ANGLE_CONFIDENCE_SCALE = confidenceScaleFromDelta(45);
327
328 // Transition takes 2x longer when acceleration is 0.25 Gs.
329 private static final float MAGNITUDE_CONFIDENCE_SCALE = confidenceScaleFromDelta(
330 SensorManager.STANDARD_GRAVITY * 0.25f);
331
332 // The number of milliseconds for which a new orientation must be stable before
333 // we perform an orientation change under ideal conditions. It will take
334 // proportionally longer than this to effect an orientation change when
335 // the proposed orientation confidence is low.
336 private static final float ORIENTATION_SETTLE_TIME_MS = 250;
337
338 // The confidence that we have abount effecting each orientation change.
339 // When one of these values exceeds 1.0, we have determined our new orientation!
340 private float mConfidence[] = new float[4];
341
342 public SensorEventListenerImpl(WindowOrientationListener orientationListener) {
343 mOrientationListener = orientationListener;
344 }
345
346 public int getCurrentRotation(int lastRotation) {
347 return mRotation != ROTATION_UNKNOWN ? mRotation : lastRotation;
348 }
349
350 @Override
351 public void onAccuracyChanged(Sensor sensor, int accuracy) {
352 }
353
354 @Override
355 public void onSensorChanged(SensorEvent event) {
356 final boolean log = mOrientationListener.mLogEnabled;
357
358 // The vector given in the SensorEvent points straight up (towards the sky) under ideal
359 // conditions (the phone is not accelerating). I'll call this up vector elsewhere.
360 float x = event.values[ACCELEROMETER_DATA_X];
361 float y = event.values[ACCELEROMETER_DATA_Y];
362 float z = event.values[ACCELEROMETER_DATA_Z];
363
364 if (log) {
365 Slog.v(TAG, "Raw acceleration vector: " +
366 "x=" + x + ", y=" + y + ", z=" + z);
367 }
368
369 // Apply a low-pass filter to the acceleration up vector in cartesian space.
370 // Reset the orientation listener state if the samples are too far apart in time
371 // or when we see values of (0, 0, 0) which indicates that we polled the
372 // accelerometer too soon after turning it on and we don't have any data yet.
373 final float timeDeltaMS = (event.timestamp - mLastTimestamp) * 0.000001f;
374 boolean skipSample;
375 if (timeDeltaMS <= 0 || timeDeltaMS > MAX_FILTER_DELTA_TIME_MS
376 || (x == 0 && y == 0 && z == 0)) {
377 if (log) {
378 Slog.v(TAG, "Resetting orientation listener.");
379 }
380 for (int i = 0; i < 4; i++) {
381 mConfidence[i] = 0;
382 }
383 skipSample = true;
384 } else {
385 final float alpha = timeDeltaMS
386 / (FILTER_TIME_CONSTANT_MS + timeDeltaMS) * FILTER_GAIN;
387 x = alpha * (x - mLastFilteredX) + mLastFilteredX;
388 y = alpha * (y - mLastFilteredY) + mLastFilteredY;
389 z = alpha * (z - mLastFilteredZ) + mLastFilteredZ;
390 if (log) {
391 Slog.v(TAG, "Filtered acceleration vector: " +
392 "x=" + x + ", y=" + y + ", z=" + z);
393 }
394 skipSample = false;
395 }
396 mLastTimestamp = event.timestamp;
397 mLastFilteredX = x;
398 mLastFilteredY = y;
399 mLastFilteredZ = z;
400
401 boolean orientationChanged = false;
402 if (!skipSample) {
403 // Determine a proposed orientation based on the currently available data.
404 int proposedOrientation = ROTATION_UNKNOWN;
405 float combinedConfidence = 1.0f;
406
407 // Calculate the magnitude of the acceleration vector.
408 final float magnitude = (float) Math.sqrt(x * x + y * y + z * z);
409 if (magnitude < MIN_ACCELERATION_MAGNITUDE
410 || magnitude > MAX_ACCELERATION_MAGNITUDE) {
411 if (log) {
412 Slog.v(TAG, "Ignoring sensor data, magnitude out of range: "
413 + "magnitude=" + magnitude);
414 }
415 } else {
416 // Calculate the tilt angle.
417 // This is the angle between the up vector and the x-y plane (the plane of
418 // the screen) in a range of [-90, 90] degrees.
419 // -90 degrees: screen horizontal and facing the ground (overhead)
420 // 0 degrees: screen vertical
421 // 90 degrees: screen horizontal and facing the sky (on table)
422 final int tiltAngle = (int) Math.round(
423 Math.asin(z / magnitude) * RADIANS_TO_DEGREES);
424
425 // If the tilt angle is too close to horizontal then we cannot determine
426 // the orientation angle of the screen.
427 if (Math.abs(tiltAngle) > MAX_TILT) {
428 if (log) {
429 Slog.v(TAG, "Ignoring sensor data, tilt angle too high: "
430 + "magnitude=" + magnitude + ", tiltAngle=" + tiltAngle);
431 }
432 } else {
433 // Calculate the orientation angle.
434 // This is the angle between the x-y projection of the up vector onto
435 // the +y-axis, increasing clockwise in a range of [0, 360] degrees.
436 int orientationAngle = (int) Math.round(
437 -Math.atan2(-x, y) * RADIANS_TO_DEGREES);
438 if (orientationAngle < 0) {
439 // atan2 returns [-180, 180]; normalize to [0, 360]
440 orientationAngle += 360;
441 }
442
443 // Find the nearest orientation.
444 // An orientation of 0 can have a nearest angle of 0 or 360 depending
445 // on which is closer to the measured orientation angle. We leave the
446 // nearest angle at 360 in that case since it makes the delta calculation
447 // for orientation angle confidence easier below.
448 int nearestOrientation = (orientationAngle + 45) / 90;
449 int nearestOrientationAngle = nearestOrientation * 90;
450 if (nearestOrientation == 4) {
451 nearestOrientation = 0;
452 }
453
454 // Determine the proposed orientation.
455 // The confidence of the proposal is 1.0 when it is ideal and it
456 // decays exponentially as the proposal moves further from the ideal
457 // angle, tilt and magnitude of the proposed orientation.
458 if (isTiltAngleAcceptable(nearestOrientation, tiltAngle)
459 && isOrientationAngleAcceptable(nearestOrientation,
460 orientationAngle)) {
461 proposedOrientation = nearestOrientation;
462
463 final float idealOrientationAngle = nearestOrientationAngle;
464 final float orientationConfidence = confidence(orientationAngle,
465 idealOrientationAngle, ORIENTATION_ANGLE_CONFIDENCE_SCALE);
466
467 final float idealTiltAngle = 0;
468 final float tiltConfidence = confidence(tiltAngle,
469 idealTiltAngle, TILT_ANGLE_CONFIDENCE_SCALE);
470
471 final float idealMagnitude = SensorManager.STANDARD_GRAVITY;
472 final float magnitudeConfidence = confidence(magnitude,
473 idealMagnitude, MAGNITUDE_CONFIDENCE_SCALE);
474
475 combinedConfidence = orientationConfidence
476 * tiltConfidence * magnitudeConfidence;
477
478 if (log) {
479 Slog.v(TAG, "Proposal: "
480 + "magnitude=" + magnitude
481 + ", tiltAngle=" + tiltAngle
482 + ", orientationAngle=" + orientationAngle
483 + ", proposedOrientation=" + proposedOrientation
484 + ", combinedConfidence=" + combinedConfidence
485 + ", orientationConfidence=" + orientationConfidence
486 + ", tiltConfidence=" + tiltConfidence
487 + ", magnitudeConfidence=" + magnitudeConfidence);
488 }
489 } else {
490 if (log) {
491 Slog.v(TAG, "Ignoring sensor data, no proposal: "
492 + "magnitude=" + magnitude + ", tiltAngle=" + tiltAngle
493 + ", orientationAngle=" + orientationAngle);
494 }
495 }
496 }
497 }
498
499 // Sum up the orientation confidence weights.
500 // Detect an orientation change when the sum reaches 1.0.
501 final float confidenceAmount = combinedConfidence * timeDeltaMS
502 / ORIENTATION_SETTLE_TIME_MS;
503 for (int i = 0; i < 4; i++) {
504 if (i == proposedOrientation) {
505 mConfidence[i] += confidenceAmount;
506 if (mConfidence[i] >= 1.0f) {
507 mConfidence[i] = 1.0f;
508
509 if (i != mRotation) {
510 if (log) {
511 Slog.v(TAG, "Orientation changed! rotation=" + i);
512 }
513 mRotation = i;
514 orientationChanged = true;
515 }
516 }
517 } else {
518 mConfidence[i] -= confidenceAmount;
519 if (mConfidence[i] < 0.0f) {
520 mConfidence[i] = 0.0f;
521 }
522 }
523 }
524 }
525
526 // Write final statistics about where we are in the orientation detection process.
527 if (log) {
528 Slog.v(TAG, "Result: rotation=" + mRotation
529 + ", confidence=["
530 + mConfidence[0] + ", "
531 + mConfidence[1] + ", "
532 + mConfidence[2] + ", "
533 + mConfidence[3] + "], timeDeltaMS=" + timeDeltaMS);
534 }
535
536 // Tell the listener.
537 if (orientationChanged) {
538 mOrientationListener.onOrientationChanged(mRotation);
539 }
540 }
541
542 /**
543 * Returns true if the tilt angle is acceptable for a proposed
544 * orientation transition.
545 */
546 private boolean isTiltAngleAcceptable(int proposedOrientation,
547 int tiltAngle) {
548 return tiltAngle >= TILT_TOLERANCE[proposedOrientation][0]
549 && tiltAngle <= TILT_TOLERANCE[proposedOrientation][1];
550 }
551
552 /**
553 * Returns true if the orientation angle is acceptable for a proposed
554 * orientation transition.
555 * This function takes into account the gap between adjacent orientations
556 * for hysteresis.
557 */
558 private boolean isOrientationAngleAcceptable(int proposedOrientation,
559 int orientationAngle) {
560 final int currentOrientation = mRotation;
561
562 // If there is no current rotation, then there is no gap.
563 if (currentOrientation != ROTATION_UNKNOWN) {
564 // If the proposed orientation is the same or is counter-clockwise adjacent,
565 // then we set a lower bound on the orientation angle.
566 // For example, if currentOrientation is ROTATION_0 and proposed is ROTATION_90,
567 // then we want to check orientationAngle > 45 + GAP / 2.
568 if (proposedOrientation == currentOrientation
569 || proposedOrientation == (currentOrientation + 1) % 4) {
570 int lowerBound = proposedOrientation * 90 - 45
571 + ADJACENT_ORIENTATION_ANGLE_GAP / 2;
572 if (proposedOrientation == 0) {
573 if (orientationAngle >= 315 && orientationAngle < lowerBound + 360) {
574 return false;
575 }
576 } else {
577 if (orientationAngle < lowerBound) {
578 return false;
579 }
580 }
581 }
582
583 // If the proposed orientation is the same or is clockwise adjacent,
584 // then we set an upper bound on the orientation angle.
585 // For example, if currentOrientation is ROTATION_0 and proposed is ROTATION_270,
586 // then we want to check orientationAngle < 315 - GAP / 2.
587 if (proposedOrientation == currentOrientation
588 || proposedOrientation == (currentOrientation + 3) % 4) {
589 int upperBound = proposedOrientation * 90 + 45
590 - ADJACENT_ORIENTATION_ANGLE_GAP / 2;
591 if (proposedOrientation == 0) {
592 if (orientationAngle <= 45 && orientationAngle > upperBound) {
593 return false;
594 }
595 } else {
596 if (orientationAngle > upperBound) {
597 return false;
598 }
599 }
600 }
601 }
602 return true;
603 }
604
605 /**
606 * Calculate an exponentially weighted confidence value in the range [0.0, 1.0].
607 * The further the value is from the target, the more the confidence trends to 0.
608 */
609 private static float confidence(float value, float target, float scale) {
610 return (float) Math.exp(-Math.abs(value - target) * scale);
611 }
612
613 /**
614 * Calculate a scale factor for the confidence weight exponent.
615 * The scale value is chosen such that confidence(value, target, scale) == 0.5
616 * whenever abs(value - target) == cutoffDelta.
617 */
618 private static float confidenceScaleFromDelta(float cutoffDelta) {
619 return (float) -Math.log(0.5) / cutoffDelta;
620 }
621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622}