Android9.0源码学习-Sensor Framework

Posted Dufre.WC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android9.0源码学习-Sensor Framework相关的知识,希望对你有一定的参考价值。

文章目录


在之前的学习中, Android Sensor概述介绍了常用传感器的功能,测量值的含义,测量原理等等。 Android Sensor应用介绍了app如何得到Sensor的数值。那么接下来就应该思考应用层是如何得到硬件测量的数值,传感器的数值又是如何一步一步上传至应用层的。

FileList

Framework(/frameworks/base/core/java/android/hardware/)

  • SensorManager.java:SDK接口,封装了Sensor相关的API,提供给APP层使用。
  • SystemSensorManager.java:继承于SensorManager,SensorManager的实现类,负责与系统Sensor的联系。
  • Sensor.java:代表一个Sensor类
  • SensorEvent.java:代表一个SensorEvent类
  • SensorEventListener.java:用于接收传感器事件的Interface

JNI(/framework/base/core/jni)

  • android_hardware_SensorManager.cpp:负责Java层和Native层的通信

Native Framework

  • Client(/framework/native/lib/sensor)
    • SensorManager.cpp:SensorManager的Native层,负责与SensorService的通信
    • SensorEventQueue.cpp:消息队列
    • Sensor.cpp:Sensor的native层
    • ISensorServer.cpp:SensorServer在客户端接口
    • ISensorEventConnection.cpp:SensorEventConnection在客户端接口
    • BitTube.cpp:单向字节管道,提供进程间单向数据通信功能。
  • Server(/framework/native/services/sensorservice)
    • SensorDevice.cpp:负责管理和维护系统中所有的Sensor,封装了Sensor的使能,配置,数据读取等功能。
    • SensorInterface.cpp:服务端Sensor接口
    • SensorService.cpp:是整个Android Sensor Framework最核心的模块,它实现了主要的Sensor控制流和数据流,完成Sensor的参数配置,数据分发
    • SensorEventConnection.cpp:Sensor的数据传输通道,当Client开始监听某一个Sensor时,一个对应的SensorEventConnection将会被创建,Server端在接收到Sensor数据后,通过写入到SensorEventConnection传递给Client端。

Questions

在Framework的学习中,我们需要搞清楚以下几个问题?

  • APP层的控制指令是怎样一层一层下发到Framework层和HAL层?
  • sensor采集到的数据又是怎样一层一层传到APP层?
  • Client端和Server端又是怎样交互的,数据是如何通讯的?
  • 当系统第一次创建SensorService时,SensorService做了哪些初始化的工作?

SensorService初始化

SystemServer的main函数,会调用startSensorService(),从而创建第一个SensorService实例。当SensorService第一个实例创建时,其onFirstRef()接口会被调用。

onFirstRef()做了这么以下几个工作:

  • 创建SensorDevice的实例(SensorDevice& dev(SensorDevice::getInstance());),并且是单例类
    • connectHidlService()
      • mSensors = ISensors::getService()
        • Sensors::Sensors()
          • hw_get_module()加载Sensor HAL的动态库
          • sensors_open_1()执行Sensor HAL的初始化
    • 初始化mSensorListVector<sensor_t> mSensorList
    • mSensors->activate()
  • 通过dev获取SensorList(list
  • registerSensor
  • 创建Looper(mLooper = new Looper(false)),用于enable sensor后,进行数据的接收
  • 创建SensorEventAckReceiver(mAckReceiver = new SensorEventAckReceiver(this)):用于在dispatch wake up sensor event给上层后,接收上层返回的确认ACK。

registerListener流程分析

APP

下面的代码是在Android官网提供的APP获取light sensor数据的代码段,这里在获取SensorManager和Sensor后,会调用sensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);注册。

public class SensorActivity extends Activity implements SensorEventListener 
    private SensorManager sensorManager;
    private Sensor mLight;

    @Override
    public final void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    

    @Override
    public final void onAccuracyChanged(Sensor sensor, int accuracy) 
        // Do something here if sensor accuracy changes.
    

    @Override
    public final void onSensorChanged(SensorEvent event) 
        // The light sensor returns a single value.
        // Many sensors return 3 values, one for each axis.
        float lux = event.values[0];
        // Do something with this sensor value.
    

    @Override
    protected void onResume() 
        super.onResume();
        sensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
    

    @Override
    protected void onPause() 
        super.onPause();
        sensorManager.unregisterListener(this);
    

Framework

Java

在java层的调用顺序为
SensorManager.java

  • registerListener()
    • registerListenerImpl()

SystemSensorManager.java

  • registerListenerImpl()

registerListenerImpl()会维护一个mSensorListeners的HashMap(HashMap<SensorEventListener, SensorEventQueue> mSensorListeners)。

  • queue.addSensor()SensorEventQueue queue
    • mActiveSensors.put(handle, true)handle = snesor.getHandle()
    • enableSensor()
      • nativeEnableSensor()到这里会通过JNI去call到Native层

