我是靠谱客的博主 甜美未来,最近开发中收集的这篇文章主要介绍android sensor 是怎样获得sensorlist的何时启动的SensorServiceSensorService的实例化何时创建的SensorService的Client:SystemSensorService创建SensorManager怎样根据type找到Sensor frameworks/base/services/core/java/com/android/server/power/PowerManagerService.javaframeworks/base/core/jn,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

何时启动的SensorService

当然是SensorService启动后才能得到Sensor信息,Sensor信息的建立是在实例化SensorService得到的.


frameworks/base/services/java/com/android/server/SystemServer.java
/**
* Starts the small tangle of critical services that are needed to get the system off the
* ground.  These services have complex mutual dependencies which is why we initialize them all
* in one place here.  Unless your service is also entwined in these dependencies, it should be
* initialized in one of the other functions.
*/
private void startBootstrapServices() {
        // The sensor service needs access to package manager service, app ops
        // service, and permissions service, therefore we start it after them.
        // Start sensor service in a separate thread. Completion should be checked
        // before using it.
        mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
            TimingsTraceLog traceLog = new TimingsTraceLog(
                    SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
            traceLog.traceBegin(START_SENSOR_SERVICE);
            startSensorService();
            traceLog.traceEnd();
        }, START_SENSOR_SERVICE);
}

/*
 * JNI registration.
 */
static const JNINativeMethod gMethods[] = {
    /* name, signature, funcPtr */
    //这边先将该接口注册,后面给system_server调用
    { "startSensorService", "()V", (void*) android_server_SystemServer_startSensorService }
    { "startHidlServices", "()V", (void*) android_server_SystemServer_startHidlServices },
};
 
//在这儿创建sensorservice
static void android_server_SystemServer_startSensorService(JNIEnv* /* env */, jobject /* clazz */) {
    char propBuf[PROPERTY_VALUE_MAX];
    property_get("system_init.startsensorservice", propBuf, "1");
    if (strcmp(propBuf, "1") == 0) {
        SensorService::instantiate();
    }
}

SensorService的实例化

sensorservice实例化后 得到sensor infor

SensorDevice初始化的重要一步是创建SensorDevice对象,另外要注意SensorService 和SensorDevice里都有数据成员mSensors但两者的数据类型不同(看上图)

SensorDevice

SensorDevice的基类

class SensorDevice : public Singleton<SensorDevice>,
                     public SensorServiceUtil::Dumpable {
}

include/utils/Singleton.h

template <typename TYPE>
class ANDROID_API Singleton
{
public:
    static TYPE& getInstance() {
        Mutex::Autolock _l(sLock);
        TYPE* instance = sInstance;
        if (instance == nullptr) {
            instance = new TYPE();
            sInstance = instance;
        }
        return *instance;
    }

    static bool hasInstance() {
        Mutex::Autolock _l(sLock);
        return sInstance != nullptr;
    }

protected:
    ~Singleton() { }
    Singleton() { }

private:
    Singleton(const Singleton&);
    Singleton& operator = (const Singleton&);
    static Mutex sLock;
    static TYPE* sInstance;
};

namespace SensorServiceUtil {

class Dumpable {
public:
    virtual std::string dump() const = 0;
    virtual void setFormat(std::string ) {}
    virtual ~Dumpable() {}
};

size_t eventSizeBySensorType(int type);

} // namespace SensorServiceUtil

访问hidl service的接口mSensors

/*
 * The ISensorsWrapper interface includes all function from supported Sensors HAL versions. This
 * allows for the SensorDevice to use the ISensorsWrapper interface to interact with the Sensors
 * HAL regardless of the current version of the Sensors HAL that is loaded. Each concrete
 * instantiation of ISensorsWrapper must correspond to a specific Sensors HAL version. This design
 * is beneficial because only the functions that change between Sensors HAL versions must be newly
 * newly implemented, any previously implemented function that does not change may remain the same.
 *
 * Functions that exist across all versions of the Sensors HAL should be implemented as pure
 * virtual functions which forces the concrete instantiations to implement the functions.
 *
 * Functions that do not exist across all versions of the Sensors HAL should include a default
 * implementation that generates an error if called. The default implementation should never
 * be called and must be overridden by Sensors HAL versions that support the function.
 */
