2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server;
19 import android.hardware.Sensor;
20 import android.hardware.SensorEvent;
21 import android.hardware.SensorEventListener;
22 import android.hardware.SensorManager;
23 import android.os.Handler;
24 import android.os.Message;
25 import android.os.PowerManager;
26 import android.os.SystemClock;
27 import android.util.Slog;
29 import java.lang.Float;
32 * Determines if the device has been set upon a stationary object.
34 public class AnyMotionDetector {
35 interface DeviceIdleCallback {
36 public void onAnyMotionResult(int result);
39 private static final String TAG = "AnyMotionDetector";
41 private static final boolean DEBUG = false;
43 /** Stationary status is unknown due to insufficient orientation measurements. */
44 public static final int RESULT_UNKNOWN = -1;
46 /** Device is stationary, e.g. still on a table. */
47 public static final int RESULT_STATIONARY = 0;
49 /** Device has been moved. */
50 public static final int RESULT_MOVED = 1;
52 /** Orientation measurements are being performed or are planned. */
53 private static final int STATE_INACTIVE = 0;
55 /** No orientation measurements are being performed or are planned. */
56 private static final int STATE_ACTIVE = 1;
58 /** Current measurement state. */
61 /** Threshold energy above which the device is considered moving. */
62 private final float THRESHOLD_ENERGY = 5f;
64 /** The duration of the accelerometer orientation measurement. */
65 private static final long ORIENTATION_MEASUREMENT_DURATION_MILLIS = 2500;
67 /** The maximum duration we will collect accelerometer data. */
68 private static final long ACCELEROMETER_DATA_TIMEOUT_MILLIS = 3000;
70 /** The interval between accelerometer orientation measurements. */
71 private static final long ORIENTATION_MEASUREMENT_INTERVAL_MILLIS = 5000;
74 * The duration in milliseconds after which an orientation measurement is considered
75 * too stale to be used.
77 private static final int STALE_MEASUREMENT_TIMEOUT_MILLIS = 2 * 60 * 1000;
79 /** The accelerometer sampling interval. */
80 private static final int SAMPLING_INTERVAL_MILLIS = 40;
82 private final Handler mHandler;
83 private final Object mLock = new Object();
84 private Sensor mAccelSensor;
85 private SensorManager mSensorManager;
86 private PowerManager.WakeLock mWakeLock;
88 /** Threshold angle in degrees beyond which the device is considered moving. */
89 private final float mThresholdAngle;
91 /** The minimum number of samples required to detect AnyMotion. */
92 private int mNumSufficientSamples;
94 /** True if an orientation measurement is in progress. */
95 private boolean mMeasurementInProgress;
97 /** The most recent gravity vector. */
98 private Vector3 mCurrentGravityVector = null;
100 /** The second most recent gravity vector. */
101 private Vector3 mPreviousGravityVector = null;
103 /** Running sum of squared errors. */
104 private RunningSignalStats mRunningStats;
106 private DeviceIdleCallback mCallback = null;
108 public AnyMotionDetector(PowerManager pm, Handler handler, SensorManager sm,
109 DeviceIdleCallback callback, float thresholdAngle) {
110 if (DEBUG) Slog.d(TAG, "AnyMotionDetector instantiated.");
111 synchronized (mLock) {
112 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
113 mWakeLock.setReferenceCounted(false);
116 mAccelSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
117 mMeasurementInProgress = false;
118 mState = STATE_INACTIVE;
119 mCallback = callback;
120 mThresholdAngle = thresholdAngle;
121 mRunningStats = new RunningSignalStats();
122 mNumSufficientSamples = (int) Math.ceil(
123 ((double)ORIENTATION_MEASUREMENT_DURATION_MILLIS / SAMPLING_INTERVAL_MILLIS));
124 if (DEBUG) Slog.d(TAG, "mNumSufficientSamples = " + mNumSufficientSamples);
129 * Acquire accel data until we determine AnyMotion status.
131 public void checkForAnyMotion() {
133 Slog.d(TAG, "checkForAnyMotion(). mState = " + mState);
135 if (mState != STATE_ACTIVE) {
136 synchronized (mLock) {
137 mState = STATE_ACTIVE;
139 Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_ACTIVE.");
141 mCurrentGravityVector = null;
142 mPreviousGravityVector = null;
144 startOrientationMeasurementLocked();
150 if (mState == STATE_ACTIVE) {
151 synchronized (mLock) {
152 mState = STATE_INACTIVE;
153 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE.");
154 if (mMeasurementInProgress) {
155 mMeasurementInProgress = false;
156 mSensorManager.unregisterListener(mListener);
158 mHandler.removeCallbacks(mMeasurementTimeout);
159 mHandler.removeCallbacks(mSensorRestart);
160 mCurrentGravityVector = null;
161 mPreviousGravityVector = null;
167 private void startOrientationMeasurementLocked() {
168 if (DEBUG) Slog.d(TAG, "startOrientationMeasurementLocked: mMeasurementInProgress=" +
169 mMeasurementInProgress + ", (mAccelSensor != null)=" + (mAccelSensor != null));
170 if (!mMeasurementInProgress && mAccelSensor != null) {
171 if (mSensorManager.registerListener(mListener, mAccelSensor,
172 SAMPLING_INTERVAL_MILLIS * 1000)) {
173 mMeasurementInProgress = true;
174 mRunningStats.reset();
176 Message msg = Message.obtain(mHandler, mMeasurementTimeout);
177 msg.setAsynchronous(true);
178 mHandler.sendMessageDelayed(msg, ACCELEROMETER_DATA_TIMEOUT_MILLIS);
182 private int stopOrientationMeasurementLocked() {
183 if (DEBUG) Slog.d(TAG, "stopOrientationMeasurement. mMeasurementInProgress=" +
184 mMeasurementInProgress);
185 int status = RESULT_UNKNOWN;
186 if (mMeasurementInProgress) {
187 mSensorManager.unregisterListener(mListener);
188 mHandler.removeCallbacks(mMeasurementTimeout);
189 long detectionEndTime = SystemClock.elapsedRealtime();
190 mMeasurementInProgress = false;
191 mPreviousGravityVector = mCurrentGravityVector;
192 mCurrentGravityVector = mRunningStats.getRunningAverage();
194 Slog.d(TAG, "mRunningStats = " + mRunningStats.toString());
195 String currentGravityVectorString = (mCurrentGravityVector == null) ?
196 "null" : mCurrentGravityVector.toString();
197 String previousGravityVectorString = (mPreviousGravityVector == null) ?
198 "null" : mPreviousGravityVector.toString();
199 Slog.d(TAG, "mCurrentGravityVector = " + currentGravityVectorString);
200 Slog.d(TAG, "mPreviousGravityVector = " + previousGravityVectorString);
202 mRunningStats.reset();
203 status = getStationaryStatus();
204 if (DEBUG) Slog.d(TAG, "getStationaryStatus() returned " + status);
205 if (status != RESULT_UNKNOWN) {
208 Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE. status = " + status);
210 mState = STATE_INACTIVE;
213 * Unknown due to insufficient measurements. Schedule another orientation
216 if (DEBUG) Slog.d(TAG, "stopOrientationMeasurementLocked(): another measurement" +
217 " scheduled in " + ORIENTATION_MEASUREMENT_INTERVAL_MILLIS +
219 Message msg = Message.obtain(mHandler, mSensorRestart);
220 msg.setAsynchronous(true);
221 mHandler.sendMessageDelayed(msg, ORIENTATION_MEASUREMENT_INTERVAL_MILLIS);
228 * Updates mStatus to the current AnyMotion status.
230 public int getStationaryStatus() {
231 if ((mPreviousGravityVector == null) || (mCurrentGravityVector == null)) {
232 return RESULT_UNKNOWN;
234 Vector3 previousGravityVectorNormalized = mPreviousGravityVector.normalized();
235 Vector3 currentGravityVectorNormalized = mCurrentGravityVector.normalized();
236 float angle = previousGravityVectorNormalized.angleBetween(currentGravityVectorNormalized);
237 if (DEBUG) Slog.d(TAG, "getStationaryStatus: angle = " + angle
238 + " energy = " + mRunningStats.getEnergy());
239 if ((angle < mThresholdAngle) && (mRunningStats.getEnergy() < THRESHOLD_ENERGY)) {
240 return RESULT_STATIONARY;
241 } else if (Float.isNaN(angle)) {
243 * Floating point rounding errors have caused the angle calcuation's dot product to
244 * exceed 1.0. In such case, we report RESULT_MOVED to prevent devices from rapidly
245 * retrying this measurement.
249 long diffTime = mCurrentGravityVector.timeMillisSinceBoot -
250 mPreviousGravityVector.timeMillisSinceBoot;
251 if (diffTime > STALE_MEASUREMENT_TIMEOUT_MILLIS) {
252 if (DEBUG) Slog.d(TAG, "getStationaryStatus: mPreviousGravityVector is too stale at " +
253 diffTime + " ms ago. Returning RESULT_UNKNOWN.");
254 return RESULT_UNKNOWN;
259 private final SensorEventListener mListener = new SensorEventListener() {
261 public void onSensorChanged(SensorEvent event) {
262 int status = RESULT_UNKNOWN;
263 synchronized (mLock) {
264 Vector3 accelDatum = new Vector3(SystemClock.elapsedRealtime(), event.values[0],
265 event.values[1], event.values[2]);
266 mRunningStats.accumulate(accelDatum);
268 // If we have enough samples, stop accelerometer data acquisition.
269 if (mRunningStats.getSampleCount() >= mNumSufficientSamples) {
270 status = stopOrientationMeasurementLocked();
273 if (status != RESULT_UNKNOWN) {
274 mCallback.onAnyMotionResult(status);
279 public void onAccuracyChanged(Sensor sensor, int accuracy) {
283 private final Runnable mSensorRestart = new Runnable() {
286 synchronized (mLock) {
287 startOrientationMeasurementLocked();
292 private final Runnable mMeasurementTimeout = new Runnable() {
295 int status = RESULT_UNKNOWN;
296 synchronized (mLock) {
297 if (DEBUG) Slog.i(TAG, "mMeasurementTimeout. Failed to collect sufficient accel " +
298 "data within " + ACCELEROMETER_DATA_TIMEOUT_MILLIS + " ms. Stopping " +
299 "orientation measurement.");
300 status = stopOrientationMeasurementLocked();
302 if (status != RESULT_UNKNOWN) {
303 mCallback.onAnyMotionResult(status);
309 * A timestamped three dimensional vector and some vector operations.
311 public static final class Vector3 {
312 public long timeMillisSinceBoot;
317 public Vector3(long timeMillisSinceBoot, float x, float y, float z) {
318 this.timeMillisSinceBoot = timeMillisSinceBoot;
324 public float norm() {
325 return (float) Math.sqrt(dotProduct(this));
328 public Vector3 normalized() {
330 return new Vector3(timeMillisSinceBoot, x / mag, y / mag, z / mag);
334 * Returns the angle between this 3D vector and another given 3D vector.
335 * Assumes both have already been normalized.
337 * @param other The other Vector3 vector.
338 * @return angle between this vector and the other given one.
340 public float angleBetween(Vector3 other) {
341 Vector3 crossVector = cross(other);
342 float degrees = Math.abs((float)Math.toDegrees(
343 Math.atan2(crossVector.norm(), dotProduct(other))));
344 Slog.d(TAG, "angleBetween: this = " + this.toString() +
345 ", other = " + other.toString() + ", degrees = " + degrees);
349 public Vector3 cross(Vector3 v) {
351 v.timeMillisSinceBoot,
358 public String toString() {
360 msg += "timeMillisSinceBoot=" + timeMillisSinceBoot;
367 public float dotProduct(Vector3 v) {
368 return x * v.x + y * v.y + z * v.z;
371 public Vector3 times(float val) {
372 return new Vector3(timeMillisSinceBoot, x * val, y * val, z * val);
375 public Vector3 plus(Vector3 v) {
376 return new Vector3(v.timeMillisSinceBoot, x + v.x, y + v.y, z + v.z);
379 public Vector3 minus(Vector3 v) {
380 return new Vector3(v.timeMillisSinceBoot, x - v.x, y - v.y, z - v.z);
385 * Maintains running statistics on the signal revelant to AnyMotion detection, including:
387 * <li>running average.
388 * <li>running sum-of-squared-errors as the energy of the signal derivative.
391 private static class RunningSignalStats {
392 Vector3 previousVector;
393 Vector3 currentVector;
398 public RunningSignalStats() {
402 public void reset() {
403 previousVector = null;
404 currentVector = null;
405 runningSum = new Vector3(0, 0, 0, 0);
411 * Apply a 3D vector v as the next element in the running SSE.
413 public void accumulate(Vector3 v) {
415 if (DEBUG) Slog.i(TAG, "Cannot accumulate a null vector.");
419 runningSum = runningSum.plus(v);
420 previousVector = currentVector;
422 if (previousVector != null) {
423 Vector3 dv = currentVector.minus(previousVector);
424 float incrementalEnergy = dv.x * dv.x + dv.y * dv.y + dv.z * dv.z;
425 energy += incrementalEnergy;
426 if (DEBUG) Slog.i(TAG, "Accumulated vector " + currentVector.toString() +
427 ", runningSum = " + runningSum.toString() +
428 ", incrementalEnergy = " + incrementalEnergy +
429 ", energy = " + energy);
433 public Vector3 getRunningAverage() {
434 if (sampleCount > 0) {
435 return runningSum.times((float)(1.0f / sampleCount));
440 public float getEnergy() {
444 public int getSampleCount() {
449 public String toString() {
451 String currentVectorString = (currentVector == null) ?
452 "null" : currentVector.toString();
453 String previousVectorString = (previousVector == null) ?
454 "null" : previousVector.toString();
455 msg += "previousVector = " + previousVectorString;
456 msg += ", currentVector = " + currentVectorString;
457 msg += ", sampleCount = " + sampleCount;
458 msg += ", energy = " + energy;