/frameworks/base/core/java/android/hardware/SystemSensorManager.java

    @Override
    protected boolean registerListenerImpl(SensorEventListener listener, Sensor sensor,
            int delayUs, Handler handler, int maxBatchReportLatencyUs, int reservedFlags) 
        if (listener == null || sensor == null) 
            Log.e(TAG, "sensor or listener is null");
            return false;
        
        // Trigger Sensors should use the requestTriggerSensor call.
        if (sensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) 
            Log.e(TAG, "Trigger Sensors should use the requestTriggerSensor.");
            return false;
        
        if (maxBatchReportLatencyUs < 0 || delayUs < 0) 
            Log.e(TAG, "maxBatchReportLatencyUs and delayUs should be non-negative");
            return false;
        
        if (mSensorListeners.size() >= MAX_LISTENER_COUNT) 
            throw new IllegalStateException("register failed, "
                + "the sensor listeners size has exceeded the maximum limit "
                + MAX_LISTENER_COUNT);
        

        // Invariants to preserve:
        // - one Looper per SensorEventListener
        // - one Looper per SensorEventQueue
        // We map SensorEventListener to a SensorEventQueue, which holds the looper
        synchronized (mSensorListeners) 
            SensorEventQueue queue = mSensorListeners.get(listener);
            if (queue == null) 
                Looper looper = (handler != null) ? handler.getLooper() : mMainLooper;
                final String fullClassName =
                        listener.getClass().getEnclosingClass() != null
                            ? listener.getClass().getEnclosingClass().getName()
                            : listener.getClass().getName();
                queue = new SensorEventQueue(listener, looper, this, fullClassName);
                if (!queue.addSensor(sensor, delayUs, maxBatchReportLatencyUs)) 
                    queue.dispose();
                    return false;
                
                mSensorListeners.put(listener, queue);
                return true;
             else 
                return queue.addSensor(sensor, delayUs, maxBatchReportLatencyUs);
            
        
    

Native

Client

通过JNI,java层的enableSensor()会call到SensorEventQueue.cpp的enableSensor(),到这里就要去通过mSensorEventConnectionconst sp<ISensorEventConnection>)去call到Server端了。

/frameworks/native/libs/sensor/SensorEventQueue.cpp

status_t SensorEventQueue::enableSensor(Sensor const* sensor, int32_t samplingPeriodUs) const 
    return mSensorEventConnection->enableDisable(sensor->getHandle(), true,
                                                 us2ns(samplingPeriodUs), 0, 0);

/frameworks/native/libs/sensor/ISensorEventConnection.cpp

    virtual status_t enableDisable(int handle, bool enabled, nsecs_t samplingPeriodNs,
                                   nsecs_t maxBatchReportLatencyNs, int reservedFlags)
    
        Parcel data, reply;
        data.writeInterfaceToken(ISensorEventConnection::getInterfaceDescriptor());
        data.writeInt32(handle);
        data.writeInt32(enabled);
        data.writeInt64(samplingPeriodNs);
        data.writeInt64(maxBatchReportLatencyNs);
        data.writeInt32(reservedFlags);
        remote()->transact(ENABLE_DISABLE, data, &reply);
        return reply.readInt32();
    

Server

/frameworks/native/services/sensorservice/SensorEventConnection.cpp

status_t SensorService::SensorEventConnection::enableDisable(
        int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
        int reservedFlags)

    status_t err;
    if (enabled) 
        err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
                               reservedFlags, mOpPackageName);

     else 
        err = mService->disable(this, handle);
    
    return err;

在Server端是调用到了SensorService.cpp的enable(),它获取了sensor在HAL层的实例,

  • sensor->batch()
  • sensor->activate()

/frameworks/native/services/sensorservice/SensorService.cpp