class ISensorsWrapper : public VirtualLightRefBase {}

template<typename T>
class SensorsWrapperBase : public ISensorsWrapper {}

class SensorsWrapperV1_0 : public SensorsWrapperBase<hardware::sensors::V1_0::ISensors> {
public:
    SensorsWrapperV1_0(sp<hardware::sensors::V1_0::ISensors> sensors) :
        SensorsWrapperBase(sensors) { };
}

sp<SensorServiceUtil::ISensorsWrapper> mSensors;

SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV1_0() {
  sp<V1_0::ISensors> sensors = V1_0::ISensors::getService();
  mSensors = new SensorServiceUtil::SensorsWrapperV1_0(sensors); //创建了hidl ISensor class的wapper class
}

initializeSensorList


void SensorDevice::initializeSensorList() {
    float minPowerMa = 0.001; // 1 microAmp

    checkReturn(mSensors->getSensorsList(
            [&](const auto &list) {
                const size_t count = list.size();
        //list的数据类型是?
                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) {
                        ALOGI("Reported power %f not deemed sane, clamping to %f",
                              sensor.power, minPowerMa);
                        sensor.power = minPowerMa;
                    }
            //Vector<sensor_t> mSensorList;
                    mSensorList.push_back(sensor);
            //DefaultKeyedVector<int, Info> mActivationCount;
                    mActivationCount.add(list[i].sensorHandle, model);

                    checkReturn(mSensors->activate(list[i].sensorHandle, 0 /* enabled */));
                }
            }));
}

通过mSensors作为client访问hidl service

getSensorsList函数的参数直接赋值导致上面的函数很长,几乎掩盖了下面的事实:获得sensor list, 然后又使用callback 函数处理了下list

Return<void> Sensors::getSensorsList(getSensorsList_cb _hidl_cb) {
    sensor_t const *list;
    size_t count = mSensorModule->get_sensors_list(mSensorModule, &list);

    hidl_vec<SensorInfo> out;
    out.resize(count);

    for (size_t i = 0; i < count; ++i) {
        const sensor_t *src = &list[i];
        SensorInfo *dst = &out[i];

        convertFromSensor(*src, dst);
    }

    _hidl_cb(out);

    return Void();
}

来着hidl的sensorInfo和sensorService的sensor_t转换

hardware/interfaces/sensors/1.0/default/include/sensors/convert.h
void convertToSensor(const SensorInfo &src, sensor_t *dst);
//通过hidl得到是SensorInfo 转换成sensorservice里需要的sensor_t

hardware/libhardware/include/hardware/sensors.h
sensor_t


hardware/interfaces/sensors/1.0/types.hal: SensorInfo
Java层用的type也是通过Hidl规定的如accel = 1, 怎么写到sensorInfo的呢?

void convertToSensor(
        const ::android::hardware::sensors::V1_0::SensorInfo &src,
        sensor_t *dst) {
    dst->name = strdup(src.name.c_str());
    dst->vendor = strdup(src.vendor.c_str());
    dst->version = src.version;
    dst->handle = src.sensorHandle;
    dst->type = (int)src.type;
    dst->maxRange = src.maxRange;
    dst->resolution = src.resolution;
    dst->power = src.power;
    dst->minDelay = src.minDelay;
    dst->fifoReservedEventCount = src.fifoReservedEventCount;
    dst->fifoMaxEventCount = src.fifoMaxEventCount;
    dst->stringType = strdup(src.typeAsString.c_str());
    dst->requiredPermission = strdup(src.requiredPermission.c_str());
    dst->maxDelay = src.maxDelay;
    dst->flags = src.flags;
    dst->reserved[0] = dst->reserved[1] = 0;
}

struct Info 跟踪多个Client对sensor的设置

