一. 在App的使用方法
2 3 4 5 6 7 |
SensorManager sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
Sensor accSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); sensorManager.registerListener( this, accSensor, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.unregisterListener( this, accSensor); //在Listener中实现数据的监听 public void onSensorChanged(SensorEvent event) public void onAccuracyChanged(Sensor sensor, int accuracy) |
我现在要从SensorManager为入口去探究
二. SensorManager的初始化
SensorManager就是整个Sensor架构最开始的地方,所以它的初始化也是整个Sensor架构的初始化。
SensorManager在Frameworks中被继承为SystemSensorManager。
SystemSensorManager在两处被调用。
1. 在frameworks\base\core\java\android\appContextimpl.java中,供App用getSystemService()来获取服务。
2 3 4 5 6 |
registerService(SENSOR_SERVICE,
new ServiceFetcher() {
public Object createService(ContextImpl ctx) { return new SystemSensorManager(ctx.getOuterContext(), ctx.mMainThread.getHandler().getLooper()); } }); |
2. frameworks\base\services\java\com\android\server\power\PowerManagerService.java 在系统初始化时systemReady()中被调用
|
new SystemSensorManager(mContext, mHandler.getLooper());
|
SystemSensorManager构造函数
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public SystemSensorManager(Context context, Looper mainLooper) {
/* 在base/core/jni/android_hardware_SensorManager.cpp中 主要是找到Sensor类,并把类成员的jfieldID找到 */ nativeClassInit(); // initialize the sensor list final ArrayList<Sensor> fullList = sFullSensorsList; int i = 0; do { Sensor sensor = new Sensor(); /*初始化JNI的SensorManager 并通过SensorManager获取Sensor List,把List里的Sensor一个个传递上来*/ i = nativeGetNextSensor(sensor, i); if (i >= 0) { fullList.add(sensor); sHandleToSensor.append(sensor.getHandle(), sensor); } } while (i > 0); } |
nativeGetNextSensor函数
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
static jint nativeGetNextSensor(JNIEnv *env, jclass clazz, jobject sensor, jint next){
//初始化SensorManager SensorManager& mgr(SensorManager::getInstance()); Sensor const* const* sensorList; //获取Sensor List size_t count = mgr.getSensorList(&sensorList); Sensor const* const list = sensorList[next]; const SensorOffsets& sensorOffsets(gSensorOffsets); jstring name = env->NewStringUTF(list->getName().string()); jstring vendor = env->NewStringUTF(list->getVendor().string()); env->SetObjectField(sensor, sensorOffsets.name, name); //...后面的就是设置Sensor类成员了 } |
native/libs/gui/SensorManager.cpp
![](/qrcode.jpg)
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
SensorManager::SensorManager()
assertStateLocked(); } status_t SensorManager::assertStateLocked() const { if (mSensorServer == NULL) { // try for one second const String16 name( "sensorservice"); status_t err = getService(name, &mSensorServer); //注册sensorservice服务死亡通知 mDeathObserver = new DeathObserver(* const_cast<SensorManager *>( this)); mSensorServer->asBinder()->linkToDeath(mDeathObserver); //获取SensorList mSensors = mSensorServer->getSensorList(); size_t count = mSensors.size(); mSensorList = (Sensor const**)malloc(count * sizeof(Sensor*)); for (size_t i= 0 ; i<count ; i++) { mSensorList[i] = mSensors.array() + i; } } } |
native/services/sensorservice/SensorService.cpp
2 3 4 |
Vector<Sensor> SensorService::getSensorList() {
//...... return mUserSensorList; } |
mUserSensorList在onFirstRef()函数里初始化
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
void SensorService::onFirstRef() {
SensorDevice &dev(SensorDevice::getInstance()); if (dev.initCheck() == NO_ERROR) { sensor_t const *list; ssize_t count = dev.getSensorList(&list); if (count > 0) { ssize_t orientationIndex = - 1; bool hasGyro = false; uint32_t virtualSensorsNeeds = ( 1 << SENSOR_TYPE_GRAVITY) | ( 1 << SENSOR_TYPE_LINEAR_ACCELERATION) | ( 1 << SENSOR_TYPE_ROTATION_VECTOR); mLastEventSeen.setCapacity(count); for (ssize_t i = 0 ; i < count ; i++) { //把Sensor添加到SensorService的List中 registerSensor( new HardwareSensor(list[i]) ); //... 添加Sensor和Virtual Sensor //启动子线程,主要用来捕获和分发数据。后面会讲到 run( "SensorService", PRIORITY_URGENT_DISPLAY); } } |
上面的主要是SensorDevice和SensorDevice.getSensorList();
SensorDevice开始与Hardware层打交道
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
SensorDevice::SensorDevice(){
/*获取hw模块,模块ID为SENSORS_HARDWARE_MODULE_ID*/ status_t err = hw_get_module(SENSORS_HARDWARE_MODULE_ID, (hw_module_t const**)&mSensorModule); if (mSensorModule) { /*定义在hardware/sensors.h,主要是调用模块的open函数 module->methods->open(...);*/ err = sensors_open_1(&mSensorModule->common, &mSensorDevice); if (mSensorDevice) { sensor_t const* list; //再次获取sensor 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); //激活Sensor mSensorDevice->activate( reinterpret_cast< struct sensors_poll_device_t *>(mSensorDevice), list[i].handle, 0); } } } } |
SENSORS_HARDWARE_MODULE_ID模块在hardware/sensor/Sensor.c中
sensors_open_1调用了此模块的open函数
2 3 4 |
static
int open_sensors(
const
struct hw_module_t *module,
const
char *name,
struct hw_device_t **device) { return init_nusensors(module, device); } |
init_nusensors在hardware/sensor/Nusensors.cpp
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
int init_nusensors(hw_module_t
const *module, hw_device_t **device) {
sensors_poll_context_t *dev = new sensors_poll_context_t(); memset(&dev->device, 0, sizeof(sensors_poll_device_1)); //初始化hw_device_t dev->device.common.tag = HARDWARE_DEVICE_TAG; dev->device.common.version = 0; //SENSORS_DEVICE_API_VERSION_1_1; 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; dev->device.batch = poll__batch; dev->device.flush = poll__flush; *device = &dev->device.common; status = 0; return status; } |
SensorDevice然后调用sensor.cpp里的get_sensors_list
2 3 4 5 6 |
static
int sensors__get_sensors_list(
struct sensors_module_t *module,
struct sensor_t const **list) { //这个就是最低层的sensorlist *list = sSensorList; return ARRAY_SIZE(sSensorList); } |
hardware\sensor\hwmsen_chip_info.c sSensorList里包含了所有的Sensor信息
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
struct sensor_t sSensorList[MAX_NUM_SENSOR] =
{ #ifdef CUSTOM_KERNEL_ACCELEROMETER { .name = ACCELEROMETER, .vendor = ACCELEROMETER_VENDER, .version = 1, .handle = ID_ACCELEROMETER, .type = SENSOR_TYPE_ACCELEROMETER, .maxRange = ACCELEROMETER_RANGE, //32.0f, .resolution = ACCELEROMETER_RESOLUTION, //4.0f/1024.0f, .power = ACCELEROMETER_POWER, //130.0f/1000.0f, .reserved = {} }, { .name = ACCELEROMETER_1, .vendor = ACCELEROMETER_VENDER, .version = 1, .handle = ID_ACCELEROMETER, .type = SENSOR_TYPE_ACCELEROMETER, .maxRange = ACCELEROMETER_RANGE, //32.0f, .resolution = ACCELEROMETER_RESOLUTION, //4.0f/1024.0f, .power = ACCELEROMETER_POWER, //130.0f/1000.0f, .reserved = {} }, { .name = ACCELEROMETER_2, .vendor = ACCELEROMETER_VENDER, .version = 1, .handle = ID_ACCELEROMETER, .type = SENSOR_TYPE_ACCELEROMETER, .maxRange = ACCELEROMETER_RANGE, //32.0f, .resolution = ACCELEROMETER_RESOLUTION, //4.0f/1024.0f, .power = ACCELEROMETER_POWER, //130.0f/1000.0f, .reserved = {} }, #endif #ifdef CUSTOM_KERNEL_ALSPS { .name = PROXIMITY, .vendor = PROXIMITY_VENDER, .version = 1, .handle = ID_PROXIMITY, .type = SENSOR_TYPE_PROXIMITY, .maxRange = PROXIMITY_RANGE, //1.00f, .resolution = PROXIMITY_RESOLUTION, //1.0f, .power = PROXIMITY_POWER, //0.13f, .reserved = {} }, //.... }; |
SensorDevice接着调用 mSensorDevice->activate();
在这里我们先理清楚一下mSensorDevice的类型转换问题
mSensorDevice的类型为sensors_poll_device_1_t,在最后的初始化为*device = &dev->device.common; common为hw_device_t类型。dev为sensors_poll_context_t类型。
再来看看这几个类型之间的关系
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
struct sensors_poll_context_t {
struct sensors_poll_device_t device; // must be first sensors_poll_context_t(); int activate( int handle, int enabled); //... }; struct sensors_poll_device_t { struct hw_device_t common; int (*activate)( struct sensors_poll_device_t *dev, int (*setDelay)( struct sensors_poll_device_t *dev, int (*poll)( struct sensors_poll_device_t *dev, }; typedef struct sensors_poll_device_1 { union { struct sensors_poll_device_t v0; struct { struct hw_device_t common; int (*activate)( struct sensors_poll_device_t *dev, int (*setDelay)( struct sensors_poll_device_t *dev, int (*poll)( struct sensors_poll_device_t *dev, }; }; int (*batch)( struct sensors_poll_device_1* dev, int (*flush)( struct sensors_poll_device_1* dev, int handle); void (*reserved_procs[ 8])( void); } sensors_poll_device_1_t; |
sensors_poll_context_t的device和sensors_poll_device_t的common都在第一位,所以他们的指针地址都是一样的。
只要获取了首地址后,就可以通过类型的不同取到不同的值。
首先是mSensorDevice的sensors_poll_device_1_t,sensors_poll_device_1_t 的前半节成员位置分布是与 sensors_poll_context_t的一样的,所以mSensorDevice->activate调的就是初始化之后的poll__activate()。poll__activate的第一个参数又是mSensorDevice,poll__activate里又把它转换为sensors_poll_context_t,这样就可以调用sensors_poll_context_t里面的activate()函数。
sensors_poll_context_t的activate():
其中的handle是sSensorList里的handle
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
int sensors_poll_context_t::activate(
int handle,
int enabled) {
int index = handleToDriver(handle); //使能Sensor if(ID_ORIENTATION == handle) { ((AccelerationSensor*)(mSensors[accel]))->enableNoHALDataAcc(enabled); ((Hwmsen*)(mSensors[hwmsen]))->enableNoHALDataAcc(enabled); } if( NULL != mSensors[index] && index > 0 ) { ALOGD( "use new sensor index=%d, mSensors[index](%x)", index, mSensors[index]); err = mSensors[index]->enable(handle, enabled); } if(err || index< 0 ) { ALOGD( "use old sensor err(%d),index(%d) go to old hwmsen\n",err,index); // notify to hwmsen sensor to support old architecture err = mSensors[hwmsen]->enable(handle, enabled); } if (enabled && !err) { //通过管道发送唤醒消息。这里有个疑问,一初始化就把所有的Sensor setenable和wake了,不会耗电吗?不是另有其用 const char wakeMessage(WAKE_MESSAGE); int result = write(mWritePipeFd, &wakeMessage, 1); ALOGE_IF(result< 0, "error sending wake message (%s)", strerror(errno)); } return err; } |
其中的hwmsen是MTK提供的对所有的Sensor驱动进行统一管理的一个小架构。Hwmsen这个类会打开"/dev/hwmsensor"节点,访问hwmsen低层驱动,hwmsen集中了所有的sensor驱动,进行统一的管理。在sensors_poll_context_t()的构造函数中,把很多sensor类赋值给了mSensors,这里类继承了SensorBase。hardware层就是通过这些类去访问低层驱动。
三. Sensor数据的监听
这个要从App的registerListener说起。
App里getDefaultSensor根据Sensor Type从SensorList里获取出相应的Sensor传入到registerListener,先传入的是SensorManager.java的registerListener。
2 3 4 5 6 7 8 9 |
public boolean registerListener(SensorEventListener listener, Sensor sensor,
int rateUs) {
return registerListener(listener, sensor, rateUs, null); } public boolean registerListener(SensorEventListener listener, Sensor sensor, int rateUs, Handler handler) { int delay = getDelay(rateUs); return registerListenerImpl(listener, sensor, delay, handler, 0, 0); } |
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
protected boolean registerListenerImpl(SensorEventListener listener, Sensor sensor,
int delayUs, Handler handler, int maxBatchReportLatencyUs, int reservedFlags) { SensorEventQueue queue = mSensorListeners.get(listener); //以前没有添加过的Listener,走这里 if (queue == null) { //获取主线程的Looper Looper looper = (handler != null) ? handler.getLooper() : mMainLooper; //新建一个SensorEventQueue queue = new SensorEventQueue(listener, looper, this); //把Sensor添加进这个Queue if (!queue.addSensor(sensor, delayUs, maxBatchReportLatencyUs, reservedFlags)) { queue.dispose(); return false; } mSensorListeners.put(listener, queue); return true; } else { return queue.addSensor(sensor, delayUs, maxBatchReportLatencyUs, reservedFlags); } } |
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public SensorEventQueue(SensorEventListener listener, Looper looper,
SystemSensorManager manager) { super(looper, manager); } BaseEventQueue(Looper looper, SystemSensorManager manager) { //创建Native层的EventQueue nSensorEventQueue = nativeInitBaseEventQueue( this, looper.getQueue(), mScratch); } /* nativeInitBaseEventQueue在native层对应的是nativeInitSensorEventQueue 在Frameworks/base/core/jni/android_hardware_SensorManager.cpp */ static jint nativeInitSensorEventQueue(JNIEnv *env, jclass clazz, jobject eventQ, jobject msgQ, jfloatArray scratch) { SensorManager& mgr(SensorManager::getInstance()); //真正创建SensorEventQueue sp<SensorEventQueue> queue(mgr.createEventQueue()); sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, msgQ); //Receiver继承LooperCallback,主要用于数据的Poll。 sp<Receiver> receiver = new Receiver(queue, messageQueue, eventQ, scratch); } |
2 3 4 5 6 7 8 9 10 11 |
sp<SensorEventQueue> SensorManager::createEventQueue() {
sp<SensorEventQueue> queue; //通过SensorServer创建一个Connection sp<ISensorEventConnection> connection = mSensorServer->createSensorEventConnection(); //通过这个Connection创建一个SensorEventQueue queue = new SensorEventQueue(connection); return queue; } |
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
sp<ISensorEventConnection> SensorService::createSensorEventConnection() {
uid_t uid = IPCThreadState::self()->getCallingUid(); sp<SensorEventConnection> result( new SensorEventConnection( this, uid)); return result; } SensorService::SensorEventConnection::SensorEventConnection( const sp<SensorService>& service, uid_t uid){ const SensorDevice& device(SensorDevice::getInstance()); //这个VERSION在hardware/sensor/Sensor.c的sensor_module_t里 if (device.getHalDeviceVersion() >= SENSORS_DEVICE_API_VERSION_1_1) { // Increase socket buffer size to 1MB for batching capabilities. mChannel = new BitTube(service->mSocketBufferSize); } else { //代码里的VERSION是1.0 mChannel = new BitTube(SOCKET_BUFFER_SIZE_NON_BATCHED); } } |
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
BitTube::BitTube(size_t bufsize)
: mSendFd(- 1), mReceiveFd(- 1) { init(bufsize, bufsize); } void BitTube::init(size_t rcvbuf, size_t sndbuf) { int sockets[ 2]; if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets) == 0) { size_t size = DEFAULT_SOCKET_BUFFER_SIZE; setsockopt(sockets[ 0], SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)); setsockopt(sockets[ 1], SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf)); // sine we don't use the "return channel", we keep it small... setsockopt(sockets[ 0], SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)); setsockopt(sockets[ 1], SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)); fcntl(sockets[ 0], F_SETFL, O_NONBLOCK); fcntl(sockets[ 1], F_SETFL, O_NONBLOCK); //这里主要是初始化mReceiveFd和mSendFd,用来后面的消息和数据的传递 mReceiveFd = sockets[ 0]; mSendFd = sockets[ 1]; } else { mReceiveFd = -errno; ALOGE( "BitTube: pipe creation failed (%s)", strerror(-mReceiveFd)); } } |
回到createEventQueue(),new SensorEventQueue(connection);
2 3 4 |
SensorEventQueue::SensorEventQueue(
const sp<ISensorEventConnection>& connection)
: mSensorEventConnection(connection), mRecBuffer( NULL), mAvailable( 0), mConsumed( 0) { mRecBuffer = new ASensorEvent[MAX_RECEIVE_BUFFER_EVENT_COUNT]; } |
这里android_hardware_SensorManager.cpp的nativeInitSensorEventQueue(),createEventQueue已经创建完。接下来创建了一个messageQueue。把SensorEventQueue和MessageQueue一起传给了Receiver,这个Receiver继承于LooperCallback。那这些类之间有什么联系呢。
写过APP的就都对Handler,Mesg和Looper有一些了解。而这些的底层实现就会刚才提到的这几个类有关,Android用此来实现进程间通信。这里简要说明:
MessageQueue是一个消息队列,用于存放消息。
Looper相当于一个消息管理者,它管理着队列里的消息进出,分发。它会把队列里的消息分发给相应的处理者。
整个进程间通信间通信用的是poll相关的FD来实现,此机制还提供了一个addFd接口。些接口传入了一个fd和一个LooperCallback,如果有消息过来,就会调用LooperCallback。
在Receiver的onFirstRef()
2 3 4 5 6 7 |
virtual
void onFirstRef() {
LooperCallback::onFirstRef(); //mSensorQueue->getFd(),得到的是BitTube里的mReceiveFd。 //这里开始监听mReceiveFd。如果有消息过来则调用handleEvent mMessageQueue->getLooper()->addFd(mSensorQueue->getFd(), 0, ALOOPER_EVENT_INPUT, this, mSensorQueue.get()); } |
|
queue.addSensor(sensor, delayUs, maxBatchReportLatencyUs, reservedFlags)
|
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
status_t SensorService::enable(
const sp<SensorEventConnection>& connection,
int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags){ //mSensorMap在registerSensor里初始化。 //这个获取出来的sensor在registerSensor的时候就与SensorDevice绑定 //即调用这个sensor里的函数就相当于调用SensorDevice里的函数 SensorInterface* sensor = mSensorMap.valueFor(handle); rec = new SensorRecord(connection); //把相应的Sensor handle(即Sensor Type)加入到activesSensor mActiveSensors.add(handle, rec); //把handle与connection绑定 if (connection->addSensor(handle)) { BatteryService::enableSensor(connection->getUid(), handle); if (mActiveConnections.indexOf(connection) < 0) { //并把connection加入到ActiveConnection的队列里 mActiveConnections.add(connection); } } status_t err = sensor->batch(connection.get(), handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs); if (err == NO_ERROR) { connection->setFirstFlushPending(handle, true); status_t err_flush = sensor->flush(connection.get(), handle); // Flush may return error if the sensor is not activated or the underlying h/w sensor does // not support flush. if (err_flush != NO_ERROR) { connection->setFirstFlushPending(handle, false); } } //真正启动Sensor sensor->activate(connection.get(), true); } |
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
bool SensorService::threadLoop(){
sensors_event_t buffer[minBufferSize]; do { count = device.poll(buffer, numEventMax); //我们现在的机器没有虚拟传感器,所以忽略了虚拟传感器部分。 //现在的版本为1.0,所以不会跑这里 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) { } // 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); // Some sensors need to be auto disabled after the trigger cleanupAutoDisabledSensor(connection, buffer, count); } } // We have read the data, upper layers should hold the wakelock. if (wakeLockAcquired) release_wake_lock(WAKE_LOCK_NAME); } while (count >= 0 || Thread::exitPending()); } |
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
int sensors_poll_context_t::pollEvents(sensors_event_t* data,
int count){
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())) { //如果有数据就调用sensor的readEvents 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) { n = poll(mPollFds, numFds, nbEvents ? 0 : - 1); } // if we have events and space, go read them } while (n && count); } |
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
int Hwmsen::readEvents(sensors_event_t* data,
int count){
//读取input数据 ssize_t n = mInputReader.fill(mdata_fd); int numEventReceived = 0; input_event const* event; while (count && mInputReader.readEvent(&event)) { int type = event->type; if (type == EV_REL) { processEvent(event->code, event->value); int64_t time = timevalToNano(event->time); for (i= 0 ; count && i<MAX_ANDROID_SENSOR_NUM ; i++) { if (mPendingMask & ( 1<<i)) { mPendingMask &= ~( 1<<i); *data++ = mPendingEvents[i]; count--; numEventReceived++; } } } mInputReader.next(); } return numEventReceived; } void Hwmsen::processEvent( int code, int value) { hwm_trans_data sensors_data; sensors_data.date_type = value; //set flag to read specified sensor //真正获取Sensor Data err = ioctl(dev_fd, HWM_IO_GET_SENSORS_DATA, &sensors_data); for(i = 0; i < MAX_ANDROID_SENSOR_NUM; i++) { //根据不同的Snesor类型处理数据 switch (i) { case ID_ORIENTATION: break; case ID_MAGNETIC: break; case ID_ACCELEROMETER: mPendingMask |= 1<<Accelerometer; mPendingEvents[Accelerometer].type = SENSOR_TYPE_ACCELEROMETER; mPendingEvents[Accelerometer].sensor = sensors_data.data[ID_ACCELEROMETER].sensor; mPendingEvents[Accelerometer].acceleration.status = sensors_data.data[ID_ACCELEROMETER].status; mPendingEvents[Accelerometer].acceleration.v[ 0] = ( float)sensors_data.data[ID_ACCELEROMETER].values[ 0]; mPendingEvents[Accelerometer].acceleration.v[ 1] = ( float)sensors_data.data[ID_ACCELEROMETER].values[ 1]; mPendingEvents[Accelerometer].acceleration.v[ 2] = ( float)sensors_data.data[ID_ACCELEROMETER].values[ 2]; mPendingEvents[Accelerometer].acceleration.v[ 0]/=sensors_data.data[ID_ACCELEROMETER].value_divide; mPendingEvents[Accelerometer].acceleration.v[ 1]/=sensors_data.data[ID_ACCELEROMETER].value_divide; mPendingEvents[Accelerometer].acceleration.v[ 2]/=sensors_data.data[ID_ACCELEROMETER].value_divide; mPendingEvents[Accelerometer].timestamp = sensors_data.data[ID_ACCELEROMETER].time; //ALOGE("[ID_ACCELEROMETER](%f,%f,%f) \r\n",mPendingEvents[Accelerometer].acceleration.v[0],mPendingEvents[Accelerometer].acceleration.v[1],mPendingEvents[Accelerometer].acceleration.v[2]); break; case ID_GYROSCOPE: break; case ID_PROXIMITY: break; case ID_LIGHT: break; } } } |
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
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; //这里传入的scratch为空 if (scratch) { } else { scratch = const_cast<sensors_event_t *>(buffer); count = numEvents; } // Send pending flush events (if any) before sending events from the cache. { ASensorEvent flushCompleteEvent; flushCompleteEvent.type = SENSOR_TYPE_META_DATA; flushCompleteEvent.sensor = 0; Mutex::Autolock _l(mConnectionLock); // Loop through all the sensors for this connection and check if there are any pending // flush complete events to be sent. for (size_t i = 0; i < mSensorInfo.size(); ++i) { FlushInfo& flushInfo = mSensorInfo.editValueAt(i); while (flushInfo.mPendingFlushEventsToSend > 0) { flushCompleteEvent.meta_data.sensor = mSensorInfo.keyAt(i); ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1); if (size < 0) { // ALOGW("dropping %d events on the floor", count); countFlushCompleteEventsLocked(scratch, count); return size; } ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ", flushCompleteEvent.meta_data.sensor); flushInfo.mPendingFlushEventsToSend--; } } } // Early return if there are no events for this connection. if (count == 0) { return status_t(NO_ERROR); } //把数据发送出去 // NOTE: ASensorEvent and sensors_event_t are the same type ssize_t size = SensorEventQueue::write(mChannel, reinterpret_cast<ASensorEvent const*>(scratch), count); } |
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
virtual
int handleEvent(
int fd,
int events,
void* data) {
JNIEnv* env = AndroidRuntime::getJNIEnv(); sp<SensorEventQueue> q = reinterpret_cast<SensorEventQueue *>(data); ssize_t n; ASensorEvent buffer[ 16]; while ((n = q->read(buffer, 16)) > 0) { for ( int i= 0 ; i<n ; i++) { if (buffer[i].type == SENSOR_TYPE_STEP_COUNTER) { // step-counter returns a uint64, but the java API only deals with floats float value = float(buffer[i].u64.step_counter); env->SetFloatArrayRegion(mScratch, 0, 1, &value); } else { env->SetFloatArrayRegion(mScratch, 0, 16, buffer[i].data); } if (buffer[i].type == SENSOR_TYPE_META_DATA) { // This is a flush complete sensor event. Call dispatchFlushCompleteEvent // method. env->CallVoidMethod(mReceiverObject, gBaseEventQueueClassInfo.dispatchFlushCompleteEvent, buffer[i].meta_data.sensor); } else { //调用了SystemSensorManager.ava的dispatchSensorEvent函数, //dispatchSensorEvent又调用了Listener.onSensorChanged把数据传到App层 env->CallVoidMethod(mReceiverObject, gBaseEventQueueClassInfo.dispatchSensorEvent, buffer[i].sensor, mScratch, buffer[i].vector.status, buffer[i].timestamp); } } } } |