43 changes: 39 additions & 4 deletions libsensors/Android.mk
Expand Up @@ -17,15 +17,50 @@ LOCAL_PATH := $(call my-dir)

ifneq ($(TARGET_SIMULATOR),true)

# HAL module implemenation, not prelinked and stored in
# HAL module implemenation, not prelinked, and stored in
# hw/<SENSORS_HARDWARE_MODULE_ID>.<ro.product.board>.so
include $(CLEAR_VARS)
LOCAL_PRELINK_MODULE := false

LOCAL_MODULE := sensors.sapphire

LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/hw

LOCAL_MODULE_TAGS := optional

LOCAL_CFLAGS := -DLOG_TAG=\"Sensors\"
LOCAL_SRC_FILES := \
sensors.c \
nusensors.cpp \
InputEventReader.cpp \
SensorBase.cpp \
AkmSensor.cpp

LOCAL_SHARED_LIBRARIES := liblog libcutils
LOCAL_PRELINK_MODULE := false

include $(BUILD_SHARED_LIBRARY)

# HAL module implemenation, not prelinked and stored in
# hw/<SENSORS_HARDWARE_MODULE_ID>.<ro.product.board>.so
include $(CLEAR_VARS)

LOCAL_MODULE := sensors.trout

LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/hw

LOCAL_MODULE_TAGS := optional

LOCAL_CFLAGS := -DLOG_TAG=\"Sensors\"
LOCAL_SRC_FILES := \
sensors.c \
nusensors.cpp \
InputEventReader.cpp \
SensorBase.cpp \
AkmSensor.cpp

LOCAL_SHARED_LIBRARIES := liblog libcutils
LOCAL_SRC_FILES := sensors.c
LOCAL_MODULE := sensors.msm7k
LOCAL_PRELINK_MODULE := false

include $(BUILD_SHARED_LIBRARY)

endif # !TARGET_SIMULATOR
88 changes: 88 additions & 0 deletions libsensors/InputEventReader.cpp
@@ -0,0 +1,88 @@
/*
* 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.
*/

#include <stdint.h>
#include <errno.h>
#include <unistd.h>
#include <poll.h>

#include <sys/cdefs.h>
#include <sys/types.h>

#include <linux/input.h>

#include <cutils/log.h>

#include "InputEventReader.h"

/*****************************************************************************/

struct input_event;

InputEventCircularReader::InputEventCircularReader(size_t numEvents)
: mBuffer(new input_event[numEvents * 2]),
mBufferEnd(mBuffer + numEvents),
mHead(mBuffer),
mCurr(mBuffer),
mFreeSpace(numEvents)
{
}

InputEventCircularReader::~InputEventCircularReader()
{
delete [] mBuffer;
}

ssize_t InputEventCircularReader::fill(int fd)
{
size_t numEventsRead = 0;
if (mFreeSpace) {
const ssize_t nread = read(fd, mHead, mFreeSpace * sizeof(input_event));
if (nread<0 || nread % sizeof(input_event)) {
// we got a partial event!!
return nread<0 ? -errno : -EINVAL;
}

numEventsRead = nread / sizeof(input_event);
if (numEventsRead) {
mHead += numEventsRead;
mFreeSpace -= numEventsRead;
if (mHead > mBufferEnd) {
size_t s = mHead - mBufferEnd;
memcpy(mBuffer, mBufferEnd, s * sizeof(input_event));
mHead = mBuffer + s;
}
}
}

return numEventsRead;
}

ssize_t InputEventCircularReader::readEvent(input_event const** events)
{
*events = mCurr;
ssize_t available = (mBufferEnd - mBuffer) - mFreeSpace;
return available ? 1 : 0;
}

void InputEventCircularReader::next()
{
mCurr++;
mFreeSpace++;
if (mCurr >= mBufferEnd) {
mCurr = mBuffer;
}
}
47 changes: 47 additions & 0 deletions libsensors/InputEventReader.h
@@ -0,0 +1,47 @@
/*
* 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.
*/

#ifndef ANDROID_INPUT_EVENT_READER_H
#define ANDROID_INPUT_EVENT_READER_H

#include <stdint.h>
#include <errno.h>
#include <sys/cdefs.h>
#include <sys/types.h>

/*****************************************************************************/

struct input_event;