//这个结构体用了跟踪多个Client对sensor的设置
    // Store batch parameters in the KeyedVector and the optimal batch_rate and timeout in
    // bestBatchParams. For every batch() call corresponding params are stored in batchParams
    // vector. A continuous mode request is batch(... timeout=0 ..) followed by activate(). A batch
    // mode request is batch(... timeout > 0 ...) followed by activate().
    // Info is a per-sensor data structure which contains the batch parameters for each client that
    // has registered for this sensor.
    struct Info {
        BatchParams bestBatchParams;
        // Key is the unique identifier(ident) for each client, value is the batch parameters
        // requested by the client.
        KeyedVector<void*, BatchParams> batchParams;

        // Flag to track if the sensor is active
        bool isActive = false;

        // Sets batch parameters for this ident. Returns error if this ident is not already present
        // in the KeyedVector above.
        status_t setBatchParamsForIdent(void* ident, int flags, int64_t samplingPeriodNs,
                                        int64_t maxBatchReportLatencyNs);
        // Finds the optimal parameters for batching and stores them in bestBatchParams variable.
        void selectBatchParams();
        // Removes batchParams for an ident and re-computes bestBatchParams. Returns the index of
        // the removed ident. If index >=0, ident is present and successfully removed.
        ssize_t removeBatchParamsForIdent(void* ident);

        int numActiveClients() const;
    };
到此,在sensor service初始化时已经得到了 sensorlist.

何时创建的SensorService的Client:SystemSensorService

创建SystemSensorService后得到了sensorService的client,可以使用sensorService的服务CREATE_SENSOR_EVENT_CONNECTION在registerListener时创建event connection去配置Sensor的采样率、去得到SensorEvent.

frameworks/base/core/java/android/app/SystemServiceRegistry.java

/**
 * Manages all of the system services that can be returned by {@link Context#getSystemService}.
 * Used by {@link ContextImpl}.
 */
public static final String SENSOR_SERVICE = "sensor";
registerService(Context.SENSOR_SERVICE, SensorManager.class,
        new CachedServiceFetcher<SensorManager>() {
    @Override
    public SensorManager createService(ContextImpl ctx) {
        return new SystemSensorManager(ctx.getOuterContext(),
          ctx.mMainThread.getHandler().getLooper());
    }});

创建SensorManager

创建完SensorManger后Native创建了Sensors也赋值到Java层,之后APP可以获得已经生成的mSensorManager,通过Type得到Sensor. 已得到Sensor为参数调用registerListener创建SensorEventQueue得到SensorEvent.

mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE)
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL)


public SystemSensorManager(Context context, Looper mainLooper) {
        synchronized (sLock) {
            if (!isNativeClassInited) {
                sNativeClassInited = true;
                nativeClassInit();
            }
        }

        mMainLooper = mainLooper;
        mTargetSdkLevel = context.getApplicationInfo().targetSdkVersion;
        mContext = context;
        mNativeInstance = nativeCreate(context.getOpPackageName());

        // initialize the sensor list
        for (int index = 0;; ++index) {
            Sensor sensor = new Sensor();
            if (!nativeGetSensorAtIndex(mNativeInstance, sensor, index)) break;
            mFullSensorsList.add(sensor);
            mHandleToSensor.put(sensor.getHandle(), sensor);
        }
}

nativeClassInit

SensorOffsets

struct SensorOffsets
{
    jclass      clazz;
    //fields
    jfieldID    name;
    jfieldID    vendor;
    jfieldID    version;
    jfieldID    handle;
    jfieldID    range;
    jfieldID    resolution;
    jfieldID    power;
    jfieldID    minDelay;
    jfieldID    fifoReservedEventCount;
    jfieldID    fifoMaxEventCount;
    jfieldID    stringType;
    jfieldID    requiredPermission;
    jfieldID    maxDelay;
    jfieldID    flags;
    //methods
    jmethodID   setType;
    jmethodID   setUuid;
    jmethodID   init;
} gSensorOffsets;

nativeClassInit


