summaryrefslogtreecommitdiffstats
path: root/services
diff options
context:
space:
mode:
authorMathias Agopian <mathias@google.com>2010-07-21 16:06:46 -0700
committerAndroid (Google) Code Review <android-gerrit@google.com>2010-07-21 16:06:46 -0700
commite4764521353e898554931a557460fc49209fb0a9 (patch)
tree261afe438ecda0a438afe04c8a5e1c40bf978d63 /services
parent3685db7f5dd8a830a4e096404d4924e12697fb78 (diff)
parent1bf797857e025e8a71db86fb9e79765a767ec1eb (diff)
downloadframeworks_base-e4764521353e898554931a557460fc49209fb0a9.zip
frameworks_base-e4764521353e898554931a557460fc49209fb0a9.tar.gz
frameworks_base-e4764521353e898554931a557460fc49209fb0a9.tar.bz2
Merge "new SensorService" into gingerbread
Diffstat (limited to 'services')
-rw-r--r--services/java/com/android/server/SensorService.java282
-rw-r--r--services/java/com/android/server/SystemServer.java4
-rw-r--r--services/jni/Android.mk1
-rw-r--r--services/jni/com_android_server_SensorService.cpp177
-rw-r--r--services/jni/onload.cpp2
-rw-r--r--services/sensorservice/Android.mk28
-rw-r--r--services/sensorservice/SensorService.cpp359
-rw-r--r--services/sensorservice/SensorService.h119
-rw-r--r--services/sensorservice/tests/Android.mk14
-rw-r--r--services/sensorservice/tests/sensorservicetest.cpp90
10 files changed, 610 insertions, 466 deletions
diff --git a/services/java/com/android/server/SensorService.java b/services/java/com/android/server/SensorService.java
deleted file mode 100644
index 9f5718f..0000000
--- a/services/java/com/android/server/SensorService.java
+++ /dev/null
@@ -1,282 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server;
-
-import android.content.Context;
-import android.hardware.ISensorService;
-import android.os.Binder;
-import android.os.Bundle;
-import android.os.RemoteException;
-import android.os.IBinder;
-import android.util.Config;
-import android.util.Slog;
-import android.util.PrintWriterPrinter;
-import android.util.Printer;
-
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-
-import com.android.internal.app.IBatteryStats;
-import com.android.server.am.BatteryStatsService;
-
-
-/**
- * Class that manages the device's sensors. It register clients and activate
- * the needed sensors. The sensor events themselves are not broadcasted from
- * this service, instead, a file descriptor is provided to each client they
- * can read events from.
- */
-
-class SensorService extends ISensorService.Stub {
- static final String TAG = SensorService.class.getSimpleName();
- private static final boolean DEBUG = false;
- private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
- private static final int SENSOR_DISABLE = -1;
- private int mCurrentDelay = 0;
-
- /**
- * Battery statistics to be updated when sensors are enabled and disabled.
- */
- final IBatteryStats mBatteryStats = BatteryStatsService.getService();
-
- private final class Listener implements IBinder.DeathRecipient {
- final IBinder mToken;
- final int mUid;
-
- int mSensors = 0;
- int mDelay = 0x7FFFFFFF;
-
- Listener(IBinder token, int uid) {
- mToken = token;
- mUid = uid;
- }
-
- void addSensor(int sensor, int delay) {
- mSensors |= (1<<sensor);
- if (delay < mDelay)
- mDelay = delay;
- }
-
- void removeSensor(int sensor) {
- mSensors &= ~(1<<sensor);
- }
-
- boolean hasSensor(int sensor) {
- return ((mSensors & (1<<sensor)) != 0);
- }
-
- public void binderDied() {
- if (localLOGV) Slog.d(TAG, "sensor listener died");
- synchronized(mListeners) {
- mListeners.remove(this);
- mToken.unlinkToDeath(this, 0);
- // go through the lists of sensors used by the listener that
- // died and deactivate them.
- for (int sensor=0 ; sensor<32 && mSensors!=0 ; sensor++) {
- if (hasSensor(sensor)) {
- removeSensor(sensor);
- deactivateIfUnusedLocked(sensor);
- try {
- mBatteryStats.noteStopSensor(mUid, sensor);
- } catch (RemoteException e) {
- // oops. not a big deal.
- }
- }
- }
- if (mListeners.size() == 0) {
- _sensors_control_wake();
- _sensors_control_close();
- } else {
- // TODO: we should recalculate the delay, since removing
- // a listener may increase the overall rate.
- }
- mListeners.notify();
- }
- }
- }
-
- @SuppressWarnings("unused")
- public SensorService(Context context) {
- if (localLOGV) Slog.d(TAG, "SensorService startup");
- _sensors_control_init();
- }
-
- public Bundle getDataChannel() throws RemoteException {
- // synchronize so we do not require sensor HAL to be thread-safe.
- synchronized(mListeners) {
- return _sensors_control_open();
- }
- }
-
- public boolean enableSensor(IBinder binder, String name, int sensor, int enable)
- throws RemoteException {
-
- if (localLOGV) Slog.d(TAG, "enableSensor " + name + "(#" + sensor + ") " + enable);
-
- if (binder == null) {
- Slog.e(TAG, "listener is null (sensor=" + name + ", id=" + sensor + ")");
- return false;
- }
-
- if (enable < 0 && (enable != SENSOR_DISABLE)) {
- Slog.e(TAG, "invalid enable parameter (enable=" + enable +
- ", sensor=" + name + ", id=" + sensor + ")");
- return false;
- }
-
- boolean res;
- int uid = Binder.getCallingUid();
- synchronized(mListeners) {
- res = enableSensorInternalLocked(binder, uid, name, sensor, enable);
- if (res == true) {
- // Inform battery statistics service of status change
- long identity = Binder.clearCallingIdentity();
- if (enable == SENSOR_DISABLE) {
- mBatteryStats.noteStopSensor(uid, sensor);
- } else {
- mBatteryStats.noteStartSensor(uid, sensor);
- }
- Binder.restoreCallingIdentity(identity);
- }
- }
- return res;
- }
-
- private boolean enableSensorInternalLocked(IBinder binder, int uid,
- String name, int sensor, int enable) throws RemoteException {
-
- // check if we have this listener
- Listener l = null;
- for (Listener listener : mListeners) {
- if (binder == listener.mToken) {
- l = listener;
- break;
- }
- }
-
- if (enable != SENSOR_DISABLE) {
- // Activate the requested sensor
- if (_sensors_control_activate(sensor, true) == false) {
- Slog.w(TAG, "could not enable sensor " + sensor);
- return false;
- }
-
- if (l == null) {
- /*
- * we don't have a listener for this binder yet, so
- * create a new one and add it to the list.
- */
- l = new Listener(binder, uid);
- binder.linkToDeath(l, 0);
- mListeners.add(l);
- mListeners.notify();
- }
-
- // take note that this sensor is now used by this client
- l.addSensor(sensor, enable);
-
- } else {
-
- if (l == null) {
- /*
- * This client isn't in the list, this usually happens
- * when enabling the sensor failed, but the client
- * didn't handle the error and later tries to shut that
- * sensor off.
- */
- Slog.w(TAG, "listener with binder " + binder +
- ", doesn't exist (sensor=" + name +
- ", id=" + sensor + ")");
- return false;
- }
-
- // remove this sensor from this client
- l.removeSensor(sensor);
-
- // see if we need to deactivate this sensors=
- deactivateIfUnusedLocked(sensor);
-
- // if the listener doesn't have any more sensors active
- // we can get rid of it
- if (l.mSensors == 0) {
- // we won't need this death notification anymore
- binder.unlinkToDeath(l, 0);
- // remove the listener from the list
- mListeners.remove(l);
- // and if the list is empty, turn off the whole sensor h/w
- if (mListeners.size() == 0) {
- _sensors_control_wake();
- _sensors_control_close();
- }
- mListeners.notify();
- }
- }
-
- // calculate and set the new delay
- int minDelay = 0x7FFFFFFF;
- for (Listener listener : mListeners) {
- if (listener.mDelay < minDelay)
- minDelay = listener.mDelay;
- }
- if (minDelay != 0x7FFFFFFF) {
- mCurrentDelay = minDelay;
- _sensors_control_set_delay(minDelay);
- }
-
- return true;
- }
-
- private void deactivateIfUnusedLocked(int sensor) {
- int size = mListeners.size();
- for (int i=0 ; i<size ; i++) {
- if (mListeners.get(i).hasSensor(sensor)) {
- // this sensor is still in use, don't turn it off
- return;
- }
- }
- if (_sensors_control_activate(sensor, false) == false) {
- Slog.w(TAG, "could not disable sensor " + sensor);
- }
- }
-
- @Override
- protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
- synchronized (mListeners) {
- Printer pr = new PrintWriterPrinter(pw);
- int c = 0;
- pr.println(mListeners.size() + " listener(s), delay=" + mCurrentDelay + " ms");
- for (Listener l : mListeners) {
- pr.println("listener[" + c + "] " +
- "sensors=0x" + Integer.toString(l.mSensors, 16) +
- ", uid=" + l.mUid +
- ", delay=" +
- l.mDelay + " ms");
- c++;
- }
- }
- }
-
- private ArrayList<Listener> mListeners = new ArrayList<Listener>();
-
- private static native int _sensors_control_init();
- private static native Bundle _sensors_control_open();
- private static native int _sensors_control_close();
- private static native boolean _sensors_control_activate(int sensor, boolean activate);
- private static native int _sensors_control_set_delay(int ms);
- private static native int _sensors_control_wake();
-}
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index c01680e..ab869bb 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -165,10 +165,6 @@ class ServerThread extends Thread {
Watchdog.getInstance().init(context, battery, power, alarm,
ActivityManagerService.self());
- // Sensor Service is needed by Window Manager, so this goes first
- Slog.i(TAG, "Sensor Service");
- ServiceManager.addService(Context.SENSOR_SERVICE, new SensorService(context));
-
Slog.i(TAG, "Window Manager");
wm = WindowManagerService.main(context, power,
factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL);
diff --git a/services/jni/Android.mk b/services/jni/Android.mk
index 0cf36b3..cdc0a6f 100644
--- a/services/jni/Android.mk
+++ b/services/jni/Android.mk
@@ -7,7 +7,6 @@ LOCAL_SRC_FILES:= \
com_android_server_InputManager.cpp \
com_android_server_LightsService.cpp \
com_android_server_PowerManagerService.cpp \
- com_android_server_SensorService.cpp \
com_android_server_SystemServer.cpp \
com_android_server_VibratorService.cpp \
com_android_server_location_GpsLocationProvider.cpp \
diff --git a/services/jni/com_android_server_SensorService.cpp b/services/jni/com_android_server_SensorService.cpp
deleted file mode 100644
index 77db6da..0000000
--- a/services/jni/com_android_server_SensorService.cpp
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * Copyright 2008, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "SensorService"
-
-#include "utils/Log.h"
-
-#include <hardware/sensors.h>
-
-#include "jni.h"
-#include "JNIHelp.h"
-
-namespace android {
-
-static struct file_descriptor_offsets_t
-{
- jclass mClass;
- jmethodID mConstructor;
- jfieldID mDescriptor;
-} gFileDescriptorOffsets;
-
-static struct parcel_file_descriptor_offsets_t
-{
- jclass mClass;
- jmethodID mConstructor;
-} gParcelFileDescriptorOffsets;
-
-static struct bundle_descriptor_offsets_t
-{
- jclass mClass;
- jmethodID mConstructor;
- jmethodID mPutIntArray;
- jmethodID mPutParcelableArray;
-} gBundleOffsets;
-
-/*
- * The method below are not thread-safe and not intended to be
- */
-
-static sensors_control_device_t* sSensorDevice = 0;
-
-static jint
-android_init(JNIEnv *env, jclass clazz)
-{
- sensors_module_t* module;
- if (hw_get_module(SENSORS_HARDWARE_MODULE_ID, (const hw_module_t**)&module) == 0) {
- if (sensors_control_open(&module->common, &sSensorDevice) == 0) {
- const struct sensor_t* list;
- int count = module->get_sensors_list(module, &list);
- return count;
- }
- }
- return 0;
-}
-
-static jobject
-android_open(JNIEnv *env, jclass clazz)
-{
- native_handle_t* handle = sSensorDevice->open_data_source(sSensorDevice);
- if (!handle) {
- return NULL;
- }
-
- // new Bundle()
- jobject bundle = env->NewObject(
- gBundleOffsets.mClass,
- gBundleOffsets.mConstructor);
-
- if (handle->numFds > 0) {
- jobjectArray fdArray = env->NewObjectArray(handle->numFds,
- gParcelFileDescriptorOffsets.mClass, NULL);
- for (int i = 0; i < handle->numFds; i++) {
- // new FileDescriptor()
- jobject fd = env->NewObject(gFileDescriptorOffsets.mClass,
- gFileDescriptorOffsets.mConstructor);
- env->SetIntField(fd, gFileDescriptorOffsets.mDescriptor, handle->data[i]);
- // new ParcelFileDescriptor()
- jobject pfd = env->NewObject(gParcelFileDescriptorOffsets.mClass,
- gParcelFileDescriptorOffsets.mConstructor, fd);
- env->SetObjectArrayElement(fdArray, i, pfd);
- }
- // bundle.putParcelableArray("fds", fdArray);
- env->CallVoidMethod(bundle, gBundleOffsets.mPutParcelableArray,
- env->NewStringUTF("fds"), fdArray);
- }
-
- if (handle->numInts > 0) {
- jintArray intArray = env->NewIntArray(handle->numInts);
- env->SetIntArrayRegion(intArray, 0, handle->numInts, &handle->data[handle->numInts]);
- // bundle.putIntArray("ints", intArray);
- env->CallVoidMethod(bundle, gBundleOffsets.mPutIntArray,
- env->NewStringUTF("ints"), intArray);
- }
-
- // delete the file handle, but don't close any file descriptors
- native_handle_delete(handle);
- return bundle;
-}
-
-static jint
-android_close(JNIEnv *env, jclass clazz)
-{
- if (sSensorDevice->close_data_source)
- return sSensorDevice->close_data_source(sSensorDevice);
- else
- return 0;
-}
-
-static jboolean
-android_activate(JNIEnv *env, jclass clazz, jint sensor, jboolean activate)
-{
- int active = sSensorDevice->activate(sSensorDevice, sensor, activate);
- return (active<0) ? false : true;
-}
-
-static jint
-android_set_delay(JNIEnv *env, jclass clazz, jint ms)
-{
- return sSensorDevice->set_delay(sSensorDevice, ms);
-}
-
-static jint
-android_data_wake(JNIEnv *env, jclass clazz)
-{
- int res = sSensorDevice->wake(sSensorDevice);
- return res;
-}
-
-
-static JNINativeMethod gMethods[] = {
- {"_sensors_control_init", "()I", (void*) android_init },
- {"_sensors_control_open", "()Landroid/os/Bundle;", (void*) android_open },
- {"_sensors_control_close", "()I", (void*) android_close },
- {"_sensors_control_activate", "(IZ)Z", (void*) android_activate },
- {"_sensors_control_wake", "()I", (void*) android_data_wake },
- {"_sensors_control_set_delay","(I)I", (void*) android_set_delay },
-};
-
-int register_android_server_SensorService(JNIEnv *env)
-{
- jclass clazz;
-
- clazz = env->FindClass("java/io/FileDescriptor");
- gFileDescriptorOffsets.mClass = (jclass)env->NewGlobalRef(clazz);
- gFileDescriptorOffsets.mConstructor = env->GetMethodID(clazz, "<init>", "()V");
- gFileDescriptorOffsets.mDescriptor = env->GetFieldID(clazz, "descriptor", "I");
-
- clazz = env->FindClass("android/os/ParcelFileDescriptor");
- gParcelFileDescriptorOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
- gParcelFileDescriptorOffsets.mConstructor = env->GetMethodID(clazz, "<init>",
- "(Ljava/io/FileDescriptor;)V");
-
- clazz = env->FindClass("android/os/Bundle");
- gBundleOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
- gBundleOffsets.mConstructor = env->GetMethodID(clazz, "<init>", "()V");
- gBundleOffsets.mPutIntArray = env->GetMethodID(clazz, "putIntArray", "(Ljava/lang/String;[I)V");
- gBundleOffsets.mPutParcelableArray = env->GetMethodID(clazz, "putParcelableArray",
- "(Ljava/lang/String;[Landroid/os/Parcelable;)V");
-
- return jniRegisterNativeMethods(env, "com/android/server/SensorService",
- gMethods, NELEM(gMethods));
-}
-
-}; // namespace android
diff --git a/services/jni/onload.cpp b/services/jni/onload.cpp
index 1a2d8b6..cd4f0a4 100644
--- a/services/jni/onload.cpp
+++ b/services/jni/onload.cpp
@@ -9,7 +9,6 @@ int register_android_server_BatteryService(JNIEnv* env);
int register_android_server_InputManager(JNIEnv* env);
int register_android_server_LightsService(JNIEnv* env);
int register_android_server_PowerManagerService(JNIEnv* env);
-int register_android_server_SensorService(JNIEnv* env);
int register_android_server_VibratorService(JNIEnv* env);
int register_android_server_SystemServer(JNIEnv* env);
int register_android_server_location_GpsLocationProvider(JNIEnv* env);
@@ -33,7 +32,6 @@ extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
register_android_server_LightsService(env);
register_android_server_AlarmManagerService(env);
register_android_server_BatteryService(env);
- register_android_server_SensorService(env);
register_android_server_VibratorService(env);
register_android_server_SystemServer(env);
register_android_server_location_GpsLocationProvider(env);
diff --git a/services/sensorservice/Android.mk b/services/sensorservice/Android.mk
new file mode 100644
index 0000000..75f690f
--- /dev/null
+++ b/services/sensorservice/Android.mk
@@ -0,0 +1,28 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= \
+ SensorService.cpp
+
+LOCAL_CFLAGS:= -DLOG_TAG=\"SensorService\"
+
+# need "-lrt" on Linux simulator to pick up clock_gettime
+ifeq ($(TARGET_SIMULATOR),true)
+ ifeq ($(HOST_OS),linux)
+ LOCAL_LDLIBS += -lrt -lpthread
+ endif
+endif
+
+LOCAL_SHARED_LIBRARIES := \
+ libcutils \
+ libhardware \
+ libutils \
+ libbinder \
+ libui \
+ libgui
+
+LOCAL_PRELINK_MODULE := false
+
+LOCAL_MODULE:= libsensorservice
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
new file mode 100644
index 0000000..5410cbc
--- /dev/null
+++ b/services/sensorservice/SensorService.cpp
@@ -0,0 +1,359 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/SortedVector.h>
+#include <utils/KeyedVector.h>
+#include <utils/threads.h>
+#include <utils/Atomic.h>
+#include <utils/Errors.h>
+#include <utils/RefBase.h>
+
+#include <binder/BinderService.h>
+
+#include <gui/ISensorServer.h>
+#include <gui/ISensorEventConnection.h>
+
+#include <hardware/sensors.h>
+
+#include "SensorService.h"
+
+namespace android {
+// ---------------------------------------------------------------------------
+
+/*
+ * TODO:
+ * - handle per-connection event rate
+ * - filter events per connection
+ * - make sure to keep the last value of each event type so we can quickly
+ * send something to application when they enable a sensor that is already
+ * active (the issue here is that it can take time before a value is
+ * produced by the h/w if the rate is low or if it's a one-shot sensor).
+ */
+
+SensorService::SensorService()
+ : Thread(false),
+ mDump("android.permission.DUMP")
+{
+}
+
+void SensorService::onFirstRef()
+{
+ status_t err = hw_get_module(SENSORS_HARDWARE_MODULE_ID,
+ (hw_module_t const**)&mSensorModule);
+
+ LOGE_IF(err, "couldn't load %s module (%s)",
+ SENSORS_HARDWARE_MODULE_ID, strerror(-err));
+
+ err = sensors_open(&mSensorModule->common, &mSensorDevice);
+
+ LOGE_IF(err, "couldn't open device for module %s (%s)",
+ SENSORS_HARDWARE_MODULE_ID, strerror(-err));
+
+ LOGD("nuSensorService starting...");
+
+ struct sensor_t const* list;
+ int count = mSensorModule->get_sensors_list(mSensorModule, &list);
+ for (int i=0 ; i<count ; i++) {
+ Sensor sensor(list + i);
+ LOGI("%s", sensor.getName().string());
+ mSensorList.add(sensor);
+ mSensorDevice->activate(mSensorDevice, sensor.getHandle(), 0);
+ }
+
+ run("SensorService", PRIORITY_URGENT_DISPLAY);
+}
+
+SensorService::~SensorService()
+{
+}
+
+status_t SensorService::dump(int fd, const Vector<String16>& args)
+{
+ const size_t SIZE = 1024;
+ char buffer[SIZE];
+ String8 result;
+ if (!mDump.checkCalling()) {
+ snprintf(buffer, SIZE, "Permission Denial: "
+ "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
+ IPCThreadState::self()->getCallingPid(),
+ IPCThreadState::self()->getCallingUid());
+ result.append(buffer);
+ } else {
+ Mutex::Autolock _l(mLock);
+ snprintf(buffer, SIZE, "%d connections / %d active\n",
+ mConnections.size(), mActiveConnections.size());
+ result.append(buffer);
+ snprintf(buffer, SIZE, "Active sensors:\n");
+ result.append(buffer);
+ for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
+ snprintf(buffer, SIZE, "handle=%d, connections=%d\n",
+ mActiveSensors.keyAt(i),
+ mActiveSensors.valueAt(i)->getNumConnections());
+ result.append(buffer);
+ }
+ }
+ write(fd, result.string(), result.size());
+ return NO_ERROR;
+}
+
+bool SensorService::threadLoop()
+{
+ LOGD("nuSensorService thread starting...");
+
+ sensors_event_t buffer[16];
+ struct sensors_poll_device_t* device = mSensorDevice;
+ ssize_t count;
+
+ do {
+ count = device->poll(device, buffer, sizeof(buffer)/sizeof(*buffer));
+ if (count<0) {
+ LOGE("sensor poll failed (%s)", strerror(-count));
+ break;
+ }
+
+ const SortedVector< wp<SensorEventConnection> > activeConnections(
+ getActiveConnections());
+
+ size_t numConnections = activeConnections.size();
+ if (numConnections) {
+ for (size_t i=0 ; i<numConnections ; i++) {
+ sp<SensorEventConnection> connection(activeConnections[i].promote());
+ if (connection != 0) {
+ connection->sendEvents(buffer, count);
+ }
+ }
+ }
+
+ } while (count >= 0 || Thread::exitPending());
+
+ LOGW("Exiting SensorService::threadLoop!");
+ return false;
+}
+
+SortedVector< wp<SensorService::SensorEventConnection> >
+SensorService::getActiveConnections() const
+{
+ Mutex::Autolock _l(mLock);
+ return mActiveConnections;
+}
+
+Vector<Sensor> SensorService::getSensorList()
+{
+ return mSensorList;
+}
+
+sp<ISensorEventConnection> SensorService::createSensorEventConnection()
+{
+ sp<SensorEventConnection> result(new SensorEventConnection(this));
+ Mutex::Autolock _l(mLock);
+ mConnections.add(result);
+ return result;
+}
+
+void SensorService::cleanupConnection(const wp<SensorEventConnection>& connection)
+{
+ Mutex::Autolock _l(mLock);
+ ssize_t index = mConnections.indexOf(connection);
+ if (index >= 0) {
+
+ size_t size = mActiveSensors.size();
+ for (size_t i=0 ; i<size ; ) {
+ SensorRecord* rec = mActiveSensors.valueAt(i);
+ if (rec && rec->removeConnection(connection)) {
+ mSensorDevice->activate(mSensorDevice, mActiveSensors.keyAt(i), 0);
+ mActiveSensors.removeItemsAt(i, 1);
+ delete rec;
+ size--;
+ } else {
+ i++;
+ }
+ }
+
+ mActiveConnections.remove(connection);
+ mConnections.removeItemsAt(index, 1);
+ }
+}
+
+status_t SensorService::enable(const sp<SensorEventConnection>& connection,
+ int handle)
+{
+ status_t err = NO_ERROR;
+ Mutex::Autolock _l(mLock);
+ SensorRecord* rec = mActiveSensors.valueFor(handle);
+ if (rec == 0) {
+ rec = new SensorRecord(connection);
+ mActiveSensors.add(handle, rec);
+ err = mSensorDevice->activate(mSensorDevice, handle, 1);
+ LOGE_IF(err, "Error activating sensor %d (%s)", handle, strerror(-err));
+ } else {
+ err = rec->addConnection(connection);
+ }
+ if (err == NO_ERROR) {
+ // connection now active
+ connection->addSensor(handle);
+ if (mActiveConnections.indexOf(connection) < 0) {
+ mActiveConnections.add(connection);
+ }
+ }
+ return err;
+}
+
+status_t SensorService::disable(const sp<SensorEventConnection>& connection,
+ int handle)
+{
+ status_t err = NO_ERROR;
+ Mutex::Autolock _l(mLock);
+ SensorRecord* rec = mActiveSensors.valueFor(handle);
+ LOGW("sensor (handle=%d) is not enabled", handle);
+ if (rec) {
+ // see if this connection becomes inactive
+ connection->removeSensor(handle);
+ if (connection->hasAnySensor() == false) {
+ mActiveConnections.remove(connection);
+ }
+ // see if this sensor becomes inactive
+ if (rec->removeConnection(connection)) {
+ mActiveSensors.removeItem(handle);
+ delete rec;
+ err = mSensorDevice->activate(mSensorDevice, handle, 0);
+ }
+ }
+ return err;
+}
+
+status_t SensorService::setRate(const sp<SensorEventConnection>& connection,
+ int handle, nsecs_t ns)
+{
+ status_t err = NO_ERROR;
+ Mutex::Autolock _l(mLock);
+
+ err = mSensorDevice->setDelay(mSensorDevice, handle, ns);
+
+ // TODO: handle rate per connection
+ return err;
+}
+
+// ---------------------------------------------------------------------------
+
+SensorService::SensorRecord::SensorRecord(
+ const sp<SensorEventConnection>& connection)
+{
+ mConnections.add(connection);
+}
+
+status_t SensorService::SensorRecord::addConnection(
+ const sp<SensorEventConnection>& connection)
+{
+ if (mConnections.indexOf(connection) < 0) {
+ mConnections.add(connection);
+ }
+ return NO_ERROR;
+}
+
+bool SensorService::SensorRecord::removeConnection(
+ const wp<SensorEventConnection>& connection)
+{
+ ssize_t index = mConnections.indexOf(connection);
+ if (index >= 0) {
+ mConnections.removeItemsAt(index, 1);
+ }
+ return mConnections.size() ? false : true;
+}
+
+// ---------------------------------------------------------------------------
+
+SensorService::SensorEventConnection::SensorEventConnection(
+ const sp<SensorService>& service)
+ : mService(service), mChannel(new SensorChannel())
+{
+}
+
+SensorService::SensorEventConnection::~SensorEventConnection()
+{
+ mService->cleanupConnection(this);
+}
+
+void SensorService::SensorEventConnection::onFirstRef()
+{
+}
+
+void SensorService::SensorEventConnection::addSensor(int32_t handle) {
+ if (mSensorList.indexOf(handle) <= 0) {
+ mSensorList.add(handle);
+ }
+}
+
+void SensorService::SensorEventConnection::removeSensor(int32_t handle) {
+ mSensorList.remove(handle);
+}
+
+bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
+ return mSensorList.indexOf(handle) >= 0;
+}
+
+bool SensorService::SensorEventConnection::hasAnySensor() const {
+ return mSensorList.size() ? true : false;
+}
+
+status_t SensorService::SensorEventConnection::sendEvents(
+ sensors_event_t const* buffer, size_t count)
+{
+ // TODO: we should only send the events for the sensors this connection
+ // is registered for.
+
+ ssize_t size = mChannel->write(buffer, count*sizeof(sensors_event_t));
+ if (size == -EAGAIN) {
+ // the destination doesn't accept events anymore, it's probably
+ // full. For now, we just drop the events on the floor.
+ LOGW("dropping %d events on the floor", count);
+ return size;
+ }
+
+ LOGE_IF(size<0, "dropping %d events on the floor (%s)",
+ count, strerror(-size));
+
+ return size < 0 ? size : NO_ERROR;
+}
+
+sp<SensorChannel> SensorService::SensorEventConnection::getSensorChannel() const
+{
+ return mChannel;
+}
+
+status_t SensorService::SensorEventConnection::enableDisable(
+ int handle, bool enabled)
+{
+ status_t err;
+ if (enabled) {
+ err = mService->enable(this, handle);
+ } else {
+ err = mService->disable(this, handle);
+ }
+ return err;
+}
+
+status_t SensorService::SensorEventConnection::setEventRate(
+ int handle, nsecs_t ns)
+{
+ return mService->setRate(this, handle, ns);
+}
+
+// ---------------------------------------------------------------------------
+}; // namespace android
+
diff --git a/services/sensorservice/SensorService.h b/services/sensorservice/SensorService.h
new file mode 100644
index 0000000..d5e321c
--- /dev/null
+++ b/services/sensorservice/SensorService.h
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_SENSOR_SERVICE_H
+#define ANDROID_SENSOR_SERVICE_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Vector.h>
+#include <utils/SortedVector.h>
+#include <utils/KeyedVector.h>
+#include <utils/threads.h>
+#include <utils/RefBase.h>
+
+#include <binder/BinderService.h>
+#include <binder/Permission.h>
+
+#include <gui/Sensor.h>
+#include <gui/SensorChannel.h>
+#include <gui/ISensorServer.h>
+#include <gui/ISensorEventConnection.h>
+
+// ---------------------------------------------------------------------------
+
+struct sensors_poll_device_t;
+struct sensors_module_t;
+
+namespace android {
+// ---------------------------------------------------------------------------
+
+class SensorService :
+ public BinderService<SensorService>,
+ public BnSensorServer,
+ protected Thread
+{
+ friend class BinderService<SensorService>;
+
+ SensorService();
+ virtual ~SensorService();
+
+ virtual void onFirstRef();
+
+ // Thread interface
+ virtual bool threadLoop();
+
+ // ISensorServer interface
+ virtual Vector<Sensor> getSensorList();
+ virtual sp<ISensorEventConnection> createSensorEventConnection();
+ virtual status_t dump(int fd, const Vector<String16>& args);
+
+
+ class SensorEventConnection : public BnSensorEventConnection {
+ virtual sp<SensorChannel> getSensorChannel() const;
+ virtual status_t enableDisable(int handle, bool enabled);
+ virtual status_t setEventRate(int handle, nsecs_t ns);
+ sp<SensorService> const mService;
+ sp<SensorChannel> const mChannel;
+ SortedVector<int32_t> mSensorList;
+ public:
+ SensorEventConnection(const sp<SensorService>& service);
+ virtual ~SensorEventConnection();
+ virtual void onFirstRef();
+ status_t sendEvents(sensors_event_t const* buffer, size_t count);
+ bool hasSensor(int32_t handle) const;
+ bool hasAnySensor() const;
+ void addSensor(int32_t handle);
+ void removeSensor(int32_t handle);
+ };
+
+ class SensorRecord {
+ SortedVector< wp<SensorEventConnection> > mConnections;
+ public:
+ SensorRecord(const sp<SensorEventConnection>& connection);
+ status_t addConnection(const sp<SensorEventConnection>& connection);
+ bool removeConnection(const wp<SensorEventConnection>& connection);
+ size_t getNumConnections() const { return mConnections.size(); }
+ };
+
+ SortedVector< wp<SensorEventConnection> > getActiveConnections() const;
+
+ // constants
+ Vector<Sensor> mSensorList;
+ struct sensors_poll_device_t* mSensorDevice;
+ struct sensors_module_t* mSensorModule;
+ Permission mDump;
+
+ // protected by mLock
+ mutable Mutex mLock;
+ SortedVector< wp<SensorEventConnection> > mConnections;
+ DefaultKeyedVector<int, SensorRecord*> mActiveSensors;
+ SortedVector< wp<SensorEventConnection> > mActiveConnections;
+
+public:
+ static char const* getServiceName() { return "sensorservice"; }
+
+ void cleanupConnection(const wp<SensorEventConnection>& connection);
+ status_t enable(const sp<SensorEventConnection>& connection, int handle);
+ status_t disable(const sp<SensorEventConnection>& connection, int handle);
+ status_t setRate(const sp<SensorEventConnection>& connection, int handle, nsecs_t ns);
+};
+
+// ---------------------------------------------------------------------------
+}; // namespace android
+
+#endif // ANDROID_SENSOR_SERVICE_H
diff --git a/services/sensorservice/tests/Android.mk b/services/sensorservice/tests/Android.mk
new file mode 100644
index 0000000..45296dd
--- /dev/null
+++ b/services/sensorservice/tests/Android.mk
@@ -0,0 +1,14 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= \
+ sensorservicetest.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+ libcutils libutils libui libgui
+
+LOCAL_MODULE:= test-sensorservice
+
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_EXECUTABLE)
diff --git a/services/sensorservice/tests/sensorservicetest.cpp b/services/sensorservice/tests/sensorservicetest.cpp
new file mode 100644
index 0000000..e464713
--- /dev/null
+++ b/services/sensorservice/tests/sensorservicetest.cpp
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <android/sensor.h>
+#include <gui/Sensor.h>
+#include <gui/SensorManager.h>
+#include <gui/SensorEventQueue.h>
+#include <utils/PollLoop.h>
+
+using namespace android;
+
+bool receiver(int fd, int events, void* data)
+{
+ sp<SensorEventQueue> q((SensorEventQueue*)data);
+ ssize_t n;
+ ASensorEvent buffer[8];
+ while ((n = q->read(buffer, 8)) > 0) {
+ for (int i=0 ; i<n ; i++) {
+ if (buffer[i].type == Sensor::TYPE_ACCELEROMETER) {
+ printf("time=%lld, value=<%5.1f,%5.1f,%5.1f>\n",
+ buffer[i].timestamp,
+ buffer[i].acceleration.x,
+ buffer[i].acceleration.y,
+ buffer[i].acceleration.z);
+ }
+ }
+ }
+ if (n<0 && n != -EAGAIN) {
+ printf("error reading events (%s)\n", strerror(-n));
+ }
+ return true;
+}
+
+
+int main(int argc, char** argv)
+{
+ SensorManager& mgr(SensorManager::getInstance());
+
+ Sensor const* const* list;
+ ssize_t count = mgr.getSensorList(&list);
+ printf("numSensors=%d\n", count);
+
+ sp<SensorEventQueue> q = mgr.createEventQueue();
+ printf("queue=%p\n", q.get());
+
+ Sensor const* accelerometer = mgr.getDefaultSensor(Sensor::TYPE_ACCELEROMETER);
+ printf("accelerometer=%p (%s)\n",
+ accelerometer, accelerometer->getName().string());
+ q->enableSensor(accelerometer);
+
+ q->setEventRate(accelerometer, ms2ns(10));
+
+ sp<PollLoop> loop = new PollLoop(false);
+ loop->setCallback(q->getFd(), POLLIN, receiver, q.get());
+
+ do {
+ //printf("about to poll...\n");
+ int32_t ret = loop->pollOnce(-1, 0, 0);
+ switch (ret) {
+ case ALOOPER_POLL_CALLBACK:
+ //("ALOOPER_POLL_CALLBACK\n");
+ break;
+ case ALOOPER_POLL_TIMEOUT:
+ printf("ALOOPER_POLL_TIMEOUT\n");
+ break;
+ case ALOOPER_POLL_ERROR:
+ printf("ALOOPER_POLL_TIMEOUT\n");
+ break;
+ default:
+ printf("ugh? poll returned %d\n", ret);
+ break;
+ }
+ } while (1);
+
+
+ return 0;
+}