RK 传感器调用流程 从JNI 到 kernel driver

本文详细解析Android传感器从JNI层到Kernel驱动的调用流程,包括应用开发步骤、HAL层的传感器设备实例化、传感器列表获取、Kernel驱动的数据上报等关键环节,深入探讨了传感器数据在系统中的传递过程。
摘要由CSDN通过智能技术生成
  • 由 b178903294创建, 最后修改于3月 27, 2020 

一、应用开发五步曲

(1)   获取传感器管理器对象;

mSensorManager =(SensorManager) getSystemService(SENSOR_SERVICE);

 

 

(2)   获取传感器对象;

mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);

 

(3)  定义事件监听器;

private final SensorEventListener mProximitySensorListener = new SensorEventListener() {

        @Override

        public void onSensorChanged(SensorEvent event) {

            if (mProximitySensorEnabled) {

                final long time = SystemClock.uptimeMillis();

                final float distance = event.values[0];

                // do something

            }

        }

 

(4)   注册事件监听器;

mSensorManager.registerListener(mProximitySensorListener, mProximitySensor,

                    proximitySensorRate * 1000, mHandler);

 

(5)   卸载事件监听器;

mSensorManager.unregisterListener(mProximitySensorListener);

 

 

二、流程框架

各部分之间架构图如下:

1)SystemServer.java所在目录frameworks/base/services/java/com/android/server

 

public final class SystemServer {

    ...

        private void run() {

        // If a device's clock is before 1970 (before 0), a lot of

        // APIs crash dealing with negative numbers, notably

        // java.io.File#setLastModified, so instead we fake it and

        // hope that time from cell towers or NTP fixes it shortly.

        ...

        nativeInit();

        ...

        }

        ...

}

我们主要看nativeInit()方法,这个方法在哪里定义呢?
在framework下SystemServer的native层定义。

2)com_android_server_SystemServer.cpp文件( frameworks/base/services/core/jni )

namespace android {

  

static void android_server_SystemServer_nativeInit(JNIEnv* env, jobject clazz) {

    char propBuf[PROPERTY_VALUE_MAX];

    property_get("system_init.startsensorservice", propBuf, "1");

    if (strcmp(propBuf, "1") == 0) {

        // Start the sensor service

        SensorService::instantiate();

    }

}

  

/*

 * JNI registration.

 */

static JNINativeMethod gMethods[] = {

    /* name, signature, funcPtr */

    "nativeInit""()V", (void*) android_server_SystemServer_nativeInit },

};

  

int register_android_server_SystemServer(JNIEnv* env)

{

    return jniRegisterNativeMethods(env, "com/android/server/SystemServer",

            gMethods, NELEM(gMethods));

}

};

nativeInit()方法中调用了SensorService::instantiate()接口初始化了一个实例。
3)通过frameworks/native/services/sensorservice/SensorService.h中SensorService的定义得知其继承于BinderService,我们看BinderService中该方法的实现:

class BinderService

{

public:

    static status_t publish(bool allowIsolated = false) {

        sp<IServiceManager> sm(defaultServiceManager());

        return sm->addService(

                String16(SERVICE::getServiceName()),

                new SERVICE(), allowIsolated);

    }  

  

    static void publishAndJoinThreadPool(bool allowIsolated = false) {

        publish(allowIsolated);

        joinThreadPool();

    }  

  

    static void instantiate() { publish(); }

  

    static status_t shutdown() { return NO_ERROR; }

  

private:

...

}

调用了静态的publish()方法:
其实就是向ServiceManager注册SensorService,add的service名称为sensor service,后续会调用SensorService::onFirstRef()方法,开始一系列的初始化。

4)onFirstRef()方法。

void SensorService::onFirstRef()

{

    ALOGD("nuSensorService starting...");

  

    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++) {

                registerSensor( new HardwareSensor(list[i]) );

                switch (list[i].type) {

                    case SENSOR_TYPE_ORIENTATION:

                        orientationIndex = i;

                        break;

                    case SENSOR_TYPE_GYROSCOPE:

                    case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:

                        hasGyro = true;

                        break;

                    case SENSOR_TYPE_GRAVITY:

                    case SENSOR_TYPE_LINEAR_ACCELERATION:

                    case SENSOR_TYPE_ROTATION_VECTOR:

                        virtualSensorsNeeds &= ~(1<<list[i].type);

                        break;

                }

            }

  

            // it's safe to instantiate the SensorFusion object here

            // (it wants to be instantiated after h/w sensors have been

            // registered)

            const SensorFusion& fusion(SensorFusion::getInstance());

  

            // build the sensor list returned to users

            mUserSensorList = mSensorList;

  

            if (hasGyro) {

                Sensor aSensor;

  

                // Add Android virtual sensors if they're not already

                // available in the HAL

  

                aSensor = registerVirtualSensor( new RotationVectorSensor() );

                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {

                    mUserSensorList.add(aSensor);

                }

  

                aSensor = registerVirtualSensor( new GravitySensor(list, count) );

                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {

                    mUserSensorList.add(aSensor);

                }

  

                aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );

                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {

                    mUserSensorList.add(aSensor);

                }

  

                aSensor = registerVirtualSensor( new OrientationSensor() );

                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {

                    // if we are doing our own rotation-vector, also add

                    // the orientation sensor and remove the HAL provided one.

                    mUserSensorList.replaceAt(aSensor, orientationIndex);

                }

  

                // virtual debugging sensors are not added to mUserSensorList

                registerVirtualSensor( new CorrectedGyroSensor(list, count) );

                registerVirtualSensor( new GyroDriftSensor() );

            }

  

            // debugging sensor list

            mUserSensorListDebug = mSensorList;

  

            // Check if the device really supports batching by looking at the FIFO event

            // counts for each sensor.

            bool batchingSupported = false;

            for (int i = 0; i < mSensorList.size(); ++i) {

                if (mSensorList[i].getFifoMaxEventCount() > 0) {

                    batchingSupported = true;

                    break;

                }

            }

  

            if (batchingSupported) {

                // Increase socket buffer size to a max of 100 KB for batching capabilities.

                mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;

            else {

                mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;

            }

  

            // Compare the socketBufferSize value against the system limits and limit

            // it to maxSystemSocketBufferSize if necessary.

            FILE *fp = fopen("/proc/sys/net/core/wmem_max""r");

            char line[128];

            if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {

                line[sizeof(line) - 1] = '\0';

                size_t maxSystemSocketBufferSize;

                sscanf(line, "%zu", &maxSystemSocketBufferSize);

                if (mSocketBufferSize > maxSystemSocketBufferSize) {

                    mSocketBufferSize = maxSystemSocketBufferSize;

                }

            }

            if (fp) {

                fclose(fp);

            }

  

            mWakeLockAcquired = false;

            mLooper = new Looper(false);

            const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;

            mSensorEventBuffer = new sensors_event_t[minBufferSize];

            mSensorEventScratch = new sensors_event_t[minBufferSize];

            mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];

  

            mAckReceiver = new SensorEventAckReceiver(this);

            mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);

            mInitCheck = NO_ERROR;

            run("SensorService", PRIORITY_URGENT_DISPLAY);

        }

    }

}

 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  HAL  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值