static void
nativeClassInit (JNIEnv *_env, jclass _this)
{
    //android.hardware.Sensor(Sensor.java类)
    //C++引用对象,改变对象的内容,为native/java传递数据提供方便
    SensorOffsets& sensorOffsets = gSensorOffsets;
    jclass sensorClass = (jclass)
            MakeGlobalRefOrDie(_env, FindClassOrDie(_env, "android/hardware/Sensor"));
    sensorOffsets.clazz = sensorClass;
    sensorOffsets.name = GetFieldIDOrDie(_env, sensorClass, "mName", "Ljava/lang/String;");
    sensorOffsets.vendor = GetFieldIDOrDie(_env, sensorClass, "mVendor", "Ljava/lang/String;");
    sensorOffsets.version = GetFieldIDOrDie(_env, sensorClass, "mVersion", "I");
    sensorOffsets.handle = GetFieldIDOrDie(_env, sensorClass, "mHandle", "I");
    //------
    sensorOffsets.setType = GetMethodIDOrDie(_env,sensorClass, "setType", "(I)Z");
    sensorOffsets.setUuid = GetMethodIDOrDie(_env,sensorClass, "setUuid", "(JJ)V");
    sensorOffsets.init = GetMethodIDOrDie(_env,sensorClass, "<init>", "()V");
}

nativeCreate

static jlong
nativeCreate
(JNIEnv *env, jclass clazz, jstring opPackageName)
{
    ScopedUtfChars opPackageNameUtf(env, opPackageName);
    return (jlong) &SensorManager::getInstanceForPackage(String16(opPackageNameUtf.c_str()));
}

SensorManager& SensorManager::getInstanceForPackage(const String16& packageName) {
    waitForSensorService(nullptr);
    SensorManager* sensorManager;

    sensorManager = new SensorManager(opPackageName);
    return *sensorManager;
}

SensorManager构造函数

//SensorManager 数据成员
/*
    sp<ISensorServer> mSensorServer;
    Sensor const** mSensorList;
    Vector<Sensor> mSensors;
 */
SensorManager::SensorManager(const String16& opPackageName)
    : mSensorList(nullptr), mOpPackageName(opPackageName), mDirectConnectionHandle(1) {
    Mutex::Autolock _l(mLock);
    assertStateLocked();
}

status_t SensorManager::assertStateLocked() {
    {
        waitForSensorService(&mSensorServer);

        mSensors = mSensorServer->getSensorList(mOpPackageName);
        size_t count = mSensors.size();
        mSensorList =
                static_cast<Sensor const**>(malloc(count * sizeof(Sensor*)));
        LOG_ALWAYS_FATAL_IF(mSensorList == nullptr, "mSensorList NULL");

        for (size_t i=0 ; i<count ; i++) {
            mSensorList[i] = mSensors.array() + i;
        }
    }
    return NO_ERROR;
}

nativeGetSensorAtIndex

static jboolean
nativeGetSensorAtIndex(JNIEnv *env, jclass clazz, jlong sensorManager, jobject sensor, jint index)
{
    SensorManager* mgr = reinterpret_cast<SensorManager*>(sensorManager);

    Sensor const* const* sensorList;
    ssize_t count = mgr->getSensorList(&sensorList);

    return translateNativeSensorToJavaSensor(env, sensor, *sensorList[index]) != NULL;
}

translateNativeSensorToJavaSensor

