sensor fwk arch

1 SensorService

整个android sensor模块的核心是SensorService,应用通过SensorManager与其交互,SensorService基本上管理sensor的所有行为,包括

  • 开关sensor,
  • 获取sensor数据给到应用,
  • 应用是否有权限获取sensor,
  • 待机后sensor的行为,
  • sensor数据和开关记录缓存,
  • 还可以在这自定义虚拟sensor,等等。

1.1 sensorService启动

  1. sensorService跑在system_server进程,
  2. SensorService需要访问pkms服务 appOpsService服务 PermissionsService 因此在它们之后启动SensorService
  3. SystemServerInitThreadPool在单独的线程中

1.1.1 java

  • zygote启动,调用SystemServer main方法,启动系统服务
  • 服务端java代码和jni c++代码都运行在系统服务进程system_server里面,system_server进程启动
    • 先加载jni生成的动态链接库 System.loadLibrary(“android_servers”), libandroid_server.so,初始化本地 Native service
    • 然后从服务的java代码生成service.jar中加载对应服务的class文件,启动服务
// ./frameworks/base/services/java/com/android/server/SystemServer.java
/**
 * The main entry point from zygote.
 */
public static void main(String[] args) {
    new SystemServer().run();
}
public final class SystemServer {
    private static final String TAG = "SystemServer";
    private void run() {
            // Initialize native services.
            System.loadLibrary("android_servers");
        // Start services.
        try {
            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
            startBootstrapServices();
            startCoreServices();
            startOtherServices();
        }
...
    
    private void startBootstrapServices() {
        // The sensor service needs access to package manager service, app ops
        // service, and permissions service, therefore we start it after them.
        mSystemServiceManager.startService(SensorService.class);
    }
}
//SensorService.java
public class SensorService extends SystemService {
    private static final String START_NATIVE_SENSOR_SERVICE = "StartNativeSensorService";
    /** Start the sensor service. This is a blocking call and can take time. */
    private static native long startSensorServiceNative(ProximityActiveListener listener);
    private static native void registerProximityActiveListenerNative(long ptr);
    private static native void unregisterProximityActiveListenerNative(long ptr);
    public SensorService(Context ctx) {
        super(ctx);
        synchronized (mLock) {
            mSensorServiceStart = SystemServerInitThreadPool.submit(() -> {
                TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
                traceLog.traceBegin(START_NATIVE_SENSOR_SERVICE);
                long ptr = startSensorServiceNative(new ProximityListenerDelegate());
                synchronized (mLock) {
                    mPtr = ptr;
                }
                traceLog.traceEnd();
            }, START_NATIVE_SENSOR_SERVICE);
        }
    }
}

1.1.2 jni

通过对JNI的了解 System.loadLibrary(“android_servers”); 会去查找libandroid_servers.so 这个库文件

cc_library_shared {
    name: "libandroid_servers",
    defaults: ["libservices.core-libs"],
    whole_static_libs: ["libservices.core"],
}
//frameworks/base/services/core/jni/onload.cpp
extern "C" jint JNI_OnLoad(JavaVM* vm, void* /* reserved */)
{
    JNIEnv* env = NULL;
    jint result = -1;

    if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
        ALOGE("GetEnv failed!");
        return result;
    }
    ALOG_ASSERT(env, "Could not retrieve the env!");
    ...
	register_android_server_sensor_SensorService(vm, env);    return JNI_VERSION_1_4;
}

//frameworks/base/services/core/jni/com_android_server_sensor_SensorService.cpp
static const JNINativeMethod methods[] = {
        {
                "startSensorServiceNative", "(L" PROXIMITY_ACTIVE_CLASS ";)J",
                reinterpret_cast(startSensorServiceNative)
        },
        {
                "registerProximityActiveListenerNative", "(J)V",
                reinterpret_cast(registerProximityActiveListenerNative)
        },
        {
                "unregisterProximityActiveListenerNative", "(J)V",
                reinterpret_cast(unregisterProximityActiveListenerNative)
         },

};

