blob: 6390bcd21022dc5ec1bf46e8a9ca0660606b298e [file] [log] [blame]
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001/*
2 * Copyright (C) 2015 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 com.android.server;
18
19import android.app.AlarmManager;
20import android.content.BroadcastReceiver;
21import android.content.Intent;
22import android.hardware.Sensor;
23import android.hardware.SensorEvent;
24import android.hardware.SensorEventListener;
25import android.hardware.SensorManager;
26import android.os.Handler;
27import android.os.Message;
28import android.os.PowerManager;
29import android.os.SystemClock;
30import android.util.Slog;
31
32import java.lang.Float;
33
34/**
35 * Determines if the device has been set upon a stationary object.
36 */
37public class AnyMotionDetector {
38 interface DeviceIdleCallback {
39 public void onAnyMotionResult(int result);
40 }
41
42 private static final String TAG = "AnyMotionDetector";
43
44 private static final boolean DEBUG = false;
45
46 /** Stationary status is unknown due to insufficient orientation measurements. */
47 public static final int RESULT_UNKNOWN = -1;
48
49 /** Device is stationary, e.g. still on a table. */
50 public static final int RESULT_STATIONARY = 0;
51
52 /** Device has been moved. */
53 public static final int RESULT_MOVED = 1;
54
55 /** Orientation measurements are being performed or are planned. */
56 private static final int STATE_INACTIVE = 0;
57
58 /** No orientation measurements are being performed or are planned. */
59 private static final int STATE_ACTIVE = 1;
60
61 /** Current measurement state. */
62 private int mState;
63
64 /** Threshold angle in degrees beyond which the device is considered moving. */
65 private final float THRESHOLD_ANGLE = 2f;
66
67 /** Threshold energy above which the device is considered moving. */
68 private final float THRESHOLD_ENERGY = 5f;
69
70 /** The duration of the accelerometer orientation measurement. */
71 private static final long ORIENTATION_MEASUREMENT_DURATION_MILLIS = 2500;
72
73 /** The maximum duration we will collect accelerometer data. */
74 private static final long ACCELEROMETER_DATA_TIMEOUT_MILLIS = 3000;
75
76 /** The interval between accelerometer orientation measurements. */
77 private static final long ORIENTATION_MEASUREMENT_INTERVAL_MILLIS = 5000;
78
79 /**
80 * The duration in milliseconds after which an orientation measurement is considered
81 * too stale to be used.
82 */
83 private static final int STALE_MEASUREMENT_TIMEOUT_MILLIS = 2 * 60 * 1000;
84
85 /** The accelerometer sampling interval. */
86 private static final int SAMPLING_INTERVAL_MILLIS = 40;
87
88 private AlarmManager mAlarmManager;
89 private final Handler mHandler;
90 private Intent mAlarmIntent;
91 private final Object mLock = new Object();
92 private Sensor mAccelSensor;
93 private SensorManager mSensorManager;
94 private PowerManager.WakeLock mWakeLock;
95
96 /** The time when detection was last performed. */
97 private long mDetectionStartTime;
98
99 /** The minimum number of samples required to detect AnyMotion. */
100 private int mNumSufficientSamples;
101
102 /** True if an orientation measurement is in progress. */
103 private boolean mMeasurementInProgress;
104
105 /** The most recent gravity vector. */
106 private Vector3 mCurrentGravityVector = null;
107
108 /** The second most recent gravity vector. */
109 private Vector3 mPreviousGravityVector = null;
110
111 /** Running sum of squared errors. */
112 private RunningSignalStats mRunningStats;
113
114 private DeviceIdleCallback mCallback = null;
115
116 public AnyMotionDetector(AlarmManager am, PowerManager pm, Handler handler, SensorManager sm,
117 DeviceIdleCallback callback) {
118 if (DEBUG) Slog.d(TAG, "AnyMotionDetector instantiated.");
119 mAlarmManager = am;
120 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
121 mHandler = handler;
122 mSensorManager = sm;
123 mAccelSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
124 mMeasurementInProgress = false;
125 mState = STATE_INACTIVE;
126 mCallback = callback;
127 mRunningStats = new RunningSignalStats();
128 mNumSufficientSamples = (int) Math.ceil(
129 ((double)ORIENTATION_MEASUREMENT_DURATION_MILLIS / SAMPLING_INTERVAL_MILLIS));
130 if (DEBUG) Slog.d(TAG, "mNumSufficientSamples = " + mNumSufficientSamples);
131 }
132
133 /*
134 * Acquire accel data until we determine AnyMotion status.
135 */
136 public void checkForAnyMotion() {
137 if (DEBUG) Slog.d(TAG, "checkForAnyMotion(). mState = " + mState);
138 if (mState != STATE_ACTIVE) {
139 mState = STATE_ACTIVE;
140 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_ACTIVE.");
141 mCurrentGravityVector = null;
142 mPreviousGravityVector = null;
143 startOrientationMeasurement();
144 }
145 }
146
147 private void startOrientationMeasurement() {
148 if (DEBUG) Slog.d(TAG, "startOrientationMeasurement: mMeasurementInProgress=" +
149 mMeasurementInProgress + ", (mAccelSensor != null)=" + (mAccelSensor != null));
150
151 if (!mMeasurementInProgress && mAccelSensor != null) {
152 if (mSensorManager.registerListener(mListener, mAccelSensor,
153 SAMPLING_INTERVAL_MILLIS * 1000)) {
154 mWakeLock.acquire();
155 mMeasurementInProgress = true;
156 mDetectionStartTime = SystemClock.elapsedRealtime();
157 mRunningStats.reset();
158 }
159
160 Message msg = Message.obtain(mHandler, mMeasurementTimeout);
161 msg.setAsynchronous(true);
162 mHandler.sendMessageDelayed(msg, ACCELEROMETER_DATA_TIMEOUT_MILLIS);
163 }
164 }
165
166 private int stopOrientationMeasurementLocked() {
167 if (DEBUG) Slog.d(TAG, "stopOrientationMeasurement. mMeasurementInProgress=" +
168 mMeasurementInProgress);
169 int status = RESULT_UNKNOWN;
170 if (mMeasurementInProgress) {
171 mSensorManager.unregisterListener(mListener);
172 mHandler.removeCallbacks(mMeasurementTimeout);
173 if (mWakeLock.isHeld()) {
174 mWakeLock.release();
175 }
176 long detectionEndTime = SystemClock.elapsedRealtime();
177 mMeasurementInProgress = false;
178 mPreviousGravityVector = mCurrentGravityVector;
179 mCurrentGravityVector = mRunningStats.getRunningAverage();
180 if (DEBUG) {
181 Slog.d(TAG, "mRunningStats = " + mRunningStats.toString());
182 String currentGravityVectorString = (mCurrentGravityVector == null) ?
183 "null" : mCurrentGravityVector.toString();
184 String previousGravityVectorString = (mPreviousGravityVector == null) ?
185 "null" : mPreviousGravityVector.toString();
186 Slog.d(TAG, "mCurrentGravityVector = " + currentGravityVectorString);
187 Slog.d(TAG, "mPreviousGravityVector = " + previousGravityVectorString);
188 }
189 mRunningStats.reset();
190 status = getStationaryStatus();
191 if (DEBUG) Slog.d(TAG, "getStationaryStatus() returned " + status);
192 if (status != RESULT_UNKNOWN) {
193 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE. status = " +
194 status);
195 mState = STATE_INACTIVE;
196 } else {
197 /*
198 * Unknown due to insufficient measurements. Schedule another orientation
199 * measurement.
200 */
201 if (DEBUG) Slog.d(TAG, "stopOrientationMeasurementLocked(): another measurement" +
202 " scheduled in " + ORIENTATION_MEASUREMENT_INTERVAL_MILLIS +
203 " milliseconds.");
204 Message msg = Message.obtain(mHandler, mSensorRestart);
205 msg.setAsynchronous(true);
206 mHandler.sendMessageDelayed(msg, ORIENTATION_MEASUREMENT_INTERVAL_MILLIS);
207 }
208 }
209 return status;
210 }
211
212 /*
213 * Updates mStatus to the current AnyMotion status.
214 */
215 public int getStationaryStatus() {
216 if ((mPreviousGravityVector == null) || (mCurrentGravityVector == null)) {
217 return RESULT_UNKNOWN;
218 }
219 Vector3 previousGravityVectorNormalized = mPreviousGravityVector.normalized();
220 Vector3 currentGravityVectorNormalized = mCurrentGravityVector.normalized();
221 float angle = previousGravityVectorNormalized.angleBetween(currentGravityVectorNormalized);
222 if (DEBUG) Slog.d(TAG, "getStationaryStatus: angle = " + angle);
223 if ((angle < THRESHOLD_ANGLE) && (mRunningStats.getEnergy() < THRESHOLD_ENERGY)) {
224 return RESULT_STATIONARY;
225 } else if (Float.isNaN(angle)) {
226 /**
227 * Floating point rounding errors have caused the angle calcuation's dot product to
228 * exceed 1.0. In such case, we report RESULT_MOVED to prevent devices from rapidly
229 * retrying this measurement.
230 */
231 return RESULT_MOVED;
232 }
233 long diffTime = mCurrentGravityVector.timeMillisSinceBoot -
234 mPreviousGravityVector.timeMillisSinceBoot;
235 if (diffTime > STALE_MEASUREMENT_TIMEOUT_MILLIS) {
236 if (DEBUG) Slog.d(TAG, "getStationaryStatus: mPreviousGravityVector is too stale at " +
237 diffTime + " ms ago. Returning RESULT_UNKNOWN.");
238 return RESULT_UNKNOWN;
239 }
240 return RESULT_MOVED;
241 }
242
243 private final SensorEventListener mListener = new SensorEventListener() {
244 @Override
245 public void onSensorChanged(SensorEvent event) {
246 int status = RESULT_UNKNOWN;
247 synchronized (mLock) {
248 Vector3 accelDatum = new Vector3(SystemClock.elapsedRealtime(), event.values[0],
249 event.values[1], event.values[2]);
250 mRunningStats.accumulate(accelDatum);
251
252 // If we have enough samples, stop accelerometer data acquisition.
253 if (mRunningStats.getSampleCount() >= mNumSufficientSamples) {
254 status = stopOrientationMeasurementLocked();
255 }
256 }
257 if (status != RESULT_UNKNOWN) {
258 mCallback.onAnyMotionResult(status);
259 }
260 }
261
262 @Override
263 public void onAccuracyChanged(Sensor sensor, int accuracy) {
264 }
265 };
266
267 private final Runnable mSensorRestart = new Runnable() {
268 @Override
269 public void run() {
270 synchronized (mLock) {
271 startOrientationMeasurement();
272 }
273 }
274 };
275
276 private final Runnable mMeasurementTimeout = new Runnable() {
277 @Override
278 public void run() {
279 int status = RESULT_UNKNOWN;
280 synchronized (mLock) {
281 if (DEBUG) Slog.i(TAG, "mMeasurementTimeout. Failed to collect sufficient accel " +
282 "data within " + ACCELEROMETER_DATA_TIMEOUT_MILLIS + " ms. Stopping " +
283 "orientation measurement.");
284 status = stopOrientationMeasurementLocked();
285 }
286 if (status != RESULT_UNKNOWN) {
287 mCallback.onAnyMotionResult(status);
288 }
289 }
290 };
291
292 /**
293 * A timestamped three dimensional vector and some vector operations.
294 */
295 private static class Vector3 {
296 public long timeMillisSinceBoot;
297 public float x;
298 public float y;
299 public float z;
300
301 public Vector3(long timeMillisSinceBoot, float x, float y, float z) {
302 this.timeMillisSinceBoot = timeMillisSinceBoot;
303 this.x = x;
304 this.y = y;
305 this.z = z;
306 }
307
308 private float norm() {
309 return (float) Math.sqrt(dotProduct(this));
310 }
311
312 private Vector3 normalized() {
313 float mag = norm();
314 return new Vector3(timeMillisSinceBoot, x / mag, y / mag, z / mag);
315 }
316
317 /**
318 * Returns the angle between this 3D vector and another given 3D vector.
319 * Assumes both have already been normalized.
320 *
321 * @param other The other Vector3 vector.
322 * @return angle between this vector and the other given one.
323 */
324 public float angleBetween(Vector3 other) {
325 double degrees = Math.toDegrees(Math.acos(this.dotProduct(other)));
326 float returnValue = (float) degrees;
327 Slog.d(TAG, "angleBetween: this = " + this.toString() +
328 ", other = " + other.toString());
329 Slog.d(TAG, " degrees = " + degrees + ", returnValue = " + returnValue);
330 return returnValue;
331 }
332
333 @Override
334 public String toString() {
335 String msg = "";
336 msg += "timeMillisSinceBoot=" + timeMillisSinceBoot;
337 msg += " | x=" + x;
338 msg += ", y=" + y;
339 msg += ", z=" + z;
340 return msg;
341 }
342
343 public float dotProduct(Vector3 v) {
344 return x * v.x + y * v.y + z * v.z;
345 }
346
347 public Vector3 times(float val) {
348 return new Vector3(timeMillisSinceBoot, x * val, y * val, z * val);
349 }
350
351 public Vector3 plus(Vector3 v) {
352 return new Vector3(v.timeMillisSinceBoot, x + v.x, y + v.y, z + v.z);
353 }
354
355 public Vector3 minus(Vector3 v) {
356 return new Vector3(v.timeMillisSinceBoot, x - v.x, y - v.y, z - v.z);
357 }
358 }
359
360 /**
361 * Maintains running statistics on the signal revelant to AnyMotion detection, including:
362 * <ul>
363 * <li>running average.
364 * <li>running sum-of-squared-errors as the energy of the signal derivative.
365 * <ul>
366 */
367 private static class RunningSignalStats {
368 Vector3 previousVector;
369 Vector3 currentVector;
370 Vector3 runningSum;
371 float energy;
372 int sampleCount;
373
374 public RunningSignalStats() {
375 reset();
376 }
377
378 public void reset() {
379 previousVector = null;
380 currentVector = null;
381 runningSum = new Vector3(0, 0, 0, 0);
382 energy = 0;
383 sampleCount = 0;
384 }
385
386 /**
387 * Apply a 3D vector v as the next element in the running SSE.
388 */
389 public void accumulate(Vector3 v) {
390 if (v == null) {
391 if (DEBUG) Slog.i(TAG, "Cannot accumulate a null vector.");
392 return;
393 }
394 sampleCount++;
395 runningSum = runningSum.plus(v);
396 previousVector = currentVector;
397 currentVector = v;
398 if (previousVector != null) {
399 Vector3 dv = currentVector.minus(previousVector);
400 float incrementalEnergy = dv.x * dv.x + dv.y * dv.y + dv.z * dv.z;
401 energy += incrementalEnergy;
402 if (DEBUG) Slog.i(TAG, "Accumulated vector " + currentVector.toString() +
403 ", runningSum = " + runningSum.toString() +
404 ", incrementalEnergy = " + incrementalEnergy +
405 ", energy = " + energy);
406 }
407 }
408
409 public Vector3 getRunningAverage() {
410 if (sampleCount > 0) {
411 return runningSum.times((float)(1.0f / sampleCount));
412 }
413 return null;
414 }
415
416 public float getEnergy() {
417 return energy;
418 }
419
420 public int getSampleCount() {
421 return sampleCount;
422 }
423
424 @Override
425 public String toString() {
426 String msg = "";
427 String currentVectorString = (currentVector == null) ?
428 "null" : currentVector.toString();
429 String previousVectorString = (previousVector == null) ?
430 "null" : previousVector.toString();
431 msg += "previousVector = " + previousVectorString;
432 msg += ", currentVector = " + currentVectorString;
433 msg += ", sampleCount = " + sampleCount;
434 msg += ", energy = " + energy;
435 return msg;
436 }
437 }
438}