static jobject
translateNativeSensorToJavaSensor(JNIEnv *env, jobject sensor, const Sensor& nativeSensor) {
    const SensorOffsets& sensorOffsets(gSensorOffsets);

    if (sensor != NULL) {
        jstring name = getJavaInternedString(env, nativeSensor.getName());
        jstring vendor = getJavaInternedString(env, nativeSensor.getVendor());
        jstring requiredPermission =
                getJavaInternedString(env, nativeSensor.getRequiredPermission());

        env->SetObjectField(sensor, sensorOffsets.name,      name);
        env->SetObjectField(sensor, sensorOffsets.vendor,    vendor);
        env->SetIntField(sensor, sensorOffsets.version,      nativeSensor.getVersion());
        env->SetIntField(sensor, sensorOffsets.handle,       nativeSensor.getHandle());
        env->SetFloatField(sensor, sensorOffsets.range,      nativeSensor.getMaxValue());
        env->SetFloatField(sensor, sensorOffsets.resolution, nativeSensor.getResolution());
        env->SetFloatField(sensor, sensorOffsets.power,      nativeSensor.getPowerUsage());
        env->SetIntField(sensor, sensorOffsets.minDelay,     nativeSensor.getMinDelay());
        env->SetIntField(sensor, sensorOffsets.fifoReservedEventCount,
                         nativeSensor.getFifoReservedEventCount());
        env->SetIntField(sensor, sensorOffsets.fifoMaxEventCount,
                         nativeSensor.getFifoMaxEventCount());
        env->SetObjectField(sensor, sensorOffsets.requiredPermission,
                            requiredPermission);
        env->SetIntField(sensor, sensorOffsets.maxDelay, nativeSensor.getMaxDelay());
        env->SetIntField(sensor, sensorOffsets.flags, nativeSensor.getFlags());
    //调用java层函数 boolean setType(int value)
        if (env->CallBooleanMethod(sensor, sensorOffsets.setType, nativeSensor.getType())
                == JNI_FALSE) {
            jstring stringType = getJavaInternedString(env, nativeSensor.getStringType());
            env->SetObjectField(sensor, sensorOffsets.stringType, stringType);
        }

        int64_t id = nativeSensor.getId();
        env->CallVoidMethod(sensor, sensorOffsets.setUuid, id, 0);
    }
    return sensor;
}

怎样根据type找到Sensor

调用SystemSensorManager后得到所有的Sensor信息,可以通过type得到Sensor, type和Sensor的关联及handle和Sensor的关联等都是native层建立的。
public Sensor getDefaultSensor(int type) {
        // TODO: need to be smarter, for now, just return the 1st sensor
        List<Sensor> l = getSensorList(type);
        boolean wakeUpSensor = false;
        // For the following sensor types, return a wake-up sensor. These types are by default
        // defined as wake-up sensors. For the rest of the SDK defined sensor types return a
        // non_wake-up version.
        if (type == Sensor.TYPE_PROXIMITY || type == Sensor.TYPE_SIGNIFICANT_MOTION
                || type == Sensor.TYPE_TILT_DETECTOR || type == Sensor.TYPE_WAKE_GESTURE
                || type == Sensor.TYPE_GLANCE_GESTURE || type == Sensor.TYPE_PICK_UP_GESTURE
                || type == Sensor.TYPE_WRIST_TILT_GESTURE
                || type == Sensor.TYPE_DYNAMIC_SENSOR_META) {
            wakeUpSensor = true;
        }

        for (Sensor sensor : l) {
            if (sensor.isWakeUpSensor() == wakeUpSensor) return sensor;
        }
        return null;
}

public List<Sensor> getSensorList(int type) {
        // cache the returned lists the first time
        List<Sensor> list;
        final List<Sensor> fullList = getFullSensorList();
        synchronized (mSensorListByType) {
            list = mSensorListByType.get(type);
            if (list == null) {
                if (type == Sensor.TYPE_ALL) {
                    list = fullList;
                } else {
                    list = new ArrayList<Sensor>();
                    for (Sensor i : fullList) {
                        if (i.getType() == type) {
                            list.add(i);
                        }
                    }
                }
                list = Collections.unmodifiableList(list);
                mSensorListByType.append(type, list);
            }
        }
        return list;
}

/===================================================================//

从java层到SEE层看怎样得到sesorlist的, 这个过程对java app而言是隐藏的,当java api getDefaulSensor时已经建立。


frameworks/base/services/core/java/com/android/server/power/PowerManagerService.java


SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());