int register_android_server_sensor_SensorService(JavaVM* vm, JNIEnv* env) {
    sJvm = vm;
    jclass listenerClass = FindClassOrDie(env, PROXIMITY_ACTIVE_CLASS);
    sMethodIdOnProximityActive = GetMethodIDOrDie(env, listenerClass, "onProximityActive", "(Z)V");
    return jniRegisterNativeMethods(env, "com/android/server/sensors/SensorService", methods,
                                    NELEM(methods));
}

static jlong startSensorServiceNative(JNIEnv* env, jclass, jobject listener) {
    NativeSensorService* service = new NativeSensorService(env, listener);
    return reinterpret_cast(service);
}

NativeSensorService::NativeSensorService(JNIEnv* env, jobject listener)
      : mProximityActiveListenerDelegate(new ProximityActiveListenerDelegate(env, listener)) {
    if (base::GetBoolProperty("system_init.startsensorservice", true)) {
        sp sm(defaultServiceManager());
        mService = new SensorService();//进入到SensorService
        sm->addService(String16(SensorService::getServiceName()), mService,
                       false /* allowIsolated */, IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
    }
}

1.1.3 native (SensorService)

class SensorService :
        public BinderService<SensorService>,
        public BnSensorServer,
        protected Thread
  1. BinderService 是 Android Service 框架的主要类,是个模板类,它提供了 Service 的生命周期管理、进程间通信、请求响应处理等功能。Android 中的绝大部分 Service 都会继承此类
  2. BnSensorServer:frameworks/native/libs/sensor/include/sensor/ISensorServer.h
    和 BinderService 主要实现IPC跨进程通信,实际继承BnInterface: frameworks/native/libs/binder/include/binder/IInterface.h
  3. Thread:继承 Thread 启动 threadLoop

总结下sensorservice启动过程

  1. 系统初始化进程加载,启动SystemServer,Zygote中会执行SystemServier main方法,导致其run方法被调用;

  2. 加载本地库文件, System.loadLibrary(“android_servers”); 获取本地方法;

  3. 被加载到的JNI库文件导致JNI_Onload函数被调用;调用本地jni文件

  4. 注册本地方法jniRegisterNativeMethods 数组;

  5. 完成Java 到 C++ 函数绑定,使Java能否访问到C库中的函数;

  6. 启动startBootstrapServices();

  7. 最后调用native方法 native void startSensorService();

  8. JNI文件com_android_server_SystemServer.cpp,绑定的函数数组,由java的startSensorService方法绑定到

    android_server_SystemServer_startSensorService函数;

  9. C++函数中,start_sensor_service被调用;

  10. 调用SensorService的调用publish

  11. 创建一个Serivces,通过sm->addService 来添加到android中去; sm->addService( String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated); 其中sm是ServiceManager的引用:sp sm(defaultServiceManager());

1.2 sensorService

SensorService继承关系

Sensorservice : public BnSensorServer
BnSensorServer : public BnInterface<ISensorService>
BnInterface : public BBinder
BBinder : public IBinder
IBinder : public virtual RefBase // 对象第一次强引用时自动调用onFirstRef方法

1.2.1 onFirstRef

void SensorService::onFirstRef() {
// 在 SensorDevice 的构造函数中,会建立和hal层的连接
    SensorDevice& dev(SensorDevice::getInstance());
    //.......
    if (dev.initCheck() == NO_ERROR) {
// 通过 SensorDevice,调用 Sensor HAL 提供的 get_sensors_list 接口,获取所支持的 Sensor 信息获,调用registerSensor函数把Sensor保存起来
        sensor_t const* list;
        ssize_t count = dev.getSensorList(&list);
        //.......
            for (ssize_t i=0 ; i<count ; i++) {
            //.......
                if (useThisSensor) {
                    registerSensor( new HardwareSensor(list[i]) );
                }
            }
//SensorFusion功能,传感融合。它的主要作用就是,按照一定的算法计算系统的多个传感器对某一个值的上报的数据,得到更准确的值。
            // it's safe to instantiate the SensorFusion object here
            // (it wants to be instantiated after h/w sensors have been
            // registered)
            SensorFusion::getInstance();
//注册虚拟传感器:这些虚拟的传感器步会产生真的数据,而是通过SensorFusion功能计算得到的值,作为虚拟传感的数据。
           //虚拟sensor就是拿一个或多个物理sensor通过算法处理得到的,比如自动转屏,根据加速度算出来
           //虚拟sensor的算法一直在跑,跑在ap侧功耗高,手机厂家会实现在协处理器里边,比如枭龙845,而不是直接用谷歌在fwk实现的那套算法
                registerSensor(new RotationVectorSensor(), !needRotationVector, true);
                registerSensor(new OrientationSensor(), !needRotationVector, true);
            //.......
// 初始化一些Buffer,用他们保存sensor硬件上报的数据
            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 wp<const SensorEventConnection> [minBufferSize];
            mCurrentOperatingMode = NORMAL;
            //.......
//创建一个 Looper 和 SensorEventAckReceiver。其中 Looper 用于 enable sensor 后,进行数据的接收;而 SensorEventAckReceiver 则用于在 dispatch wake up sensor event 给上层后,接收上层返回的确认 ACK。
            mAckReceiver = new SensorEventAckReceiver(this);
            mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
//SensorService 不仅是一个服务,而且他还是一个线程,初始化工作的最后就是启动该线程执行threadLoop函数。threadLoop函数主要的工作就是,循环读取sensor硬件上传上来的数据,然后分发给应用。
            run("SensorService", PRIORITY_URGENT_DISPLAY); 
            //.......
}

1.2.3 threadLoop

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);
    //为何要这么做,再解释一下,比如说这边有vcount个虚拟的 sensor跑在framework,
    //那么比较极端的情况下每从HAL取numEventMax个数据,这边vcount个sensor会各生成numEventMax个数据,
    //而mSensorEventBuffer 最多只能容纳 MAX_RECEIVE_BUFFER_EVENT_COUNT个数据,
    //所以 numEventMax = minBufferSize / (1 + vcount);
 
    SensorDevice& device(SensorDevice::getInstance());
 
    const int halVersion = device.getHalDeviceVersion();
    do {
        //通过SensorDevice往HAL层取数据, 若没有数据的时候就一直阻塞(这个由前面说的第三方SO库实现)
        //一般在该so库的poll里边,可以采用c++标准实现的queue::pop(),来获取数据,没数据时就一直阻塞,
        //当驱动有数据上来时,另外一个线程将sensor数据往这个队列里边queue::pop就行了
        //还记得mSensorEventBuffer,sensorservice中256个sensor_event_t
        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
        // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
        // releasing the wakelock.
        bool bufferHasWakeUpEvent = false;
        for (int i = 0; i < count; i++) {
            if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
                bufferHasWakeUpEvent = true;
                break;
            }
        }
		//若有wakeup 类型sensor上报的数据就持有wakelock
        if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
            setWakeLockAcquiredLocked(true);
        }
        recordLastValueLocked(mSensorEventBuffer, count);//将事件保存下来,后面可以用dumpsys sensorservice dump出来方便分析问题
 
        // 暂时可先忽略handle virtual sensor,dynamic sensor部分不看
		
		
        // Send our events to clients. Check the state of wake lock for each client and release the
        // lock if none of the clients need it.
        bool needsWakeLock = false;
        size_t numConnections = activeConnections.size();
        for (size_t i=0 ; i < numConnections; ++i) {
            if (activeConnections[i] != 0) {
				//通过SensorEventConnection 将数据通过socket发送给应用
                activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
                        mMapFlushEventsToConnections);
                needsWakeLock |= activeConnections[i]->needsWakeLock();
                // If the connection has one-shot sensors, it may be cleaned up after first trigger.
                // Early check for one-shot sensors.
                if (activeConnections[i]->hasOneShotSensors()) {
                    cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
                            count);
                }
            }
        }
		
		//若还有wake up 类型的sensor报上来的数据的话,需要继续持有wakelock
        if (mWakeLockAcquired && !needsWakeLock) {
            setWakeLockAcquiredLocked(false);
        }
    } while (!Thread::exitPending());
 
    ALOGW("Exiting SensorService::threadLoop => aborting...");
    abort();
    return false;
}