class InputEventCircularReader
{
struct input_event* const mBuffer;
struct input_event* const mBufferEnd;
struct input_event* mHead;
struct input_event* mCurr;
ssize_t mFreeSpace;

public:
InputEventCircularReader(size_t numEvents);
~InputEventCircularReader();
ssize_t fill(int fd);
ssize_t readEvent(input_event const** events);
void next();
};

/*****************************************************************************/

#endif // ANDROID_INPUT_EVENT_READER_H
154 changes: 154 additions & 0 deletions libsensors/LightSensor.cpp
@@ -0,0 +1,154 @@
/*
* 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.
*/

#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/select.h>

#include <linux/lightsensor.h>

#include <cutils/log.h>

#include "LightSensor.h"

/*****************************************************************************/

LightSensor::LightSensor()
: SensorBase(LS_DEVICE_NAME, "lightsensor-level"),
mEnabled(0),
mInputReader(4),
mHasPendingEvent(false)
{
mPendingEvent.version = sizeof(sensors_event_t);
mPendingEvent.sensor = ID_L;
mPendingEvent.type = SENSOR_TYPE_LIGHT;
memset(mPendingEvent.data, 0, sizeof(mPendingEvent.data));

open_device();

int flags = 0;
if (!ioctl(dev_fd, LIGHTSENSOR_IOCTL_GET_ENABLED, &flags)) {
if (flags) {
mEnabled = 1;
setInitialState();
}
}

if (!mEnabled) {
close_device();
}
}

LightSensor::~LightSensor() {
}

int LightSensor::setInitialState() {
struct input_absinfo absinfo;
if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_LIGHT), &absinfo)) {
mPendingEvent.light = indexToValue(absinfo.value);
mHasPendingEvent = true;
}
return 0;
}

int LightSensor::enable(int32_t, int en) {
int flags = en ? 1 : 0;
int err = 0;
if (flags != mEnabled) {
if (!mEnabled) {
open_device();
}
err = ioctl(dev_fd, LIGHTSENSOR_IOCTL_ENABLE, &flags);
err = err<0 ? -errno : 0;
LOGE_IF(err, "LIGHTSENSOR_IOCTL_ENABLE failed (%s)", strerror(-err));
if (!err) {
mEnabled = en ? 1 : 0;
if (en) {
setInitialState();
}
}
if (!mEnabled) {
close_device();
}
}
return err;
}

bool LightSensor::hasPendingEvents() const {
return mHasPendingEvent;
}

int LightSensor::readEvents(sensors_event_t* data, int count)
{
if (count < 1)
return -EINVAL;

if (mHasPendingEvent) {
mHasPendingEvent = false;
mPendingEvent.timestamp = getTimestamp();
*data = mPendingEvent;
return mEnabled ? 1 : 0;
}

ssize_t n = mInputReader.fill(data_fd);
if (n < 0)
return n;

int numEventReceived = 0;
input_event const* event;

while (count && mInputReader.readEvent(&event)) {
int type = event->type;
if (type == EV_ABS) {
if (event->code == EVENT_TYPE_LIGHT) {
if (event->value != -1) {
// FIXME: not sure why we're getting -1 sometimes
mPendingEvent.light = indexToValue(event->value);
}
}
} else if (type == EV_SYN) {
mPendingEvent.timestamp = timevalToNano(event->time);
if (mEnabled) {
*data++ = mPendingEvent;
count--;
numEventReceived++;
}
} else {
LOGE("LightSensor: unknown event (type=%d, code=%d)",
type, event->code);
}
mInputReader.next();
}

return numEventReceived;
}

float LightSensor::indexToValue(size_t index) const
{
static const float luxValues[8] = {
10.0, 160.0, 225.0, 320.0,
640.0, 1280.0, 2600.0, 10240.0
};

const size_t maxIndex = sizeof(luxValues)/sizeof(*luxValues) - 1;
if (index > maxIndex)
index = maxIndex;
return luxValues[index];
}
52 changes: 52 additions & 0 deletions libsensors/LightSensor.h
@@ -0,0 +1,52 @@
/*
* 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.
*/

#ifndef ANDROID_LIGHT_SENSOR_H
#define ANDROID_LIGHT_SENSOR_H

#include <stdint.h>
#include <errno.h>
#include <sys/cdefs.h>
#include <sys/types.h>

#include "nusensors.h"
#include "SensorBase.h"
#include "InputEventReader.h"

/*****************************************************************************/

struct input_event;