status_t SensorService::enable(const sp<SensorEventConnection>& connection,
        int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
        const String16& opPackageName) 
    if (mInitCheck != NO_ERROR)
        return mInitCheck;

    sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
    if (sensor == nullptr ||
        !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) 
        return BAD_VALUE;
    

    Mutex::Autolock _l(mLock);
    if (mCurrentOperatingMode != NORMAL
           && !isWhiteListedPackage(connection->getPackageName())) 
        return INVALID_OPERATION;
    

    SensorRecord* rec = mActiveSensors.valueFor(handle);
    if (rec == 0) 
        rec = new SensorRecord(connection);
        mActiveSensors.add(handle, rec);
        if (sensor->isVirtual()) 
            mActiveVirtualSensors.emplace(handle);
        
     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 if it's not a
            // "continuous" sensor.
            if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) 
                // NOTE: The wake_up flag of this event may get set to
                // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.

                auto logger = mRecentEvent.find(handle);
                if (logger != mRecentEvent.end()) 
                    sensors_event_t event;
                    // It is unlikely that this buffer is empty as the sensor is already active.
                    // One possible corner case may be two applications activating an on-change
                    // sensor at the same time.
                    if(logger->second->populateLastEvent(&event)) 
                        event.sensor = handle;
                        if (event.version == sizeof(sensors_event_t)) 
                            if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) 
                                setWakeLockAcquiredLocked(true);
                            
                            connection->sendEvents(&event, 1, NULL);
                            if (!connection->needsWakeLock() && mWakeLockAcquired) 
                                checkWakeLockStateLocked();
                            
                        
                    
                
            
        
    

    if (connection->addSensor(handle)) 
        BatteryService::enableSensor(connection->getUid(), 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);
        
     else 
        ALOGW("sensor %08x already enabled in connection %p (ignoring)",
            handle, connection.get());
    

    // Check maximum delay for the sensor.
    nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
    if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) 
        samplingPeriodNs = maxDelayNs;
    

    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
    if (samplingPeriodNs < minDelayNs) 
        samplingPeriodNs = minDelayNs;
    

    ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
                                "rate=%" PRId64 " timeout== %" PRId64"",
             handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);

    status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
                                 maxBatchReportLatencyNs);

    // Call flush() before calling activate() on the sensor. Wait for a first
    // flush complete event before sending events on this connection. Ignore
    // one-shot sensors which don't support flush(). Ignore on-change sensors
    // to maintain the on-change logic (any on-change events except the initial
    // one should be trigger by a change in value). Also if this sensor isn't
    // already active, don't call flush().
    if (err == NO_ERROR &&
            sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
            rec->getNumConnections() > 1) 
        connection->setFirstFlushPending(handle, true);
        status_t err_flush = sensor->flush(connection.get(), handle);
        // Flush may return error if the underlying h/w sensor uses an older HAL.
        if (err_flush == NO_ERROR) 
            rec->addPendingFlushConnection(connection.get());
         else 
            connection->setFirstFlushPending(handle, false);
        
    

    if (err == NO_ERROR) 
        ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
        err = sensor->activate(connection.get(), true);
    

    if (err == NO_ERROR) 
        connection->updateLooperRegistration(mLooper);

        mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
                SensorRegistrationInfo(handle, connection->getPackageName(),
                                       samplingPeriodNs, maxBatchReportLatencyNs, true);
        mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
    

    if (err != NO_ERROR) 
        // batch/activate has failed, reset our state.
        cleanupWithoutDisableLocked(connection, handle);
    
    return err;

How the app get sensor data

Server

接下来分析,数据是如何传递到APP的,刚才有讲到在SensorService的onFirstRef()函数中,会new一个Looper(),我们来看看这里面做了什么。

  • SensorDevice& device(SensorDevice::getInstance())
  • device.poll()轮询,获取SensorEventBuffer
  • recordLastValueLocked(mSensorEventBuffer, count)记录前几次的数据
  • handle virtual sensors
  • activeConnections[i]->sendEvents()发送events到客户端

这里activeConnections是一个SensorEventConnection数组,因此它调用了SensorEventConnectionsendEvents()

/frameworks/native/services/sensorservice/SensorService.cpp

bool SensorService::threadLoop() 
    ALOGD("nuSensorService thread starting...");

    // each virtual sensor could generate an event per "real" event, that's why we need to size
    // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.  in practice, this is too
    // aggressive, but guaranteed to be enough.
    const size_t vcount = mSensors.getVirtualSensors().size();
    const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
    const size_t numEventMax = minBufferSize / (1 + vcount);

    SensorDevice& device(SensorDevice::getInstance());

    const int halVersion = device.getHalDeviceVersion();
    do 
        ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
        if (count < 0) 
            ALOGE("sensor poll failed (%s)", strerror(-count));
            break;
        

        // Reset sensors_event_t.flags to zero for all events in the buffer.
        for (int i = 0; i < count; i++) 
             mSensorEventBuffer[i].flags = 0;
        

        // Make a copy of the connection vector as some connections may be removed during the course
        // of this loop (especially when one-shot sensor events are present in the sensor_event
        // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
        // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
        // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
        // strongPointers to a vector before the lock is acquired.
        SortedVector< sp<SensorEventConnection> > activeConnections;
        populateActiveConnections(&activeConnections);

        Mutex::Autolock _l(mLock);
        // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
        // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
        // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should<

以上是关于Android9.0源码学习-Sensor Framework的主要内容,如果未能解决你的问题,请参考以下文章

android9.0 UsbService源码解析

android9.0 UsbService源码解析

android9.0 UsbService源码解析

android9.0 UsbManager源码解析

android9.0 UsbManager源码解析

android9.0 UsbManager源码解析