frameworks/base/core/java/android/hardware/SystemSensorManager.java
    /** {@hide} */
    public SystemSensorManager(Context context, Looper mainLooper) {
        synchronized (sLock) {
            if (!sNativeClassInited) {
                sNativeClassInited = true;
                nativeClassInit();
            }
        }

        mMainLooper = mainLooper;
        mTargetSdkLevel = context.getApplicationInfo().targetSdkVersion;
        mContext = context;
        mNativeInstance = nativeCreate(context.getOpPackageName());

        // initialize the sensor list
        for (int index = 0;; ++index) {
            Sensor sensor = new Sensor();
            if (!nativeGetSensorAtIndex(mNativeInstance, sensor, index)) break;
            mFullSensorsList.add(sensor);
            mHandleToSensor.put(sensor.getHandle(), sensor);
        }
    }

frameworks/base/core/jni/android_hardware_SensorManager.cpp


nativeCreate
(JNIEnv *env, jclass clazz, jstring opPackageName)
{
    ScopedUtfChars opPackageNameUtf(env, opPackageName);
    //通过类的全局函数,也就是static函数
    return (jlong) &SensorManager::getInstanceForPackage(String16(opPackageNameUtf.c_str()));
}

framework/native/libs/sensor/SensorManager.cpp


class SensorManager : public ASensorManager
{
public:
    static SensorManager& getInstanceForPackage(const String16& packageName);
}

getInstanceForPackage -> SensorManager sensorManager = new SensorManager(opPackageName);
SensorManager::SensorManager(const String16& opPackageName)
    : mSensorList(nullptr), mOpPackageName(opPackageName), mDirectConnectionHandle(1) {
    Mutex::Autolock _l(mLock);
    assertStateLocked();
}

sp<ISensorServer> mSensorServer;
Vector<Sensor> mSensors;
status_t SensorManager::assertStateLocked() {
  waitForSensorService(&mSensorServer);
  //通过sensorservice的代理调用
  mSensors = mSensorServer->getSensorList(mOpPackageName);

}

frameworks/native/libs/sensor/ISensorServer.cpp


    virtual Vector<Sensor> getSensorList(const String16& opPackageName)
    {
        Parcel data, reply;
        data.writeInterfaceToken(ISensorServer::getInterfaceDescriptor());
        data.writeString16(opPackageName);
        remote()->transact(GET_SENSOR_LIST, data, &reply);
        Sensor s;
        Vector<Sensor> v;
        uint32_t n = reply.readUint32();
        v.setCapacity(n);
        while (n) {
            n--;
            reply.read(s);
            v.add(s);
        }
        return v;
    }

//下面到sensor service的实现部分

//SensorService的构造函数中并没有太多函数呢
class SensorService :
        public BinderService<SensorService>,
        public BnSensorServer,
        protected Thread
{
}
SensorService::SensorService()
    : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
      mWakeLockAcquired(false) {
    mUidPolicy = new UidPolicy(this);
    mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
}

//继承类的成员函数:onFirstRef
void SensorService::onFirstRef() {
    ALOGD("nuSensorService starting...");
    SensorDevice& dev(SensorDevice::getInstance());
}

//这里调到SensorDevice::getInstance(),单例化SensorDevice
#include <utils/Singleton.h>
template <typename TYPE>
class ANDROID_API Singleton
{
public:
    static TYPE& getInstance() {
        Mutex::Autolock _l(sLock);
        TYPE* instance = sInstance;
        if (instance == nullptr) {
            instance = new TYPE();
            sInstance = instance;
        }
        return *instance;
    }

    static bool hasInstance() {
        Mutex::Autolock _l(sLock);
        return sInstance != nullptr;
    }

protected:
    ~Singleton() { }
    Singleton() { }

private:
    Singleton(const Singleton&);
    Singleton& operator = (const Singleton&);
    static Mutex sLock;
    static TYPE* sInstance;
};

class SensorDevice : public Singleton<SensorDevice>,
                     public SensorServiceUtil::Dumpable {
}

SensorDevice::SensorDevice()
        : mHidlTransportErrors(20),
          mRestartWaiter(new HidlServiceRegistrationWaiter()),
          mEventQueueFlag(nullptr),
          mWakeLockQueueFlag(nullptr),
          mReconnecting(false) {
    if (!connectHidlService()) {
        return;
    }

    initializeSensorList();

    mIsDirectReportSupported =
            (checkReturnAndGetStatus(mSensors->unregisterDirectChannel(-1)) != INVALID_OPERATION);
}