class LightSensor : public SensorBase {
int mEnabled;
InputEventCircularReader mInputReader;
sensors_event_t mPendingEvent;
bool mHasPendingEvent;

float indexToValue(size_t index) const;
int setInitialState();

public:
LightSensor();
virtual ~LightSensor();
virtual int readEvents(sensors_event_t* data, int count);
virtual bool hasPendingEvents() const;
virtual int enable(int32_t handle, int enabled);
};

/*****************************************************************************/

#endif // ANDROID_LIGHT_SENSOR_H
Empty file.
190 changes: 190 additions & 0 deletions libsensors/NOTICE
@@ -0,0 +1,190 @@

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.

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.


Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.

"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:

(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and

(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and

(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and

(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.

You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

144 changes: 144 additions & 0 deletions libsensors/ProximitySensor.cpp
@@ -0,0 +1,144 @@
/*
* 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.
*/

#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/select.h>

#include <linux/capella_cm3602.h>

#include <cutils/log.h>

#include "ProximitySensor.h"

/*****************************************************************************/

ProximitySensor::ProximitySensor()
: SensorBase(CM_DEVICE_NAME, "proximity"),
mEnabled(0),
mInputReader(4),
mHasPendingEvent(false)
{
mPendingEvent.version = sizeof(sensors_event_t);
mPendingEvent.sensor = ID_P;
mPendingEvent.type = SENSOR_TYPE_PROXIMITY;
memset(mPendingEvent.data, 0, sizeof(mPendingEvent.data));

open_device();

int flags = 0;
if (!ioctl(dev_fd, CAPELLA_CM3602_IOCTL_GET_ENABLED, &flags)) {
mEnabled = 1;
if (flags) {
setInitialState();
}
}
if (!mEnabled) {
close_device();
}
}

ProximitySensor::~ProximitySensor() {
}

int ProximitySensor::setInitialState() {
struct input_absinfo absinfo;
if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_PROXIMITY), &absinfo)) {
// make sure to report an event immediately
mHasPendingEvent = true;
mPendingEvent.distance = indexToValue(absinfo.value);
}
return 0;
}

int ProximitySensor::enable(int32_t, int en) {
int newState = en ? 1 : 0;
int err = 0;
if (newState != mEnabled) {
if (!mEnabled) {
open_device();
}
int flags = newState;
err = ioctl(dev_fd, CAPELLA_CM3602_IOCTL_ENABLE, &flags);
err = err<0 ? -errno : 0;
LOGE_IF(err, "CAPELLA_CM3602_IOCTL_ENABLE failed (%s)", strerror(-err));
if (!err) {
mEnabled = newState;
if (en) {
setInitialState();
}
}
if (!mEnabled) {
close_device();
}
}
return err;
}

bool ProximitySensor::hasPendingEvents() const {
return mHasPendingEvent;
}

int ProximitySensor::readEvents(sensors_event_t* data, int count)
{
if (count < 1)
return -EINVAL;

if (mHasPendingEvent) {
mHasPendingEvent = false;
mPendingEvent.timestamp = getTimestamp();
*data = mPendingEvent;
return mEnabled ? 1 : 0;
}

ssize_t n = mInputReader.fill(data_fd);
if (n < 0)
return n;

int numEventReceived = 0;
input_event const* event;

while (count && mInputReader.readEvent(&event)) {
int type = event->type;
if (type == EV_ABS) {
if (event->code == EVENT_TYPE_PROXIMITY) {
mPendingEvent.distance = indexToValue(event->value);
}
} else if (type == EV_SYN) {
mPendingEvent.timestamp = timevalToNano(event->time);
if (mEnabled) {
*data++ = mPendingEvent;
count--;
numEventReceived++;
}
} else {
LOGE("ProximitySensor: unknown event (type=%d, code=%d)",
type, event->code);
}
mInputReader.next();
}

return numEventReceived;
}

float ProximitySensor::indexToValue(size_t index) const
{
return index * PROXIMITY_THRESHOLD_CM;
}
52 changes: 52 additions & 0 deletions libsensors/ProximitySensor.h
@@ -0,0 +1,52 @@
/*
* 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.
*/

#ifndef ANDROID_PROXIMITY_SENSOR_H
#define ANDROID_PROXIMITY_SENSOR_H

#include <stdint.h>
#include <errno.h>
#include <sys/cdefs.h>
#include <sys/types.h>

#include "nusensors.h"
#include "SensorBase.h"
#include "InputEventReader.h"

/*****************************************************************************/

struct input_event;

class ProximitySensor : public SensorBase {
int mEnabled;
InputEventCircularReader mInputReader;
sensors_event_t mPendingEvent;
bool mHasPendingEvent;

int setInitialState();
float indexToValue(size_t index) const;

public:
ProximitySensor();
virtual ~ProximitySensor();
virtual int readEvents(sensors_event_t* data, int count);
virtual bool hasPendingEvents() const;
virtual int enable(int32_t handle, int enabled);
};

/*****************************************************************************/

#endif // ANDROID_PROXIMITY_SENSOR_H
122 changes: 122 additions & 0 deletions libsensors/SensorBase.cpp
@@ -0,0 +1,122 @@
/*
* 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.
*/

#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/select.h>

#include <cutils/log.h>

#include <linux/input.h>

#include "SensorBase.h"

/*****************************************************************************/

SensorBase::SensorBase(
const char* dev_name,
const char* data_name)
: dev_name(dev_name), data_name(data_name),
dev_fd(-1), data_fd(-1)
{
data_fd = openInput(data_name);
}

SensorBase::~SensorBase() {
if (data_fd >= 0) {
close(data_fd);
}
if (dev_fd >= 0) {
close(dev_fd);
}
}

int SensorBase::open_device() {
if (dev_fd<0 && dev_name) {
dev_fd = open(dev_name, O_RDONLY);
LOGE_IF(dev_fd<0, "Couldn't open %s (%s)", dev_name, strerror(errno));
}
return 0;
}

int SensorBase::close_device() {
if (dev_fd >= 0) {
close(dev_fd);
dev_fd = -1;
}
return 0;
}

int SensorBase::getFd() const {
return data_fd;
}

int SensorBase::setDelay(int32_t handle, int64_t ns) {
return 0;
}

bool SensorBase::hasPendingEvents() const {
return false;
}

int64_t SensorBase::getTimestamp() {
struct timespec t;
t.tv_sec = t.tv_nsec = 0;
clock_gettime(CLOCK_MONOTONIC, &t);
return int64_t(t.tv_sec)*1000000000LL + t.tv_nsec;
}

int SensorBase::openInput(const char* inputName) {
int fd = -1;
const char *dirname = "/dev/input";
char devname[PATH_MAX];
char *filename;
DIR *dir;
struct dirent *de;
dir = opendir(dirname);
if(dir == NULL)
return -1;
strcpy(devname, dirname);
filename = devname + strlen(devname);
*filename++ = '/';
while((de = readdir(dir))) {
if(de->d_name[0] == '.' &&
(de->d_name[1] == '\0' ||
(de->d_name[1] == '.' && de->d_name[2] == '\0')))
continue;
strcpy(filename, de->d_name);
fd = open(devname, O_RDONLY);
if (fd>=0) {
char name[80];
if (ioctl(fd, EVIOCGNAME(sizeof(name) - 1), &name) < 1) {
name[0] = '\0';
}
if (!strcmp(name, inputName)) {
break;
} else {
close(fd);
fd = -1;
}
}
}
closedir(dir);
LOGE_IF(fd<0, "couldn't find '%s' input device", inputName);
return fd;
}
64 changes: 64 additions & 0 deletions libsensors/SensorBase.h
@@ -0,0 +1,64 @@
/*
* 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.
*/

#ifndef ANDROID_SENSOR_BASE_H
#define ANDROID_SENSOR_BASE_H

#include <stdint.h>
#include <errno.h>
#include <sys/cdefs.h>
#include <sys/types.h>


/*****************************************************************************/

struct sensors_event_t;

class SensorBase {
protected:
const char* dev_name;
const char* data_name;
int dev_fd;
int data_fd;

static int openInput(const char* inputName);
static int64_t getTimestamp();


static int64_t timevalToNano(timeval const& t) {
return t.tv_sec*1000000000LL + t.tv_usec*1000;
}

int open_device();
int close_device();

public:
SensorBase(
const char* dev_name,
const char* data_name);

virtual ~SensorBase();

virtual int readEvents(sensors_event_t* data, int count) = 0;
virtual bool hasPendingEvents() const;
virtual int getFd() const;
virtual int setDelay(int32_t handle, int64_t ns);
virtual int enable(int32_t handle, int enabled) = 0;
};

/*****************************************************************************/

#endif // ANDROID_SENSOR_BASE_H
217 changes: 217 additions & 0 deletions libsensors/nusensors.cpp
@@ -0,0 +1,217 @@
/*
* 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.
*/

#include <hardware/sensors.h>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
#include <math.h>

#include <poll.h>
#include <pthread.h>

#include <linux/input.h>

#include <cutils/atomic.h>
#include <cutils/log.h>

#include "nusensors.h"
//#include "LightSensor.h"
//#include "ProximitySensor.h"
#include "AkmSensor.h"

/*****************************************************************************/

struct sensors_poll_context_t {
struct sensors_poll_device_t device; // must be first

sensors_poll_context_t();
~sensors_poll_context_t();
int activate(int handle, int enabled);
int setDelay(int handle, int64_t ns);
int pollEvents(sensors_event_t* data, int count);

private:
enum {
//light = 0,
//proximity = 1,
akm = 0,
numSensorDrivers,
numFds,
};

static const size_t wake = numFds - 1;
static const char WAKE_MESSAGE = 'W';
struct pollfd mPollFds[numFds];
int mWritePipeFd;
SensorBase* mSensors[numSensorDrivers];

int handleToDriver(int handle) const {
switch (handle) {
case ID_A:
case ID_M:
case ID_O:
case ID_T:
return akm;
}
return -EINVAL;
}
};

/*****************************************************************************/

sensors_poll_context_t::sensors_poll_context_t()
{
mSensors[akm] = new AkmSensor();
mPollFds[akm].fd = mSensors[akm]->getFd();
mPollFds[akm].events = POLLIN;
mPollFds[akm].revents = 0;

int wakeFds[2];
int result = pipe(wakeFds);
LOGE_IF(result<0, "error creating wake pipe (%s)", strerror(errno));
fcntl(wakeFds[0], F_SETFL, O_NONBLOCK);
fcntl(wakeFds[1], F_SETFL, O_NONBLOCK);
mWritePipeFd = wakeFds[1];

mPollFds[wake].fd = wakeFds[0];
mPollFds[wake].events = POLLIN;
mPollFds[wake].revents = 0;
}

sensors_poll_context_t::~sensors_poll_context_t() {
for (int i=0 ; i<numSensorDrivers ; i++) {
delete mSensors[i];
}
close(mPollFds[wake].fd);
close(mWritePipeFd);
}

int sensors_poll_context_t::activate(int handle, int enabled) {
int index = handleToDriver(handle);
if (index < 0) return index;
int err = mSensors[index]->enable(handle, enabled);
if (enabled && !err) {
const char wakeMessage(WAKE_MESSAGE);
int result = write(mWritePipeFd, &wakeMessage, 1);
LOGE_IF(result<0, "error sending wake message (%s)", strerror(errno));
}
return err;
}

int sensors_poll_context_t::setDelay(int handle, int64_t ns) {

int index = handleToDriver(handle);
if (index < 0) return index;
return mSensors[index]->setDelay(handle, ns);
}

int sensors_poll_context_t::pollEvents(sensors_event_t* data, int count)
{
int nbEvents = 0;
int n = 0;

do {
// see if we have some leftover from the last poll()
for (int i=0 ; count && i<numSensorDrivers ; i++) {
SensorBase* const sensor(mSensors[i]);
if ((mPollFds[i].revents & POLLIN) || (sensor->hasPendingEvents())) {
int nb = sensor->readEvents(data, count);
if (nb < count) {
// no more data for this sensor
mPollFds[i].revents = 0;
}
count -= nb;
nbEvents += nb;
data += nb;
}
}

if (count) {
// we still have some room, so try to see if we can get
// some events immediately or just wait if we don't have
// anything to return
n = poll(mPollFds, numFds, nbEvents ? 0 : -1);
if (n<0) {
LOGE("poll() failed (%s)", strerror(errno));
return -errno;
}
if (mPollFds[wake].revents & POLLIN) {
char msg;
int result = read(mPollFds[wake].fd, &msg, 1);
LOGE_IF(result<0, "error reading from wake pipe (%s)", strerror(errno));
LOGE_IF(msg != WAKE_MESSAGE, "unknown message on wake queue (0x%02x)", int(msg));
mPollFds[wake].revents = 0;
}
}
// if we have events and space, go read them
} while (n && count);

return nbEvents;
}

/*****************************************************************************/

static int poll__close(struct hw_device_t *dev)
{
sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev;
if (ctx) {
delete ctx;
}
return 0;
}

static int poll__activate(struct sensors_poll_device_t *dev,
int handle, int enabled) {
sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev;
return ctx->activate(handle, enabled);
}

static int poll__setDelay(struct sensors_poll_device_t *dev,
int handle, int64_t ns) {
sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev;
return ctx->setDelay(handle, ns);
}

static int poll__poll(struct sensors_poll_device_t *dev,
sensors_event_t* data, int count) {
sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev;
return ctx->pollEvents(data, count);
}

/*****************************************************************************/

int init_nusensors(hw_module_t const* module, hw_device_t** device)
{
int status = -EINVAL;

LOGD("init_nusensors");

sensors_poll_context_t *dev = new sensors_poll_context_t();
memset(&dev->device, 0, sizeof(sensors_poll_device_t));

dev->device.common.tag = HARDWARE_DEVICE_TAG;
dev->device.common.version = 0;
dev->device.common.module = const_cast<hw_module_t*>(module);
dev->device.common.close = poll__close;
dev->device.activate = poll__activate;
dev->device.setDelay = poll__setDelay;
dev->device.poll = poll__poll;

*device = &dev->device.common;
status = 0;
return status;
}
102 changes: 102 additions & 0 deletions libsensors/nusensors.h
@@ -0,0 +1,102 @@
/*
* 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.
*/

#ifndef ANDROID_SENSORS_H
#define ANDROID_SENSORS_H

#include <stdint.h>
#include <errno.h>
#include <sys/cdefs.h>
#include <sys/types.h>

#include <linux/input.h>

#include <hardware/hardware.h>
#include <hardware/sensors.h>

__BEGIN_DECLS

/*****************************************************************************/

int init_nusensors(hw_module_t const* module, hw_device_t** device);

/*****************************************************************************/

#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))

#define ID_A (0)
#define ID_M (1)
#define ID_O (2)
#define ID_T (3)

/*****************************************************************************/

/*
* The SENSORS Module
*/

/*****************************************************************************/

#define AKM_DEVICE_NAME "/dev/akm8976_aot"
#define LS_DEVICE_NAME "/dev/lightsensor"

#define EVENT_TYPE_ACCEL_X ABS_X
#define EVENT_TYPE_ACCEL_Y ABS_Z
#define EVENT_TYPE_ACCEL_Z ABS_Y
#define EVENT_TYPE_ACCEL_STATUS ABS_WHEEL

#define EVENT_TYPE_YAW ABS_RX
#define EVENT_TYPE_PITCH ABS_RY
#define EVENT_TYPE_ROLL ABS_RZ
#define EVENT_TYPE_ORIENT_STATUS ABS_RUDDER

#define EVENT_TYPE_MAGV_X ABS_HAT0X
#define EVENT_TYPE_MAGV_Y ABS_HAT0Y
#define EVENT_TYPE_MAGV_Z ABS_BRAKE

#define EVENT_TYPE_TEMPERATURE ABS_THROTTLE
#define EVENT_TYPE_STEP_COUNT ABS_GAS
#define EVENT_TYPE_PROXIMITY ABS_DISTANCE
#define EVENT_TYPE_LIGHT ABS_MISC

// 720 LSG = 1G
#define LSG (720.0f)


// conversion of acceleration data to SI units (m/s^2)
#define CONVERT_A (GRAVITY_EARTH / LSG)
#define CONVERT_A_X (-CONVERT_A)
#define CONVERT_A_Y (CONVERT_A)
#define CONVERT_A_Z (-CONVERT_A)

// conversion of magnetic data to uT units
#define CONVERT_M (1.0f/16.0f)
#define CONVERT_M_X (-CONVERT_M)
#define CONVERT_M_Y (-CONVERT_M)
#define CONVERT_M_Z (CONVERT_M)

#define CONVERT_O (1.0f)
#define CONVERT_O_Y (CONVERT_O)
#define CONVERT_O_P (CONVERT_O)
#define CONVERT_O_R (-CONVERT_O)

#define SENSOR_STATE_MASK (0x7FFF)

/*****************************************************************************/

__END_DECLS

#endif // ANDROID_SENSORS_H
560 changes: 24 additions & 536 deletions libsensors/sensors.c

Large diffs are not rendered by default.