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