//mSensors成员变量是访问hidl service的代理接口
sp<SensorServiceUtil::ISensorsWrapper> mSensors;
bool SensorDevice::connectHidlService() {
    HalConnectionStatus status = connectHidlServiceV2_0();
    if (status == HalConnectionStatus::DOES_NOT_EXIST) {
        status = connectHidlServiceV1_0();
    }
    return (status == HalConnectionStatus::CONNECTED);
}

SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV1_0() {
        sp<V1_0::ISensors> sensors = V1_0::ISensors::getService();
        mSensors = new SensorServiceUtil::SensorsWrapperV1_0(sensors);
}

void SensorDevice::initializeSensorList() {

    checkReturn(mSensors->getSensorsList(
            [&](const auto &list) {
                const size_t count = list.size();

//下面看下hidl service的方法
proprietary/sensors-see/sensors-hal/framework/sensors_hal.cpp

//hidl接口get_sensors_list


int sensors_hal::get_sensors_list(const sensor_t **s_list)
{
    int num_sensors = (int)_hal_sensors.size();
    sns_logi("num_sensors=%d", num_sensors);
    *s_list = &_hal_sensors[0];
    return num_sensors;
}

sensors_hal的构造函数


sensors_hal::sensors_hal()
{
  init_sensors();
}

void sensors_hal::init_sensors()
{
    auto sensors = sensor_factory::instance().get_all_available_sensors();
    auto cb  = [this](const auto& event, auto wakeup) { _event_queue.push(event, wakeup); };

    sns_logi("initializing sensors");

    for (unique_ptr<sensor>& s : sensors) {
        assert(s != nullptr);
        s->register_callback(cb);
        s->update_system_prop_details(_is_rt_thread_enable, _atrace_delay_checktime_ms);
        const sensor_t& sensor_info = s->get_sensor_info();
        sns_logd("%s: %s/%d wakeup=%d", sensor_info.name,
                 sensor_info.stringType, sensor_info.handle,
                 (sensor_info.flags & SENSOR_FLAG_WAKE_UP) != 0);
        if (((sensor_info.flags & SENSOR_FLAG_WAKE_UP) != 0)
            && (s->get_reporting_mode() == SENSOR_FLAG_CONTINUOUS_MODE)) {
            sns_logi("don't add sensor %s: %s/%d wakeup=%d", sensor_info.name,
                             sensor_info.stringType, sensor_info.handle,
                             (sensor_info.flags & SENSOR_FLAG_WAKE_UP) != 0);
        } else {
            _hal_sensors.push_back(sensor_info);
            _sensors[sensor_info.handle] = std::move(s);
        }
    }
}

//现在的关键是看怎么建立的_hal_sensors
//每个新创建的sensor,都是这个模板


static bool heart_beat_module_init()
{
    /* register supported sensor types with factory */
    sensor_factory::register_sensor(SENSOR_TYPE_HEART_BEAT,
        ssc_sensor::get_available_sensors<heart_beat>);
    sensor_factory::request_datatype(SSC_DATATYPE_HEART_BEAT);
    return true;
}
SENSOR_MODULE_INIT(heart_beat_module_init);


/**
* @brief register a new sensor type to be supported
*
* @param type sensor type as defined in sensors.h
* @param func factory function for creating sensors of this
*             type
*
*/
static void register_sensor(int type, get_available_sensors_func func)
{
        try {
            callbacks().emplace(type, func);//emplace是个啥?
        } catch (const std::exception& e) {
            sns_loge("failed to register type %d", type);
        }
}

/**
* @brief generic function template for creating ssc_sensors of
*        a given typename S
*/
    template<typename S>
    static std::vector<std::unique_ptr<sensor>> get_available_sensors()
    {
        const char *datatype = S::ssc_datatype();
        const std::vector<sensor_uid>& suids =
             sensor_factory::instance().get_suids(datatype);
        std::vector<std::unique_ptr<sensor>> sensors;
        for (const auto& suid : suids) {
            if (!(sensor_factory::instance().get_settings()
                                    & DISABLE_WAKEUP_SENSORS_FLAG)) {
              try {
                  sensors.push_back(std::make_unique<S>(suid, SENSOR_WAKEUP));
              }
            }
            try {
                sensors.push_back(std::make_unique<S>(suid, SENSOR_NO_WAKEUP));
            } 
        }
        return sensors;//这个函数调用时创建了sensor
    }


// 这里_suid_map已经赋值了,啥时候赋值的?


const std::vector<sensor_uid>& sensor_factory::get_suids(const std::string& datatype) const
{
    auto it = _suid_map.find(datatype);
    if (it != _suid_map.end()) {
        return it->second;
    } else {
        static vector<sensor_uid> empty;
        return empty;
    }
}

//_suid_map是怎么构建的?

/**
 * @brief singleton class for creating sensor objects of
 *        multiple types, querying information such as SUIDs,
 *        attributes. Classes that implement sensors are
 *        registered here.
 */
class sensor_factory
{}

sensor_factory构造函数
{

            choose_right_mandantory_list_db();
            /* find available sensors on ssc */
            discover_sensors();
            if (_suid_map.size() > 0) {
                retrieve_attributes();
            }
}
static const char* mandatory_sensors_list_file = "/mnt/vendor/persist/sensors/sensors_list.txt";
//文件的内容是所有sensor的name, 文件是怎么形成的?编译时形成的?

void sensor_factory::discover_sensors()
{
    suid_lookup lookup(
        [this](const string& datatype, const auto& suids)
        {
            this->suids_lookup_callback(datatype, suids);
        });

    sns_logd("discovering available sensors...");

    for (const auto& dt : datatypes()) {

        sns_logd("requesting %s", dt.c_str());
        lookup.request_suid(dt, true);

}

suid_lookup

suid_lookup是理解怎么得到suid的关键, 简而言之,通过suid_lookup获得了suid
当然要通过ssc_connection才能和SEE通信, suid_lookup隐藏了这一细节

#include "ssc_utils.h"
/**
 * @brief type alias for an suid event function
 *
 * param datatype: datatype of of the sensor associated with the
 * event
 * param suids: vector of suids available for the given datatype
 */
using suid_event_function =
    std::function<void(const std::string& datatype,
                       const std::vector<sensor_uid>& suids)>;

/**
 * @brief Utility class for discovering available sensors using
 *        dataytpe
 *
 */
class suid_lookup
{
public:
    /**
     * @brief creates a new connection to ssc for suid lookup
     *
     * @param cb callback function for suids
     */
    suid_lookup(suid_event_function cb);
    /**
     *  @brief look up the suid for a given datatype, registered
     *         callback will be called when suid is available for
     *         this datatype
     *
     *  @param datatype data type for which suid is requested
     *  @param default_only option to ask for publishing only default
     *         suid for the given data type. default value is false
     */
    void request_suid(std::string datatype, bool default_only = false);

    suid_event_function _cb;
    void handle_ssc_event(const uint8_t *data, size_t size);
    ssc_connection _ssc_conn;
}
 

最后

以上就是甜美未来为你收集整理的android sensor 是怎样获得sensorlist的何时启动的SensorServiceSensorService的实例化何时创建的SensorService的Client:SystemSensorService创建SensorManager怎样根据type找到Sensor frameworks/base/services/core/java/com/android/server/power/PowerManagerService.javaframeworks/base/core/jn的全部内容,希望文章能够帮你解决android sensor 是怎样获得sensorlist的何时启动的SensorServiceSensorService的实例化何时创建的SensorService的Client:SystemSensorService创建SensorManager怎样根据type找到Sensor frameworks/base/services/core/java/com/android/server/power/PowerManagerService.javaframeworks/base/core/jn所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(69)

评论列表共有 0 条评论

立即
投稿
返回
顶部