到此,sensorservice已经启动,能够接收binder通信发过来的enable(),disable(),flush()等请求。也能够读取hal层的数据给到 应用

  1. 通过poll往hal层取sensor数据, 若没有数据的时候就一直阻塞(该阻塞功能由HAL层实现),当有数据时该函数就会返回
  2. virtual sensors 相关数据计算后上报
  3. 通过SensorEventConnection中 sendEvents 将数据给到每个应用,每个应用都有自己的SensorEventConnection

1.2.4SensorDevice

SensorDevice继承了Singleton类,设计成单例,后面要用的话用getinstance()的方式, 为何用单例?是因为sensorservice会有多个线程与vendor层交互,若用多个的话,逻辑会比较混淆,并且也没有必要,节约一点内存哈哈。

SensorDevice::SensorDevice()
        : mHidlTransportErrors(20), mRestartWaiter(new HidlServiceRegistrationWaiter()) {
 
    //通过hidl与HAL层建立连接
    if (!connectHidlService()) {
        return;
    }
 
    //获取开机时前面所说的第三方SO库注册的sensor,这个SO库一般就是直接与驱动进行通信对实际sensor进行开关和数据获取了,
	//比如高通骁龙855的sensors.ssc.so通过qmi与slpi进行通信。
	//这些sensor_t 类型的结构体,需要第三方的so库里边自己实现,每个结构体对象存储一个sensor的信息
    checkReturn(mSensors->getSensorsList(
            [&](const auto &list) {
                const size_t count = list.size();
 
                mActivationCount.setCapacity(count);
                Info model;
                for (size_t i=0 ; i < count; i++) {
                    sensor_t sensor;
                    convertToSensor(list[i], &sensor);
                    // Sanity check and clamp power if it is 0 (or close)
                    if (sensor.power < minPowerMa) {
                        ALOGE("Reported power %f not deemed sane, clamping to %f",
                              sensor.power, minPowerMa);
                        sensor.power = minPowerMa;
                    }
                    mSensorList.push_back(sensor);//将HAL层注册的sensor保存起来,具体如何注册的,后面分析sensor HAL层部分再分析
					
					//保存该sensor的handle,具体数值是在前面所说的第三方SO库决定的,一般是从1开启按顺序叠加
                    mActivationCount.add(list[i].sensorHandle, model);
 
                    checkReturn(mSensors->activate(list[i].sensorHandle, 0 /* disable */));//关闭该sensor,以防开着没用漏电
                }
            }));
 
}
 
bool SensorDevice::connectHidlService() {
    // SensorDevice will wait for HAL service to start if HAL is declared in device manifest.
    size_t retry = 10;
 
    while (retry-- > 0) {
		//......
		
        //通过hidl获取 [email protected]
        mSensors = ISensors::getService();
        if (mSensors == nullptr) {
            // no sensor hidl service found
            break;
        }
		
		//.......
    }
    return (mSensors != nullptr);
}

2 应用注册sensor流程

public class SensorActivity extends Activity implements SensorEventListener {
    private final SensorManager mSensorManager;
    private final Sensor mAccelerometer;

    public SensorActivity() {
        mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    }

    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }

    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    public void onSensorChanged(SensorEvent event) {
    }
}

3 SensorManager

3.1 java

3.1.1 getSystemService

3.1.2 getDefaultSensor

3.1.3 registerListener

3.1.4 registerListener

3.1.5 BaseEventQueue


3.2 jni

3.3 native

4 连接发送与接收

你可能感兴趣的:(android,os,java,android,开发语言)