M7350v1_en_gpl

This commit is contained in:
T
2024-09-09 08:52:07 +00:00
commit f9cc65cfda
65988 changed files with 26357421 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES:= \
GravitySensor.cpp \
LinearAccelerationSensor.cpp \
RotationVectorSensor.cpp \
SensorService.cpp \
SensorInterface.cpp \
SensorDevice.cpp \
SecondOrderLowPassFilter.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)

View File

@@ -0,0 +1,106 @@
/*
* 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 <math.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <hardware/sensors.h>
#include "GravitySensor.h"
namespace android {
// ---------------------------------------------------------------------------
GravitySensor::GravitySensor(sensor_t const* list, size_t count)
: mSensorDevice(SensorDevice::getInstance()),
mAccTime(0),
mLowPass(M_SQRT1_2, 1.5f),
mX(mLowPass), mY(mLowPass), mZ(mLowPass)
{
for (size_t i=0 ; i<count ; i++) {
if (list[i].type == SENSOR_TYPE_ACCELEROMETER) {
mAccelerometer = Sensor(list + i);
break;
}
}
}
bool GravitySensor::process(sensors_event_t* outEvent,
const sensors_event_t& event)
{
const static double NS2S = 1.0 / 1000000000.0;
if (event.type == SENSOR_TYPE_ACCELEROMETER) {
float x, y, z;
const double now = event.timestamp * NS2S;
if (mAccTime == 0) {
x = mX.init(event.acceleration.x);
y = mY.init(event.acceleration.y);
z = mZ.init(event.acceleration.z);
} else {
double dT = now - mAccTime;
mLowPass.setSamplingPeriod(dT);
x = mX(event.acceleration.x);
y = mY(event.acceleration.y);
z = mZ(event.acceleration.z);
}
mAccTime = now;
*outEvent = event;
outEvent->data[0] = x;
outEvent->data[1] = y;
outEvent->data[2] = z;
outEvent->sensor = '_grv';
outEvent->type = SENSOR_TYPE_GRAVITY;
return true;
}
return false;
}
status_t GravitySensor::activate(void* ident, bool enabled) {
status_t err = mSensorDevice.activate(this, mAccelerometer.getHandle(), enabled);
if (err == NO_ERROR) {
if (enabled) {
mAccTime = 0;
}
}
return err;
}
status_t GravitySensor::setDelay(void* ident, int handle, int64_t ns)
{
return mSensorDevice.setDelay(this, mAccelerometer.getHandle(), ns);
}
Sensor GravitySensor::getSensor() const {
sensor_t hwSensor;
hwSensor.name = "Gravity Sensor";
hwSensor.vendor = "Google Inc.";
hwSensor.version = 1;
hwSensor.handle = '_grv';
hwSensor.type = SENSOR_TYPE_GRAVITY;
hwSensor.maxRange = mAccelerometer.getMaxValue();
hwSensor.resolution = mAccelerometer.getResolution();
hwSensor.power = mAccelerometer.getPowerUsage();
hwSensor.minDelay = mAccelerometer.getMinDelay();
Sensor sensor(&hwSensor);
return sensor;
}
// ---------------------------------------------------------------------------
}; // namespace android

View File

@@ -0,0 +1,54 @@
/*
* 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_GRAVITY_SENSOR_H
#define ANDROID_GRAVITY_SENSOR_H
#include <stdint.h>
#include <sys/types.h>
#include <gui/Sensor.h>
#include "SensorDevice.h"
#include "SensorInterface.h"
#include "SecondOrderLowPassFilter.h"
// ---------------------------------------------------------------------------
namespace android {
// ---------------------------------------------------------------------------
class GravitySensor : public SensorInterface {
SensorDevice& mSensorDevice;
Sensor mAccelerometer;
double mAccTime;
SecondOrderLowPassFilter mLowPass;
CascadedBiquadFilter mX, mY, mZ;
public:
GravitySensor(sensor_t const* list, size_t count);
virtual bool process(sensors_event_t* outEvent,
const sensors_event_t& event);
virtual status_t activate(void* ident, bool enabled);
virtual status_t setDelay(void* ident, int handle, int64_t ns);
virtual Sensor getSensor() const;
virtual bool isVirtual() const { return true; }
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GRAVITY_SENSOR_H

View File

@@ -0,0 +1,82 @@
/*
* 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 <math.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <hardware/sensors.h>
#include "LinearAccelerationSensor.h"
namespace android {
// ---------------------------------------------------------------------------
LinearAccelerationSensor::LinearAccelerationSensor(sensor_t const* list, size_t count)
: mSensorDevice(SensorDevice::getInstance()),
mGravitySensor(list, count)
{
mData[0] = mData[1] = mData[2] = 0;
}
bool LinearAccelerationSensor::process(sensors_event_t* outEvent,
const sensors_event_t& event)
{
bool result = mGravitySensor.process(outEvent, event);
if (result) {
if (event.type == SENSOR_TYPE_ACCELEROMETER) {
mData[0] = event.acceleration.x;
mData[1] = event.acceleration.y;
mData[2] = event.acceleration.z;
}
outEvent->data[0] = mData[0] - outEvent->data[0];
outEvent->data[1] = mData[1] - outEvent->data[1];
outEvent->data[2] = mData[2] - outEvent->data[2];
outEvent->sensor = '_lin';
outEvent->type = SENSOR_TYPE_LINEAR_ACCELERATION;
}
return result;
}
status_t LinearAccelerationSensor::activate(void* ident, bool enabled) {
return mGravitySensor.activate(ident, enabled);
}
status_t LinearAccelerationSensor::setDelay(void* ident, int handle, int64_t ns) {
return mGravitySensor.setDelay(ident, handle, ns);
}
Sensor LinearAccelerationSensor::getSensor() const {
Sensor gsensor(mGravitySensor.getSensor());
sensor_t hwSensor;
hwSensor.name = "Linear Acceleration Sensor";
hwSensor.vendor = "Google Inc.";
hwSensor.version = 1;
hwSensor.handle = '_lin';
hwSensor.type = SENSOR_TYPE_LINEAR_ACCELERATION;
hwSensor.maxRange = gsensor.getMaxValue();
hwSensor.resolution = gsensor.getResolution();
hwSensor.power = gsensor.getPowerUsage();
hwSensor.minDelay = gsensor.getMinDelay();
Sensor sensor(&hwSensor);
return sensor;
}
// ---------------------------------------------------------------------------
}; // namespace android

View File

@@ -0,0 +1,52 @@
/*
* 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_LINEAR_ACCELERATION_SENSOR_H
#define ANDROID_LINEAR_ACCELERATION_SENSOR_H
#include <stdint.h>
#include <sys/types.h>
#include <gui/Sensor.h>
#include "SensorDevice.h"
#include "SensorInterface.h"
#include "GravitySensor.h"
// ---------------------------------------------------------------------------
namespace android {
// ---------------------------------------------------------------------------
class LinearAccelerationSensor : public SensorInterface {
SensorDevice& mSensorDevice;
GravitySensor mGravitySensor;
float mData[3];
virtual bool process(sensors_event_t* outEvent,
const sensors_event_t& event);
public:
LinearAccelerationSensor(sensor_t const* list, size_t count);
virtual status_t activate(void* ident, bool enabled);
virtual status_t setDelay(void* ident, int handle, int64_t ns);
virtual Sensor getSensor() const;
virtual bool isVirtual() const { return true; }
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_LINEAR_ACCELERATION_SENSOR_H

View File

@@ -0,0 +1,169 @@
/*
* 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 <math.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <hardware/sensors.h>
#include "RotationVectorSensor.h"
namespace android {
// ---------------------------------------------------------------------------
template <typename T>
static inline T clamp(T v) {
return v < 0 ? 0 : v;
}
RotationVectorSensor::RotationVectorSensor(sensor_t const* list, size_t count)
: mSensorDevice(SensorDevice::getInstance()),
mALowPass(M_SQRT1_2, 1.5f),
mAX(mALowPass), mAY(mALowPass), mAZ(mALowPass),
mMLowPass(M_SQRT1_2, 1.5f),
mMX(mMLowPass), mMY(mMLowPass), mMZ(mMLowPass)
{
for (size_t i=0 ; i<count ; i++) {
if (list[i].type == SENSOR_TYPE_ACCELEROMETER) {
mAcc = Sensor(list + i);
}
if (list[i].type == SENSOR_TYPE_MAGNETIC_FIELD) {
mMag = Sensor(list + i);
}
}
memset(mMagData, 0, sizeof(mMagData));
}
bool RotationVectorSensor::process(sensors_event_t* outEvent,
const sensors_event_t& event)
{
const static double NS2S = 1.0 / 1000000000.0;
if (event.type == SENSOR_TYPE_MAGNETIC_FIELD) {
const double now = event.timestamp * NS2S;
if (mMagTime == 0) {
mMagData[0] = mMX.init(event.magnetic.x);
mMagData[1] = mMY.init(event.magnetic.y);
mMagData[2] = mMZ.init(event.magnetic.z);
} else {
double dT = now - mMagTime;
mMLowPass.setSamplingPeriod(dT);
mMagData[0] = mMX(event.magnetic.x);
mMagData[1] = mMY(event.magnetic.y);
mMagData[2] = mMZ(event.magnetic.z);
}
mMagTime = now;
}
if (event.type == SENSOR_TYPE_ACCELEROMETER) {
const double now = event.timestamp * NS2S;
float Ax, Ay, Az;
if (mAccTime == 0) {
Ax = mAX.init(event.acceleration.x);
Ay = mAY.init(event.acceleration.y);
Az = mAZ.init(event.acceleration.z);
} else {
double dT = now - mAccTime;
mALowPass.setSamplingPeriod(dT);
Ax = mAX(event.acceleration.x);
Ay = mAY(event.acceleration.y);
Az = mAZ(event.acceleration.z);
}
mAccTime = now;
const float Ex = mMagData[0];
const float Ey = mMagData[1];
const float Ez = mMagData[2];
float Hx = Ey*Az - Ez*Ay;
float Hy = Ez*Ax - Ex*Az;
float Hz = Ex*Ay - Ey*Ax;
const float normH = sqrtf(Hx*Hx + Hy*Hy + Hz*Hz);
if (normH < 0.1f) {
// device is close to free fall (or in space?), or close to
// magnetic north pole. Typical values are > 100.
return false;
}
const float invH = 1.0f / normH;
const float invA = 1.0f / sqrtf(Ax*Ax + Ay*Ay + Az*Az);
Hx *= invH;
Hy *= invH;
Hz *= invH;
Ax *= invA;
Ay *= invA;
Az *= invA;
const float Mx = Ay*Hz - Az*Hy;
const float My = Az*Hx - Ax*Hz;
const float Mz = Ax*Hy - Ay*Hx;
// matrix to rotation vector (normalized quaternion)
float qw = sqrtf( clamp( Hx + My + Az + 1) * 0.25f );
float qx = sqrtf( clamp( Hx - My - Az + 1) * 0.25f );
float qy = sqrtf( clamp(-Hx + My - Az + 1) * 0.25f );
float qz = sqrtf( clamp(-Hx - My + Az + 1) * 0.25f );
qx = copysignf(qx, Ay - Mz);
qy = copysignf(qy, Hz - Ax);
qz = copysignf(qz, Mx - Hy);
// this quaternion is guaranteed to be normalized, by construction
// of the rotation matrix.
*outEvent = event;
outEvent->data[0] = qx;
outEvent->data[1] = qy;
outEvent->data[2] = qz;
outEvent->data[3] = qw;
outEvent->sensor = '_rov';
outEvent->type = SENSOR_TYPE_ROTATION_VECTOR;
return true;
}
return false;
}
status_t RotationVectorSensor::activate(void* ident, bool enabled) {
mSensorDevice.activate(this, mAcc.getHandle(), enabled);
mSensorDevice.activate(this, mMag.getHandle(), enabled);
if (enabled) {
mMagTime = 0;
mAccTime = 0;
}
return NO_ERROR;
}
status_t RotationVectorSensor::setDelay(void* ident, int handle, int64_t ns)
{
mSensorDevice.setDelay(this, mAcc.getHandle(), ns);
mSensorDevice.setDelay(this, mMag.getHandle(), ns);
return NO_ERROR;
}
Sensor RotationVectorSensor::getSensor() const {
sensor_t hwSensor;
hwSensor.name = "Rotation Vector Sensor";
hwSensor.vendor = "Google Inc.";
hwSensor.version = 1;
hwSensor.handle = '_rov';
hwSensor.type = SENSOR_TYPE_ROTATION_VECTOR;
hwSensor.maxRange = 1;
hwSensor.resolution = 1.0f / (1<<24);
hwSensor.power = mAcc.getPowerUsage() + mMag.getPowerUsage();
hwSensor.minDelay = mAcc.getMinDelay();
Sensor sensor(&hwSensor);
return sensor;
}
// ---------------------------------------------------------------------------
}; // namespace android

View File

@@ -0,0 +1,58 @@
/*
* 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_ROTATION_VECTOR_SENSOR_H
#define ANDROID_ROTATION_VECTOR_SENSOR_H
#include <stdint.h>
#include <sys/types.h>
#include <gui/Sensor.h>
#include "SensorDevice.h"
#include "SensorInterface.h"
#include "SecondOrderLowPassFilter.h"
// ---------------------------------------------------------------------------
namespace android {
// ---------------------------------------------------------------------------
class RotationVectorSensor : public SensorInterface {
SensorDevice& mSensorDevice;
Sensor mAcc;
Sensor mMag;
float mMagData[3];
double mAccTime;
double mMagTime;
SecondOrderLowPassFilter mALowPass;
CascadedBiquadFilter mAX, mAY, mAZ;
SecondOrderLowPassFilter mMLowPass;
CascadedBiquadFilter mMX, mMY, mMZ;
public:
RotationVectorSensor(sensor_t const* list, size_t count);
virtual bool process(sensors_event_t* outEvent,
const sensors_event_t& event);
virtual status_t activate(void* ident, bool enabled);
virtual status_t setDelay(void* ident, int handle, int64_t ns);
virtual Sensor getSensor() const;
virtual bool isVirtual() const { return true; }
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_ROTATION_VECTOR_SENSOR_H

View File

@@ -0,0 +1,89 @@
/*
* 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 <math.h>
#include <cutils/log.h>
#include "SecondOrderLowPassFilter.h"
// ---------------------------------------------------------------------------
namespace android {
// ---------------------------------------------------------------------------
SecondOrderLowPassFilter::SecondOrderLowPassFilter(float Q, float fc)
: iQ(1.0f / Q), fc(fc)
{
}
void SecondOrderLowPassFilter::setSamplingPeriod(float dT)
{
K = tanf(float(M_PI) * fc * dT);
iD = 1.0f / (K*K + K*iQ + 1);
a0 = K*K*iD;
a1 = 2.0f * a0;
b1 = 2.0f*(K*K - 1)*iD;
b2 = (K*K - K*iQ + 1)*iD;
}
// ---------------------------------------------------------------------------
BiquadFilter::BiquadFilter(const SecondOrderLowPassFilter& s)
: s(s)
{
}
float BiquadFilter::init(float x)
{
x1 = x2 = x;
y1 = y2 = x;
return x;
}
float BiquadFilter::operator()(float x)
{
float y = (x + x2)*s.a0 + x1*s.a1 - y1*s.b1 - y2*s.b2;
x2 = x1;
y2 = y1;
x1 = x;
y1 = y;
return y;
}
// ---------------------------------------------------------------------------
CascadedBiquadFilter::CascadedBiquadFilter(const SecondOrderLowPassFilter& s)
: mA(s), mB(s)
{
}
float CascadedBiquadFilter::init(float x)
{
mA.init(x);
mB.init(x);
return x;
}
float CascadedBiquadFilter::operator()(float x)
{
return mB(mA(x));
}
// ---------------------------------------------------------------------------
}; // namespace android

View File

@@ -0,0 +1,73 @@
/*
* 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_SECOND_ORDER_LOW_PASS_FILTER_H
#define ANDROID_SECOND_ORDER_LOW_PASS_FILTER_H
#include <stdint.h>
#include <sys/types.h>
// ---------------------------------------------------------------------------
namespace android {
// ---------------------------------------------------------------------------
class BiquadFilter;
/*
* State of a 2nd order low-pass IIR filter
*/
class SecondOrderLowPassFilter {
friend class BiquadFilter;
float iQ, fc;
float K, iD;
float a0, a1;
float b1, b2;
public:
SecondOrderLowPassFilter(float Q, float fc);
void setSamplingPeriod(float dT);
};
/*
* Implements a Biquad IIR filter
*/
class BiquadFilter {
float x1, x2;
float y1, y2;
const SecondOrderLowPassFilter& s;
public:
BiquadFilter(const SecondOrderLowPassFilter& s);
float init(float in);
float operator()(float in);
};
/*
* Two cascaded biquad IIR filters
* (4-poles IIR)
*/
class CascadedBiquadFilter {
BiquadFilter mA;
BiquadFilter mB;
public:
CascadedBiquadFilter(const SecondOrderLowPassFilter& s);
float init(float in);
float operator()(float in);
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_SECOND_ORDER_LOW_PASS_FILTER_H

View File

@@ -0,0 +1,241 @@
/*
* 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 <math.h>
#include <sys/types.h>
#include <utils/Atomic.h>
#include <utils/Errors.h>
#include <utils/Singleton.h>
#include <binder/BinderService.h>
#include <binder/Parcel.h>
#include <binder/IServiceManager.h>
#include <hardware/sensors.h>
#include "SensorDevice.h"
namespace android {
// ---------------------------------------------------------------------------
class BatteryService : public Singleton<BatteryService> {
static const int TRANSACTION_noteStartSensor = IBinder::FIRST_CALL_TRANSACTION + 3;
static const int TRANSACTION_noteStopSensor = IBinder::FIRST_CALL_TRANSACTION + 4;
static const String16 DESCRIPTOR;
friend class Singleton<BatteryService>;
sp<IBinder> mBatteryStatService;
BatteryService() {
const sp<IServiceManager> sm(defaultServiceManager());
if (sm != NULL) {
const String16 name("batteryinfo");
mBatteryStatService = sm->getService(name);
}
}
status_t noteStartSensor(int uid, int handle) {
Parcel data, reply;
data.writeInterfaceToken(DESCRIPTOR);
data.writeInt32(uid);
data.writeInt32(handle);
status_t err = mBatteryStatService->transact(
TRANSACTION_noteStartSensor, data, &reply, 0);
err = reply.readExceptionCode();
return err;
}
status_t noteStopSensor(int uid, int handle) {
Parcel data, reply;
data.writeInterfaceToken(DESCRIPTOR);
data.writeInt32(uid);
data.writeInt32(handle);
status_t err = mBatteryStatService->transact(
TRANSACTION_noteStopSensor, data, &reply, 0);
err = reply.readExceptionCode();
return err;
}
public:
void enableSensor(int handle) {
if (mBatteryStatService != 0) {
int uid = IPCThreadState::self()->getCallingUid();
int64_t identity = IPCThreadState::self()->clearCallingIdentity();
noteStartSensor(uid, handle);
IPCThreadState::self()->restoreCallingIdentity(identity);
}
}
void disableSensor(int handle) {
if (mBatteryStatService != 0) {
int uid = IPCThreadState::self()->getCallingUid();
int64_t identity = IPCThreadState::self()->clearCallingIdentity();
noteStopSensor(uid, handle);
IPCThreadState::self()->restoreCallingIdentity(identity);
}
}
};
const String16 BatteryService::DESCRIPTOR("com.android.internal.app.IBatteryStats");
ANDROID_SINGLETON_STATIC_INSTANCE(BatteryService)
// ---------------------------------------------------------------------------
ANDROID_SINGLETON_STATIC_INSTANCE(SensorDevice)
SensorDevice::SensorDevice()
: mSensorDevice(0),
mSensorModule(0)
{
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));
if (mSensorModule) {
err = sensors_open(&mSensorModule->common, &mSensorDevice);
LOGE_IF(err, "couldn't open device for module %s (%s)",
SENSORS_HARDWARE_MODULE_ID, strerror(-err));
if (mSensorDevice) {
sensor_t const* list;
ssize_t count = mSensorModule->get_sensors_list(mSensorModule, &list);
mActivationCount.setCapacity(count);
Info model;
for (size_t i=0 ; i<size_t(count) ; i++) {
mActivationCount.add(list[i].handle, model);
mSensorDevice->activate(mSensorDevice, list[i].handle, 0);
}
}
}
}
void SensorDevice::dump(String8& result, char* buffer, size_t SIZE)
{
if (!mSensorModule) return;
sensor_t const* list;
ssize_t count = mSensorModule->get_sensors_list(mSensorModule, &list);
snprintf(buffer, SIZE, "%d h/w sensors:\n", int(count));
result.append(buffer);
Mutex::Autolock _l(mLock);
for (size_t i=0 ; i<size_t(count) ; i++) {
snprintf(buffer, SIZE, "handle=0x%08x, active-count=%d\n",
list[i].handle,
mActivationCount.valueFor(list[i].handle).rates.size());
result.append(buffer);
}
}
ssize_t SensorDevice::getSensorList(sensor_t const** list) {
if (!mSensorModule) return NO_INIT;
ssize_t count = mSensorModule->get_sensors_list(mSensorModule, list);
return count;
}
status_t SensorDevice::initCheck() const {
return mSensorDevice && mSensorModule ? NO_ERROR : NO_INIT;
}
ssize_t SensorDevice::poll(sensors_event_t* buffer, size_t count) {
if (!mSensorDevice) return NO_INIT;
return mSensorDevice->poll(mSensorDevice, buffer, count);
}
status_t SensorDevice::activate(void* ident, int handle, int enabled)
{
if (!mSensorDevice) return NO_INIT;
status_t err(NO_ERROR);
bool actuateHardware = false;
Info& info( mActivationCount.editValueFor(handle) );
if (enabled) {
Mutex::Autolock _l(mLock);
if (info.rates.indexOfKey(ident) < 0) {
info.rates.add(ident, DEFAULT_EVENTS_PERIOD);
actuateHardware = true;
} else {
// sensor was already activated for this ident
}
} else {
Mutex::Autolock _l(mLock);
if (info.rates.removeItem(ident) >= 0) {
if (info.rates.size() == 0) {
actuateHardware = true;
}
} else {
// sensor wasn't enabled for this ident
}
}
if (actuateHardware) {
err = mSensorDevice->activate(mSensorDevice, handle, enabled);
if (enabled) {
LOGE_IF(err, "Error activating sensor %d (%s)", handle, strerror(-err));
if (err == 0) {
BatteryService::getInstance().enableSensor(handle);
}
} else {
if (err == 0) {
BatteryService::getInstance().disableSensor(handle);
}
}
}
if (!actuateHardware || enabled) {
Mutex::Autolock _l(mLock);
nsecs_t ns = info.rates.valueAt(0);
for (size_t i=1 ; i<info.rates.size() ; i++) {
if (info.rates.valueAt(i) < ns) {
nsecs_t cur = info.rates.valueAt(i);
if (cur < ns) {
ns = cur;
}
}
}
mSensorDevice->setDelay(mSensorDevice, handle, ns);
}
return err;
}
status_t SensorDevice::setDelay(void* ident, int handle, int64_t ns)
{
if (!mSensorDevice) return NO_INIT;
Info& info( mActivationCount.editValueFor(handle) );
{ // scope for lock
Mutex::Autolock _l(mLock);
ssize_t index = info.rates.indexOfKey(ident);
if (index < 0) return BAD_INDEX;
info.rates.editValueAt(index) = ns;
ns = info.rates.valueAt(0);
for (size_t i=1 ; i<info.rates.size() ; i++) {
nsecs_t cur = info.rates.valueAt(i);
if (cur < ns) {
ns = cur;
}
}
}
return mSensorDevice->setDelay(mSensorDevice, handle, ns);
}
// ---------------------------------------------------------------------------
}; // namespace android

View File

@@ -0,0 +1,61 @@
/*
* 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_DEVICE_H
#define ANDROID_SENSOR_DEVICE_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/KeyedVector.h>
#include <utils/Singleton.h>
#include <utils/String8.h>
#include <gui/Sensor.h>
// ---------------------------------------------------------------------------
namespace android {
// ---------------------------------------------------------------------------
static const nsecs_t DEFAULT_EVENTS_PERIOD = 200000000; // 5 Hz
class SensorDevice : public Singleton<SensorDevice> {
friend class Singleton<SensorDevice>;
struct sensors_poll_device_t* mSensorDevice;
struct sensors_module_t* mSensorModule;
Mutex mLock; // protect mActivationCount[].rates
// fixed-size array after construction
struct Info {
Info() { }
KeyedVector<void*, nsecs_t> rates;
};
DefaultKeyedVector<int, Info> mActivationCount;
SensorDevice();
public:
ssize_t getSensorList(sensor_t const** list);
status_t initCheck() const;
ssize_t poll(sensors_event_t* buffer, size_t count);
status_t activate(void* ident, int handle, int enabled);
status_t setDelay(void* ident, int handle, int64_t ns);
void dump(String8& result, char* buffer, size_t SIZE);
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_SENSOR_DEVICE_H

View File

@@ -0,0 +1,63 @@
/*
* 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 <cutils/log.h>
#include "SensorInterface.h"
namespace android {
// ---------------------------------------------------------------------------
SensorInterface::~SensorInterface()
{
}
// ---------------------------------------------------------------------------
HardwareSensor::HardwareSensor(const sensor_t& sensor)
: mSensorDevice(SensorDevice::getInstance()),
mSensor(&sensor)
{
LOGI("%s", sensor.name);
}
HardwareSensor::~HardwareSensor() {
}
bool HardwareSensor::process(sensors_event_t* outEvent,
const sensors_event_t& event) {
*outEvent = event;
return true;
}
status_t HardwareSensor::activate(void* ident, bool enabled) {
return mSensorDevice.activate(ident, mSensor.getHandle(), enabled);
}
status_t HardwareSensor::setDelay(void* ident, int handle, int64_t ns) {
return mSensorDevice.setDelay(ident, handle, ns);
}
Sensor HardwareSensor::getSensor() const {
return mSensor;
}
// ---------------------------------------------------------------------------
}; // namespace android

View File

@@ -0,0 +1,72 @@
/*
* 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_INTERFACE_H
#define ANDROID_SENSOR_INTERFACE_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Singleton.h>
#include <gui/Sensor.h>
#include "SensorDevice.h"
// ---------------------------------------------------------------------------
namespace android {
// ---------------------------------------------------------------------------
class SensorInterface {
public:
virtual ~SensorInterface();
virtual bool process(sensors_event_t* outEvent,
const sensors_event_t& event) = 0;
virtual status_t activate(void* ident, bool enabled) = 0;
virtual status_t setDelay(void* ident, int handle, int64_t ns) = 0;
virtual Sensor getSensor() const = 0;
virtual bool isVirtual() const = 0;
};
// ---------------------------------------------------------------------------
class HardwareSensor : public SensorInterface
{
SensorDevice& mSensorDevice;
Sensor mSensor;
public:
HardwareSensor(const sensor_t& sensor);
virtual ~HardwareSensor();
virtual bool process(sensors_event_t* outEvent,
const sensors_event_t& event);
virtual status_t activate(void* ident, bool enabled);
virtual status_t setDelay(void* ident, int handle, int64_t ns);
virtual Sensor getSensor() const;
virtual bool isVirtual() const { return false; }
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_SENSOR_INTERFACE_H

View File

@@ -0,0 +1,547 @@
/*
* 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 <math.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 <utils/Singleton.h>
#include <utils/String16.h>
#include <binder/BinderService.h>
#include <binder/IServiceManager.h>
#include <gui/ISensorServer.h>
#include <gui/ISensorEventConnection.h>
#include <hardware/sensors.h>
#include "SensorService.h"
#include "GravitySensor.h"
#include "LinearAccelerationSensor.h"
#include "RotationVectorSensor.h"
namespace android {
// ---------------------------------------------------------------------------
SensorService::SensorService()
: Thread(false),
mDump("android.permission.DUMP"),
mInitCheck(NO_INIT)
{
}
void SensorService::onFirstRef()
{
LOGD("nuSensorService starting...");
SensorDevice& dev(SensorDevice::getInstance());
if (dev.initCheck() == NO_ERROR) {
uint32_t virtualSensorsNeeds =
(1<<SENSOR_TYPE_GRAVITY) |
(1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
(1<<SENSOR_TYPE_ROTATION_VECTOR);
sensor_t const* list;
int count = dev.getSensorList(&list);
mLastEventSeen.setCapacity(count);
for (int i=0 ; i<count ; i++) {
registerSensor( new HardwareSensor(list[i]) );
switch (list[i].type) {
case SENSOR_TYPE_GRAVITY:
case SENSOR_TYPE_LINEAR_ACCELERATION:
case SENSOR_TYPE_ROTATION_VECTOR:
virtualSensorsNeeds &= ~(1<<list[i].type);
break;
}
}
if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
registerVirtualSensor( new GravitySensor(list, count) );
}
if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
registerVirtualSensor( new LinearAccelerationSensor(list, count) );
}
if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
registerVirtualSensor( new RotationVectorSensor(list, count) );
}
run("SensorService", PRIORITY_URGENT_DISPLAY);
mInitCheck = NO_ERROR;
}
}
void SensorService::registerSensor(SensorInterface* s)
{
sensors_event_t event;
memset(&event, 0, sizeof(event));
const Sensor sensor(s->getSensor());
// add to the sensor list (returned to clients)
mSensorList.add(sensor);
// add to our handle->SensorInterface mapping
mSensorMap.add(sensor.getHandle(), s);
// create an entry in the mLastEventSeen array
mLastEventSeen.add(sensor.getHandle(), event);
}
void SensorService::registerVirtualSensor(SensorInterface* s)
{
registerSensor(s);
mVirtualSensorList.add( s );
}
SensorService::~SensorService()
{
for (size_t i=0 ; i<mSensorMap.size() ; i++)
delete mSensorMap.valueAt(i);
}
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, "Sensor List:\n");
result.append(buffer);
for (size_t i=0 ; i<mSensorList.size() ; i++) {
const Sensor& s(mSensorList[i]);
const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
snprintf(buffer, SIZE, "%-48s| %-32s | 0x%08x | maxRate=%7.2fHz | last=<%5.1f,%5.1f,%5.1f>\n",
s.getName().string(),
s.getVendor().string(),
s.getHandle(),
s.getMinDelay() ? (1000000.0f / s.getMinDelay()) : 0.0f,
e.data[0], e.data[1], e.data[2]);
result.append(buffer);
}
SensorDevice::getInstance().dump(result, buffer, SIZE);
snprintf(buffer, SIZE, "%d active connections\n",
mActiveConnections.size());
result.append(buffer);
snprintf(buffer, SIZE, "Active sensors:\n");
result.append(buffer);
for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
int handle = mActiveSensors.keyAt(i);
snprintf(buffer, SIZE, "%s (handle=0x%08x, connections=%d)\n",
getSensorName(handle).string(),
handle,
mActiveSensors.valueAt(i)->getNumConnections());
result.append(buffer);
}
}
write(fd, result.string(), result.size());
return NO_ERROR;
}
bool SensorService::threadLoop()
{
LOGD("nuSensorService thread starting...");
const size_t numEventMax = 16 * (1 + mVirtualSensorList.size());
sensors_event_t buffer[numEventMax];
sensors_event_t scratch[numEventMax];
SensorDevice& device(SensorDevice::getInstance());
const size_t vcount = mVirtualSensorList.size();
ssize_t count;
do {
count = device.poll(buffer, numEventMax);
if (count<0) {
LOGE("sensor poll failed (%s)", strerror(-count));
break;
}
recordLastValue(buffer, count);
// handle virtual sensors
if (count && vcount) {
const DefaultKeyedVector<int, SensorInterface*> virtualSensors(
getActiveVirtualSensors());
const size_t activeVirtualSensorCount = virtualSensors.size();
if (activeVirtualSensorCount) {
size_t k = 0;
for (size_t i=0 ; i<size_t(count) ; i++) {
sensors_event_t const * const event = buffer;
for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
sensors_event_t out;
if (virtualSensors.valueAt(j)->process(&out, event[i])) {
buffer[count + k] = out;
k++;
}
}
}
if (k) {
// record the last synthesized values
recordLastValue(&buffer[count], k);
count += k;
// sort the buffer by time-stamps
sortEventBuffer(buffer, count);
}
}
}
// send our events to clients...
const SortedVector< wp<SensorEventConnection> > activeConnections(
getActiveConnections());
size_t numConnections = activeConnections.size();
for (size_t i=0 ; i<numConnections ; i++) {
sp<SensorEventConnection> connection(
activeConnections[i].promote());
if (connection != 0) {
connection->sendEvents(buffer, count, scratch);
}
}
} while (count >= 0 || Thread::exitPending());
LOGW("Exiting SensorService::threadLoop!");
return false;
}
void SensorService::recordLastValue(
sensors_event_t const * buffer, size_t count)
{
Mutex::Autolock _l(mLock);
// record the last event for each sensor
int32_t prev = buffer[0].sensor;
for (size_t i=1 ; i<count ; i++) {
// record the last event of each sensor type in this buffer
int32_t curr = buffer[i].sensor;
if (curr != prev) {
mLastEventSeen.editValueFor(prev) = buffer[i-1];
prev = curr;
}
}
mLastEventSeen.editValueFor(prev) = buffer[count-1];
}
void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
{
struct compar {
static int cmp(void const* lhs, void const* rhs) {
sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
return r->timestamp - l->timestamp;
}
};
qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
}
SortedVector< wp<SensorService::SensorEventConnection> >
SensorService::getActiveConnections() const
{
Mutex::Autolock _l(mLock);
return mActiveConnections;
}
DefaultKeyedVector<int, SensorInterface*>
SensorService::getActiveVirtualSensors() const
{
Mutex::Autolock _l(mLock);
return mActiveVirtualSensors;
}
String8 SensorService::getSensorName(int handle) const {
size_t count = mSensorList.size();
for (size_t i=0 ; i<count ; i++) {
const Sensor& sensor(mSensorList[i]);
if (sensor.getHandle() == handle) {
return sensor.getName();
}
}
String8 result("unknown");
return result;
}
Vector<Sensor> SensorService::getSensorList()
{
return mSensorList;
}
sp<ISensorEventConnection> SensorService::createSensorEventConnection()
{
sp<SensorEventConnection> result(new SensorEventConnection(this));
return result;
}
void SensorService::cleanupConnection(SensorEventConnection* c)
{
Mutex::Autolock _l(mLock);
const wp<SensorEventConnection> connection(c);
size_t size = mActiveSensors.size();
for (size_t i=0 ; i<size ; ) {
int handle = mActiveSensors.keyAt(i);
if (c->hasSensor(handle)) {
SensorInterface* sensor = mSensorMap.valueFor( handle );
if (sensor) {
sensor->activate(c, false);
}
}
SensorRecord* rec = mActiveSensors.valueAt(i);
if (rec && rec->removeConnection(connection)) {
mActiveSensors.removeItemsAt(i, 1);
mActiveVirtualSensors.removeItem(handle);
delete rec;
size--;
} else {
i++;
}
}
mActiveConnections.remove(connection);
}
status_t SensorService::enable(const sp<SensorEventConnection>& connection,
int handle)
{
if (mInitCheck != NO_ERROR)
return mInitCheck;
Mutex::Autolock _l(mLock);
SensorInterface* sensor = mSensorMap.valueFor(handle);
status_t err = sensor ? sensor->activate(connection.get(), true) : status_t(BAD_VALUE);
if (err == NO_ERROR) {
SensorRecord* rec = mActiveSensors.valueFor(handle);
if (rec == 0) {
rec = new SensorRecord(connection);
mActiveSensors.add(handle, rec);
if (sensor->isVirtual()) {
mActiveVirtualSensors.add(handle, sensor);
}
} else {
if (rec->addConnection(connection)) {
// this sensor is already activated, but we are adding a
// connection that uses it. Immediately send down the last
// known value of the requested sensor.
sensors_event_t scratch;
sensors_event_t& event(mLastEventSeen.editValueFor(handle));
if (event.version == sizeof(sensors_event_t)) {
connection->sendEvents(&event, 1);
}
}
}
if (err == NO_ERROR) {
// connection now active
if (connection->addSensor(handle)) {
// the sensor was added (which means it wasn't already there)
// so, see if this connection becomes active
if (mActiveConnections.indexOf(connection) < 0) {
mActiveConnections.add(connection);
}
}
}
}
return err;
}
status_t SensorService::disable(const sp<SensorEventConnection>& connection,
int handle)
{
if (mInitCheck != NO_ERROR)
return mInitCheck;
status_t err = NO_ERROR;
Mutex::Autolock _l(mLock);
SensorRecord* rec = mActiveSensors.valueFor(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);
mActiveVirtualSensors.removeItem(handle);
delete rec;
}
SensorInterface* sensor = mSensorMap.valueFor(handle);
err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
}
return err;
}
status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
int handle, nsecs_t ns)
{
if (mInitCheck != NO_ERROR)
return mInitCheck;
if (ns < 0)
return BAD_VALUE;
if (ns < MINIMUM_EVENTS_PERIOD)
ns = MINIMUM_EVENTS_PERIOD;
SensorInterface* sensor = mSensorMap.valueFor(handle);
if (!sensor) return BAD_VALUE;
return sensor->setDelay(connection.get(), handle, ns);
}
// ---------------------------------------------------------------------------
SensorService::SensorRecord::SensorRecord(
const sp<SensorEventConnection>& connection)
{
mConnections.add(connection);
}
bool SensorService::SensorRecord::addConnection(
const sp<SensorEventConnection>& connection)
{
if (mConnections.indexOf(connection) < 0) {
mConnections.add(connection);
return true;
}
return false;
}
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()
{
}
bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mutex::Autolock _l(mConnectionLock);
if (mSensorInfo.indexOf(handle) <= 0) {
mSensorInfo.add(handle);
return true;
}
return false;
}
bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mutex::Autolock _l(mConnectionLock);
if (mSensorInfo.remove(handle) >= 0) {
return true;
}
return false;
}
bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mutex::Autolock _l(mConnectionLock);
return mSensorInfo.indexOf(handle) >= 0;
}
bool SensorService::SensorEventConnection::hasAnySensor() const {
Mutex::Autolock _l(mConnectionLock);
return mSensorInfo.size() ? true : false;
}
status_t SensorService::SensorEventConnection::sendEvents(
sensors_event_t const* buffer, size_t numEvents,
sensors_event_t* scratch)
{
// filter out events not for this connection
size_t count = 0;
if (scratch) {
Mutex::Autolock _l(mConnectionLock);
size_t i=0;
while (i<numEvents) {
const int32_t curr = buffer[i].sensor;
if (mSensorInfo.indexOf(curr) >= 0) {
do {
scratch[count++] = buffer[i++];
} while ((i<numEvents) && (buffer[i].sensor == curr));
} else {
i++;
}
}
} else {
scratch = const_cast<sensors_event_t *>(buffer);
count = numEvents;
}
if (count == 0)
return 0;
ssize_t size = mChannel->write(scratch, 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 ? status_t(size) : status_t(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->setEventRate(this, handle, ns);
}
// ---------------------------------------------------------------------------
}; // namespace android

View File

@@ -0,0 +1,141 @@
/*
* 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>
#include "SensorInterface.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>;
static const nsecs_t MINIMUM_EVENTS_PERIOD = 1000000; // 1000 Hz
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 ~SensorEventConnection();
virtual void onFirstRef();
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;
mutable Mutex mConnectionLock;
// protected by SensorService::mLock
SortedVector<int> mSensorInfo;
public:
SensorEventConnection(const sp<SensorService>& service);
status_t sendEvents(sensors_event_t const* buffer, size_t count,
sensors_event_t* scratch = NULL);
bool hasSensor(int32_t handle) const;
bool hasAnySensor() const;
bool addSensor(int32_t handle);
bool removeSensor(int32_t handle);
};
class SensorRecord {
SortedVector< wp<SensorEventConnection> > mConnections;
public:
SensorRecord(const sp<SensorEventConnection>& connection);
bool addConnection(const sp<SensorEventConnection>& connection);
bool removeConnection(const wp<SensorEventConnection>& connection);
size_t getNumConnections() const { return mConnections.size(); }
};
SortedVector< wp<SensorEventConnection> > getActiveConnections() const;
DefaultKeyedVector<int, SensorInterface*> getActiveVirtualSensors() const;
String8 getSensorName(int handle) const;
void recordLastValue(sensors_event_t const * buffer, size_t count);
static void sortEventBuffer(sensors_event_t* buffer, size_t count);
void registerSensor(SensorInterface* sensor);
void registerVirtualSensor(SensorInterface* sensor);
// constants
Vector<Sensor> mSensorList;
DefaultKeyedVector<int, SensorInterface*> mSensorMap;
Vector<SensorInterface *> mVirtualSensorList;
Permission mDump;
status_t mInitCheck;
// protected by mLock
mutable Mutex mLock;
DefaultKeyedVector<int, SensorRecord*> mActiveSensors;
DefaultKeyedVector<int, SensorInterface*> mActiveVirtualSensors;
SortedVector< wp<SensorEventConnection> > mActiveConnections;
// The size of this vector is constant, only the items are mutable
KeyedVector<int32_t, sensors_event_t> mLastEventSeen;
public:
static char const* getServiceName() { return "sensorservice"; }
void cleanupConnection(SensorEventConnection* connection);
status_t enable(const sp<SensorEventConnection>& connection, int handle);
status_t disable(const sp<SensorEventConnection>& connection, int handle);
status_t setEventRate(const sp<SensorEventConnection>& connection, int handle, nsecs_t ns);
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_SENSOR_SERVICE_H

View File

@@ -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)

View File

@@ -0,0 +1,103 @@
/*
* 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/Looper.h>
using namespace android;
int receiver(int fd, int events, void* data)
{
sp<SensorEventQueue> q((SensorEventQueue*)data);
ssize_t n;
ASensorEvent buffer[8];
static nsecs_t oldTimeStamp = 0;
while ((n = q->read(buffer, 8)) > 0) {
for (int i=0 ; i<n ; i++) {
if (buffer[i].type == Sensor::TYPE_GYROSCOPE) {
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 (oldTimeStamp) {
float t = float(buffer[i].timestamp - oldTimeStamp) / s2ns(1);
printf("%f ms (%f Hz)\n", t*1000, 1.0/t);
}
oldTimeStamp = buffer[i].timestamp;
}
}
if (n<0 && n != -EAGAIN) {
printf("error reading events (%s)\n", strerror(-n));
}
return 1;
}
int main(int argc, char** argv)
{
SensorManager& mgr(SensorManager::getInstance());
Sensor const* const* list;
ssize_t count = mgr.getSensorList(&list);
printf("numSensors=%d\n", int(count));
sp<SensorEventQueue> q = mgr.createEventQueue();
printf("queue=%p\n", q.get());
Sensor const* accelerometer = mgr.getDefaultSensor(Sensor::TYPE_GYROSCOPE);
printf("accelerometer=%p (%s)\n",
accelerometer, accelerometer->getName().string());
q->enableSensor(accelerometer);
q->setEventRate(accelerometer, ms2ns(10));
sp<Looper> loop = new Looper(false);
loop->addFd(q->getFd(), 0, ALOOPER_EVENT_INPUT, receiver, q.get());
do {
//printf("about to poll...\n");
int32_t ret = loop->pollOnce(-1);
switch (ret) {
case ALOOPER_POLL_WAKE:
//("ALOOPER_POLL_WAKE\n");
break;
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;
}