上一节制作了一个传感器的应用,应用程序获取传感器数据代码流程大致如下
//get sensor manager
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
//show sensor list
List sensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
System.out.println("get sensor list:");
for (Sensor s: sensors) {
System.out.println("name:" + s.getName());
System.out.println("string_type:" + s.getStringType());
System.out.println("vendor:" + s.getVendor());
}
//gyro
Sensor mGyroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if (mGyroSensor == null) {
System.out.println("gyro sensor is null.");
mViewGyro.setText("gyro sensor is null.");
}
mSensorManager.registerListener(new SensorEventListener() {
long last_ts = 0;
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
String string = "sensor_gyro=(" + new DecimalFormat("0.00").format(sensorEvent.values[0]) + "," + new DecimalFormat("0.00").format(sensorEvent.values[1]) + "," + new DecimalFormat("0.00").format(sensorEvent.values[2]) + ")\nts=" + sensorEvent.timestamp + "\ninterval=" + (sensorEvent.timestamp - last_ts)/1000/1000 + "ms";
last_ts = sensorEvent.timestamp;
//System.out.println(string);
mViewGyro.setText(string);
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
System.out.println("onAccuracyChanged.");
}
},mGyroSensor,sample_type);
如上所示,在应用层调用几个常用接口就能够获取到传感器数据了,主要接口包括
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
List sensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
Sensor mAccSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
mSensorManager.registerListener(xxx);
下面对这四个接口为主线来学习源代码,理解传感器的框架
该接口是一个用来获取系统服务的接口,SensorManager是一个抽象类,为应用层提供传感器接口,SystemSensorManager继承SensorManager实现了这些接口功能,我们来看一下SystemSensorManager的创建.
final class SystemServiceRegistry {
static {
//...
registerService(Context.SENSOR_SERVICE, SensorManager.class,
new CachedServiceFetcher() {
@Override
public SensorManager createService(ContextImpl ctx) {
return new SystemSensorManager(ctx.getOuterContext(),
ctx.mMainThread.getHandler().getLooper());
}});
//...
}
SystemSensorManager在SystemServiceRegistry的静态初始化块当中,因此在系统初始阶段加载SystemServiceRegistry时,SystemSensorManager就会被创建,来看一下它的构造函数
public SystemSensorManager(Context context, Looper mainLooper) {
synchronized(sLock) {
if (!sNativeClassInited) {
sNativeClassInited = true;
//获取FieldID和MethodID,存gSensorOffsets中.为后续JNI的get/set做准备
nativeClassInit();
}
}
mMainLooper = mainLooper;
mTargetSdkLevel = context.getApplicationInfo().targetSdkVersion;
mContext = context;
//创建Native层的SensorManager.
mNativeInstance = nativeCreate(context.getOpPackageName());
//通过Native层的SensorManager的getSensorList方法,初始化传感器列表,并填充到mFullSensorsList当中.建立sensor和handle之间的映射,存放在mHandleToSensor中.
for (int index = 0;;++index) {
Sensor sensor = new Sensor();
//将Native层的sensor,通过JNI返回到Java层
if (!nativeGetSensorAtIndex(mNativeInstance, sensor, index)) break;
mFullSensorsList.add(sensor);
mHandleToSensor.put(sensor.getHandle(), sensor);
}
}
调用nativeCreate创建Native层的SensorManager,在创建过程中会循环等待SensorService被创建,与其建立binder关系,接着调用SensorSerivce的getSensorList,来获取硬件传感器列表信息.
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) {
Mutex::Autolock _l(sLock);
if (iterator != sPackageInstances.end()) {
sensorManager = iterator->second;
} else {
//创建Native层sensorManager,接着看SensorManager的构造函数
sensorManager = new SensorManager(opPackageName);
//....
sPackageInstances.insert(std::make_pair(opPackageName, sensorManager));
}
return *sensorManager;
}
SensorManager::SensorManager(const String16& opPackageName)
: mSensorList(0), mOpPackageName(opPackageName) {
// okay we're not locked here, but it's not needed during construction
assertStateLocked();
}
status_t SensorManager::assertStateLocked() {
bool initSensorManager = false;
if (mSensorServer == NULL) {
initSensorManager = true;
} else {
// Ping binder to check if sensorservice is alive.
status_t err = IInterface::asBinder(mSensorServer)->pingBinder();
if (err != NO_ERROR) {
initSensorManager = true;
}
}
if (initSensorManager) {
// 等待获取Native层的SensorService被注册,超时时间60*5s
const String16 name("sensorservice");
for (int i = 0; i < 60; i++) {
status_t err = getService(name, &mSensorServer);
if (err == NAME_NOT_FOUND) {
sleep(1);
continue;
}
if (err != NO_ERROR) {
return err;
}
break;
}
class DeathObserver : public IBinder::DeathRecipient {
SensorManager& mSensorManager;
virtual void binderDied(const wp& who) {
ALOGW("sensorservice died [%p]", who.unsafe_get());
mSensorManager.sensorManagerDied();
}
public:
DeathObserver(SensorManager& mgr) : mSensorManager(mgr) { }
};
LOG_ALWAYS_FATAL_IF(mSensorServer.get() == NULL, "getService(SensorService) NULL");
mDeathObserver = new DeathObserver(*const_cast(this));
IInterface::asBinder(mSensorServer)->linkToDeath(mDeathObserver);
//通过SensorServer获取传感器列表
mSensors = mSensorServer->getSensorList(mOpPackageName);
size_t count = mSensors.size();
mSensorList =
static_castconst**>(malloc(count * sizeof(Sensor*)));
LOG_ALWAYS_FATAL_IF(mSensorList == NULL, "mSensorList NULL");
//将传感器列表存入SensorManager的mSensorList中
for (size_t i=0 ; iarray() + i;
}
}
return NO_ERROR;
}
上面SensorManager会等待SensorService注册,将它保存在成员变量mSensorServer中.小结一下这一段流程UML图
SensorManager功能都来自于SensorService,它在Android的Sensor框架中占据核心位置,接下来看一下分析一下SensorService的相关代码.
当内核启动后执行init 程序,该程序解析 init.rc文件(zygote包含在init.${ro.zygote}.rc中),rc文件中指定的应用程序在app_main.cpp中,调用AndroidRuntime的start方法,接着通过JNI调用Zyoteinit.java中的main函数,从这里开始追踪.
public static void main(String argv[]) {
//...
if (startSystemServer) {
startSystemServer(abiList, socketName);
}
//...
}
上面代码可知ZygoteInit的main函数执中调用startSystemServer函数,调用forkSystemServer创建系统服务,跳转到SystemServer的main函数
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
//...
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
//...
}
private void startBootstrapServices() {
//...
startSensorService();
//...
}
在 SystemServer 的main函数中,会创建SystemService对象,并调用run方法,在run方法中调用startBootstrapServices(),接着调用Native方法startSensorService(),
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) {
// Start the sensor service in a new thread
createThreadEtc(start_sensor_service, nullptr,
"StartSensorThread", PRIORITY_FOREGROUND);
}
}
static int start_sensor_service(void* /*unused*/) {
SensorService::instantiate();
return 0;
}
static void instantiate() { publish(); }
static status_t publish(bool allowIsolated = false) {
sp sm(defaultServiceManager());
return sm->addService(
String16(SERVICE::getServiceName()),
new SERVICE(), allowIsolated);
}
在android_server_SystemServer_startSensorService中创建线程start_sensor_service来实例化SensorService,然后将SensorService添加到ServiceManager当中(SensorManager从ServiceManager里获取SensorService).当SensorService被创建时,onFirstRef被调用,这个初始化函数完成了一些重要的初始化过程,我们来看一下
void SensorService::onFirstRef() {
//SensorDevice为单例类,为SensorServic提供访问硬件的通道,它的构造函数中完成以下几件事
//1.获取HAL层sensor的动态库,获取module--->mSensorModule
//2.调用动态库的open方法,获取device--->mSensorDevice
//3.调用动态库get_sensors_list,获取所有sensor的列表,将它们填充到mActivationCount中,并对通过active接口,对每个HAL层的sensor执行一次关闭的动作
SensorDevice& dev(SensorDevice::getInstance());
if (dev.initCheck() == NO_ERROR) {
......
//遍历sensor list 判断又那些传感器存在,将物理传感器(acc mag gyro等)和虚拟传感器(gravity、linear_acceleration、rotation vector)注册到mSensors中.
for (ssize_t i=0 ; ibool useThisSensor=true;
switch (list[i].type) {
case SENSOR_TYPE_ACCELEROMETER:
hasAccel = true;
break;
case SENSOR_TYPE_MAGNETIC_FIELD:
hasMag = true;
break;
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:
case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
case SENSOR_TYPE_GAME_ROTATION_VECTOR:
if (IGNORE_HARDWARE_FUSION) {
useThisSensor = false;
} else {
virtualSensorsNeeds &= ~(1<<list[i].type);
}
break;
}
if (useThisSensor) {
//此接口会将传感器父类SensorInterface接口与handle以std::map的方式保存在mHandleMap中.
registerSensor( new HardwareSensor(list[i]) );
}
}
// 初始化融合算法
SensorFusion::getInstance();
//当加速度计、陀螺仪、指南针都存在时,可以注册多个虚拟传感器,它们可以根据这三个传感器+算法生成虚拟传感器数据.
if (hasGyro && hasAccel && hasMag) {
// Add Android virtual sensors if they're not already
// available in the HAL
bool needRotationVector =
(virtualSensorsNeeds & (1<0;
registerSensor(new RotationVectorSensor(), !needRotationVector, true);
registerSensor(new OrientationSensor(), !needRotationVector, true);
bool needLinearAcceleration =
(virtualSensorsNeeds & (1<0;
registerSensor(new LinearAccelerationSensor(list, count),
!needLinearAcceleration, true);
// virtual debugging sensors are not for user
registerSensor( new CorrectedGyroSensor(list, count), true, true);
registerSensor( new GyroDriftSensor(), true, true);
}
//注册A+G的虚拟传感器
if (hasAccel && hasGyro) {
bool needGravitySensor = (virtualSensorsNeeds & (1<0;
registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
bool needGameRotationVector =
(virtualSensorsNeeds & (1<0;
registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
}
//注册A+M的虚拟传感器
if (hasAccel && hasMag) {
bool needGeoMagRotationVector =
(virtualSensorsNeeds & (1<0;
registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
}
// 判断所有sensor是否都支持batch方式,来设置sockBuffersize大小
bool batchingSupported = false;
mSensors.forEachSensor(
[&batchingSupported] (const Sensor& s) -> bool {
if (s.getFifoMaxEventCount() > 0) {
batchingSupported = true;
}
return !batchingSupported;
});
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;
}
// 判断申请的socket buffer 大小是否超出了系统的设置.
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);
}
//默认状态没获取wake lock
mWakeLockAcquired = false;
//创建Looper
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;
mNextSensorRegIndex = 0;
for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
mLastNSensorRegistrations.push();
}
mInitCheck = NO_ERROR;
//当SensorService处于wake_lock状态,此线程会等待loop应答,超时时间5秒,超时后清0所有SensorEventConnection锁的引用计数.
mAckReceiver = new SensorEventAckReceiver(this);
mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
//执行threadLoop()方法,轮询接收HAL层上报的数据
run("SensorService", PRIORITY_URGENT_DISPLAY);
// 设置当前进程调度优先级.
enableSchedFifoMode();
}
}
}
在 SensorService 的 onFirstRef 接口中,获取SensorDevice(单例类)的引用,这里看一下SensorDevice的构造函数
SensorDevice::SensorDevice()
: mSensorDevice(0),
mSensorModule(0) {
//从sensor.xxx.so中获取module
status_t err = hw_get_module(SENSORS_HARDWARE_MODULE_ID,
(hw_module_t const**)&mSensorModule);
ALOGE_IF(err, "couldn't load %s module (%s)",
SENSORS_HARDWARE_MODULE_ID, strerror(-err));
if (mSensorModule) {
//调用module的open接口,获取HAL层硬件访问接口
err = sensors_open_1(&mSensorModule->common, &mSensorDevice);
ALOGE_IF(err, "couldn't open device for module %s (%s)",
SENSORS_HARDWARE_MODULE_ID, strerror(-err));
if (mSensorDevice) {
if (mSensorDevice->common.version == SENSORS_DEVICE_API_VERSION_1_1 ||
mSensorDevice->common.version == SENSORS_DEVICE_API_VERSION_1_2) {
ALOGE(">>>> WARNING <<< Upgrade sensor HAL to version 1_3");
}
sensor_t const* list;
//获取传感器列表
ssize_t count = mSensorModule->get_sensors_list(mSensorModule, &list);
mActivationCount.setCapacity(count);
Info model;
//将传感器的handle和model信息放入mActivationCount中,同时默认关闭所有传感器.
for (size_t i=0 ; ilist[i].handle, model);
mSensorDevice->activate(
reinterpret_cast<struct sensors_poll_device_t *>(mSensorDevice),
list[i].handle, 0);
}
}
}
}
SensorDevice调用 hw_get_module接口加载HAL的Sensor库库,接着调用HAL层提供的open接口,执行HAL层的初始化,同时返回硬件访问接口,接着调用 Sensor HAL提供的 get_sensors_list 接口,获取所支持的 Sensor列表.
接着上面SensorService::onFirstRef接口,通过SensorDevice获取传感器列表信息后,调用registerSensor分别将传感器添加到mSensors中.然后创建 Looper , Looper用来监听传感器数据的上报和分发,接着调用run方法,启动threadLoop,轮询HAL层传感器数据的上报.来看一下SensorService的threadLoop
bool SensorService::threadLoop() {
ALOGD("nuSensorService thread starting...");
//获取虚拟传感器个数,缓冲区大小
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实例,用来跟HAL层打交道
SensorDevice& device(SensorDevice::getInstance());
const int halVersion = device.getHalDeviceVersion();
do {
//调用HAL层poll方法,来获取所有传感器数据.
ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
if (count < 0) {
ALOGE("sensor poll failed (%s)", strerror(-count));
break;
}
//读取到的sensor数据的flags标志位清0
for (int i = 0; i < count; i++) {
mSensorEventBuffer[i].flags = 0;
}
//...
//判断上报数据中是否有能够唤醒的传感器类型存在
bool bufferHasWakeUpEvent = false;
for (int i = 0; i < count; i++) {
if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
bufferHasWakeUpEvent = true;
break;
}
}
//唤醒传感器上报数据,并且当前未拿wakelock,申请拿wake lock 防止休眠
if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
setWakeLockAcquiredLocked(true);
}
//记录最后一组数据.
recordLastValueLocked(mSensorEventBuffer, count);
//处理虚拟传感器
if (count && vcount) {
sensors_event_t const * const event = mSensorEventBuffer;//从HAL层poll上来的数据
if (!mActiveVirtualSensors.empty()) {//虚拟传感器存在
size_t k = 0;
SensorFusion& fusion(SensorFusion::getInstance());
if (fusion.isEnabled()) {
for (size_t i=0 ; ievent[i]);//获取acc gyro mag数据,调用融合算法计算,有源码,感兴趣的可以跟到代码里看一下
}
}
//调用所有虚拟传感器的算法,将算法最终得出的数据添加到mSensorEventBuffer当中,并记录最后一次的值,然后对mSensorEventBuffer的数据按照时间戳进行排序
for (size_t i=0 ; ifor (int handle : mActiveVirtualSensors) {
if (count + k >= minBufferSize) {
ALOGE("buffer too small to hold all events: "
"count=%zd, k=%zu, size=%zu",
count, k, minBufferSize);
break;
}
sensors_event_t out;
sp si = mSensors.getInterface(handle);
if (si == nullptr) {
ALOGE("handle %d is not an valid virtual sensor", handle);
continue;
}
if (si->process(&out, event[i])) {
mSensorEventBuffer[count + k] = out;
k++;
}
}
}
if (k) {
// record the last synthesized values
recordLastValueLocked(&mSensorEventBuffer[count], k);
count += k;
// sort the buffer by time-stamps
sortEventBuffer(mSensorEventBuffer, count);
}
}
}
//将SENSOR_TYPE_ROTATION_VECTOR的数据的data[4]填为-1,可靠度为-1,为了兼容老版本.
if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
for (int i = 0; i < count; i++) {
if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
// All the 4 components of the quaternion should be available
// No heading accuracy. Set it to -1
mSensorEventBuffer[i].data[4] = -1;
}
}
}
//SENSOR_TYPE_META_DATA和SENSOR_TYPE_DYNAMIC_SENSOR_META类型数据进行处理
for (int i = 0; i < count; ++i) {
// Map flush_complete_events in the buffer to SensorEventConnections which called flush
// on the hardware sensor. mapFlushEventsToConnections[i] will be the
// SensorEventConnection mapped to the corresponding flush_complete_event in
// mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
mMapFlushEventsToConnections[i] = NULL;
if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
if (rec != NULL) {
mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
rec->removeFirstPendingFlushConnection();
}
}
// handle dynamic sensor meta events, process registration and unregistration of dynamic
// sensor based on content of event.
if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
const sensor_t& dynamicSensor =
*(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
handle, dynamicSensor.type, dynamicSensor.name);
if (mSensors.isNewHandle(handle)) {
const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
sensor_t s = dynamicSensor;
// make sure the dynamic sensor flag is set
s.flags |= DYNAMIC_SENSOR_MASK;
// force the handle to be consistent
s.handle = handle;
SensorInterface *si = new HardwareSensor(s, uuid);
// This will release hold on dynamic sensor meta, so it should be called
// after Sensor object is created.
device.handleDynamicSensorConnection(handle, true /*connected*/);
registerDynamicSensorLocked(si);
} else {
ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
}
} else {
int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
device.handleDynamicSensorConnection(handle, false /*connected*/);
if (!unregisterDynamicSensorLocked(handle)) {
ALOGE("Dynamic sensor release error.");
}
size_t numConnections = activeConnections.size();
for (size_t i=0 ; i < numConnections; ++i) {
if (activeConnections[i] != NULL) {
activeConnections[i]->removeSensor(handle);
}
}
}
}
}
//通过connect将数据发送给对应的client,如果是单次类型的sensor,则发送完成后进行清理.
bool needsWakeLock = false;
size_t numConnections = activeConnections.size();
for (size_t i=0 ; i < numConnections; ++i) {
if (activeConnections[i] != 0) {
//这里讲HAL层读取到的数据,通过SensorEventConnect的sendEvent方法写入到Bitube中.后面会讲
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);
}
}
}
if (mWakeLockAcquired && !needsWakeLock) {
setWakeLockAcquiredLocked(false);
}
} while (!Thread::exitPending());
ALOGW("Exiting SensorService::threadLoop => aborting...");
abort();
return false;
}
SensorManager.java中的getDefaultSensor方法是依赖getSensorlist实现的,来看一下getSensorlist方法.
public List<Sensor> getSensorList(int type) {
// cache the returned lists the first time
List<Sensor> list;
//SystemSensorManager在上面构造函数初始化时会将传感器列表信息放在mFullSensorsList当中.,这里直接获取
final List<Sensor> fullList = getFullSensorList();
//根据传入的参数type,返回指定的传感器,如果是TYPE_ALL类型,则返回整个传感器列表.
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;
}
SensorManager.java向应用提供的registerListener方法,最终会调到SystemSensorManager中的registerListenerImpl方法,
protected boolean registerListenerImpl(SensorEventListener listener, Sensor sensor,
int delayUs, Handler handler, int maxBatchReportLatencyUs, int reservedFlags) {
//...
synchronized (mSensorListeners) {
//如果listener没有对应的queue,则创建一个queue,将sensor添加到queue当中
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();
//创建与listenner和looper关联的SensorEventQueue
queue = new SensorEventQueue(listener, looper, this, fullClassName);
//添加/使能该sensor
if (!queue.addSensor(sensor, delayUs, maxBatchReportLatencyUs)) {
queue.dispose();
return false;
}
mSensorListeners.put(listener, queue);
return true;
} else {
return queue.addSensor(sensor, delayUs, maxBatchReportLatencyUs);
}
}
}
创建一个与looper,listener相关联的SensorEventQueue,看一下SensorEventQueue的构造函数,
public SensorEventQueue(SensorEventListener listener, Looper looper,
SystemSensorManager manager, String packageName) {
super(looper, manager, OPERATING_MODE_NORMAL, packageName);
mListener = listener;
}
接着看它的基类BaseEventQueue和它的nativeInitBaseEventQueue方法.
BaseEventQueue(Looper looper, SystemSensorManager manager, int mode, String packageName) {
if (packageName == null) packageName = "";
nSensorEventQueue = nativeInitBaseEventQueue(manager.mNativeInstance,
new WeakReference<>(this), looper.getQueue(),
packageName, mode, manager.mContext.getOpPackageName());
mCloseGuard.open("dispose");
mManager = manager;
}
static jlong nativeInitSensorEventQueue(JNIEnv *env, jclass clazz, jlong sensorManager,
jobject eventQWeak, jobject msgQ, jstring packageName, jint mode) {
//sensorManager是在SystemSensorService构造函数中,通过nativeCreate创建的
SensorManager* mgr = reinterpret_cast(sensorManager);
ScopedUtfChars packageUtf(env, packageName);
String8 clientName(packageUtf.c_str());
//1.创建Native层SensorEventQueue对象
sp queue(mgr->createEventQueue(clientName, mode));
//将SystemSensorManager Looper中的MessageQueue传递到Native层
sp messageQueue = android_os_MessageQueue_getMessageQueue(env, msgQ);
if (messageQueue == NULL) {
jniThrowRuntimeException(env, "MessageQueue is not initialized.");
return 0;
}
//2.创建Receiver
sp receiver = new Receiver(queue, messageQueue, eventQWeak);
receiver->incStrong((void*)nativeInitSensorEventQueue);
return jlong(receiver.get());
}
nativeInitSensorEventQueue中,有两件事要注意,1.创建SensorEventQueue对象2.创建Receiver.先看一下SensorEventQueue的创建
sp<SensorEventQueue> SensorManager::createEventQueue(String8 packageName, int mode) {
sp<SensorEventQueue> queue;
Mutex::Autolock _l(mLock);
while (assertStateLocked() == NO_ERROR) {
sp<ISensorEventConnection> connection =
mSensorServer->createSensorEventConnection(packageName, mode, mOpPackageName);
if (connection == NULL) {
// SensorService just died or the app doesn't have required permissions.
ALOGE("createEventQueue: connection is NULL.");
return NULL;
}
queue = new SensorEventQueue(connection);
break;
}
return queue;
}
SensorManager通过mSensorServer(它是在SensorManager构造函数里getService获得)的createSensorEventConnection接口,创建一个SensorEventConnection对象,它是SensorService的内部类,在SensorService::enable中被添加,用来在接收到的HAL层的数据发送出去的重要通道.接着创建一个与这个SensorEventConnection对象关联的SensorEventQueue对象,并返回.Native层的SensorEventQueue是非常重要的数据通道,一方面接收Native层SensorService发送过来的数据(SensorService的数据来自HAL层),另一方面将数据分发到Framewrok层SystemSensorManager的BaseEventQueue子类对象中.后面会通过代码说明这个过程如何发生.接着看Receiver类,Receiver构造函数
Receiver(const sp& sensorQueue,
const sp& messageQueue,
jobject receiverWeak) {
JNIEnv* env = AndroidRuntime::getJNIEnv();
//保存一个SensorEventQueue对象,后续可以通过和它关联的SensorEventConnection与SensorService打交道,比如开启/关闭传感器,设置传感器速率等.
mSensorQueue = sensorQueue;
//从SystemSensorManager传递到Native层的MessageQueue,用来与Looper建立联系,主要是用来添加/删除文件描述符.
mMessageQueue = messageQueue;
mReceiverWeakGlobal = env->NewGlobalRef(receiverWeak);
mIntScratch = (jintArray) env->NewGlobalRef(env->NewIntArray(16));
mFloatScratch = (jfloatArray) env->NewGlobalRef(env->NewFloatArray(16));
}
Receiver构造函数中,主要建立与SensorService和MessageQueue之间的关联,接着看它的onFirstRef.
virtual void onFirstRef() {
LooperCallback::onFirstRef();,
//第四个参数是this,其父类是LooperCallback
mMessageQueue->getLooper()->addFd(mSensorQueue->getFd(), 0,
ALOOPER_EVENT_INPUT, this, mSensorQueue.get());
}
Native层的MessageQueue调用Looper类的addFd方法,添加对SensorEventQueue的监听,看一下looper的addFd方法.
int Looper::addFd(int fd, int ident, int events, const sp& callback, void* data) {
//...
{ // acquire lock
AutoMutex _l(mLock);
Request request;
request.fd = fd;
request.ident = ident;
request.events = events;
request.seq = mNextRequestSeq++;
//注册callback
request.callback = callback;
request.data = data;
if (mNextRequestSeq == -1) mNextRequestSeq = 0; // reserve sequence number -1
struct epoll_event eventItem;
request.initEventItem(&eventItem);
ssize_t requestIndex = mRequests.indexOfKey(fd);
if (requestIndex < 0) {
int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
if (epollResult < 0) {
ALOGE("Error adding epoll events for fd %d: %s", fd, strerror(errno));
return -1;
}
mRequests.add(fd, request);
} else {
int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_MOD, fd, & eventItem);
//....
mRequests.replaceValueAt(requestIndex, request);
}
} // release lock
return 1;
}
Receiver继承LooperCallback并实现了handleEvent函数,addFD时会将callback传入Looper.Looper的addFd如果被监控的文件描述符,已经存在用EPOLL_CTL_MOD参数调用epoll_ctl修改,否则,EPOLL_CTL_ADD来添加.(Native层的Looper是以epoll为核心实现的,对Looper不熟悉的可以看一下epoll的简介).Looper在添加文件描述符后,后续通过pollOnce或pollAll接口来访问,最终都会调用pollInner来等待这些文件描述符被写入数据,我们来看一下pollInner
int Looper::pollInner(int timeoutMillis) {
//...
//调用epoll_wait等待所监控的文件描述符被写入数据
int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
// Check for poll error.
if (eventCount < 0) {
if (errno == EINTR) {
goto Done;
}
ALOGW("Poll failed with an unexpected error: %s", strerror(errno));
result = POLL_ERROR;
goto Done;
}
// Check for poll timeout.
if (eventCount == 0) {
#if DEBUG_POLL_AND_WAKE
ALOGD("%p ~ pollOnce - timeout", this);
#endif
result = POLL_TIMEOUT;
goto Done;
}
// Handle all events.
#if DEBUG_POLL_AND_WAKE
ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
#endif
for (int i = 0; i < eventCount; i++) {
int fd = eventItems[i].data.fd;
uint32_t epollEvents = eventItems[i].events;
if (fd == mWakeEventFd) {
if (epollEvents & EPOLLIN) {
awoken();
} else {
ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
}
} else {
ssize_t requestIndex = mRequests.indexOfKey(fd);
if (requestIndex >= 0) {
int events = 0;
if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
pushResponse(events, mRequests.valueAt(requestIndex));
} else {
ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
"no longer registered.", epollEvents, fd);
}
}
}
Done: ;
//...handleMessage...
//处理应答事件
for (size_t i = 0; i < mResponses.size(); i++) {
Response& response = mResponses.editItemAt(i);
if (response.request.ident == POLL_CALLBACK) {
int fd = response.request.fd;
int events = response.events;
void* data = response.request.data;
#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
this, response.request.callback.get(), fd, events, data);
#endif
//这里调用addFd时添加的callback类中的handleEvent方法
int callbackResult = response.request.callback->handleEvent(fd, events, data);
if (callbackResult == 0) {
removeFd(fd, response.request.seq);
}
// Clear the callback reference in the response structure promptly because we
// will not clear the response vector itself until the next poll.
response.request.callback.clear();
result = POLL_CALLBACK;
}
}
return result;
}
在Looper中epoll_wait来监听文件描述符是否有数据写入,当有数据写入后,调用callback的handleEvent方法来进行处理,这里是调用了Receiver的handleEvent方法,handleEvent中依赖于SensorEventQueue中的mSensorChannel(mSensorChannel是在SensorEventConnection构造时创建的)来实现数据的读取的,mSensorChannel是一个BitTube对象,BitTube提供全双工的跨进程的通讯管道(这里对它做了一个说明,有兴趣可以了解一下),handleEvent依赖它来获取发送过来的数据(数据从哪发来?我们后面再说),我们看一下Receiver的handleEvent接口
virtual int handleEvent(int fd, int events, void* data) {
JNIEnv* env = AndroidRuntime::getJNIEnv();
sp q = reinterpret_cast(data);
ScopedLocalRef receiverObj(env, jniGetReferent(env, mReceiverWeakGlobal));
ssize_t n;
ASensorEvent buffer[16];
//读取Bitube中的数据
while ((n = q->read(buffer, 16)) > 0) {
//对发送过来的数据根据不同类型进行处理
for (int i=0 ; iif (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(mFloatScratch, 0, 1, &value);
}
//...
}else {
int8_t status;
switch (buffer[i].type) {
case SENSOR_TYPE_ORIENTATION:
case SENSOR_TYPE_MAGNETIC_FIELD:
case SENSOR_TYPE_ACCELEROMETER:
case SENSOR_TYPE_GYROSCOPE:
case SENSOR_TYPE_GRAVITY:
case SENSOR_TYPE_LINEAR_ACCELERATION:
status = buffer[i].vector.status;
break;
case SENSOR_TYPE_HEART_RATE:
status = buffer[i].heart_rate.status;
break;
default:
status = SENSOR_STATUS_ACCURACY_HIGH;
break;
}
if (receiverObj.get()) {
//将传感器数据通过JNI调用Java层BaseEventQueue的dispatchSensorEvent方法,将消息进行分发
env->CallVoidMethod(receiverObj.get(),
gBaseEventQueueClassInfo.dispatchSensorEvent,
buffer[i].sensor,
mFloatScratch,
status,
buffer[i].timestamp);
}
}
if (env->ExceptionCheck()) {
mSensorQueue->sendAck(buffer, n);
ALOGE("Exception dispatching input event.");
return 1;
}
}
mSensorQueue->sendAck(buffer, n);
}
if (n<0 && n != -EAGAIN) {
// FIXME: error receiving events, what to do in this case?
}
return 1;
}
上面会根据不同类型的传感器将数据进行处理,常用传感器通过 gBaseEventQueueClassInfo.dispatchSensorEvent进行分发,这里实际上是调用的Framework层的SensorEventQueue类(继承BaseEventQueue)的dispatchSensorEvent方法.
protected void dispatchSensorEvent(int handle, float[] values, int inAccuracy,
long timestamp) {
//初始化时handle映射了sensor,通过handle找到sensor
final Sensor sensor = mManager.mHandleToSensor.get(handle);
if (sensor == null) {
// sensor disconnected
return;
}
SensorEvent t = null;
synchronized (mSensorsEvents) {
t = mSensorsEvents.get(handle);
}
if (t == null) {
// This may happen if the client has unregistered and there are pending events in
// the queue waiting to be delivered. Ignore.
return;
}
// Copy from the values array.
System.arraycopy(values, 0, t.values, 0, t.values.length);
t.timestamp = timestamp;
t.accuracy = inAccuracy;
t.sensor = sensor;
// 精度变化时调用监听器的onAccuracyChanged回调函数
final int accuracy = mSensorAccuracies.get(handle);
if ((t.accuracy >= 0) && (accuracy != t.accuracy)) {
mSensorAccuracies.put(handle, t.accuracy);
mListener.onAccuracyChanged(t.sensor, t.accuracy);
}
//调用监听器的onSensorChanged回调函数,将数据返回给APP
mListener.onSensorChanged(t);
}
dispatchSensorEvent里,通过handle找到对应的sensor,将数据通过SensorEventListener的onSensorChanged将数据给应用程序.
回顾一下前面的流程,Looper通过epoll_wait将数据读出,回调Receiver的handleEvent函数,handleEvent调用SensorEventQueuem的read方法读取数据,然后通过JNI回调Framework层SensorEventQueue的dispatchSensorEvent方法,在dispatchSensorEvent方法中回调SensorEventListener的onSensorChanged方法,这个方法为应用注册的监听方法,将数据返回到应用层.可是是谁将数据写入Looper监控的文件描述符中的?我们接着看一下这个过程.之前说过”handleEvent调用SensorEventQueue的read方法读取数据”,读取和写入都依赖于BitTube对象,它在SensorEventConnection构造函数中创建(mChannel),然后SensorEventQueue通过getSensorChannel()接口获取该对象,(这里可以按照mSensorChannel的线索,反推写入数据的地方,接下来直接描述结果),SensorService在onFirstRef最后执行了run,threadLoop开始运行,这个函数上面分析过了,在最后时
//...
activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
mMapFlushEventsToConnections);
//...
return false;
}
SensorEventConnection的sendEvents方法会将数据写入BitTube中
status_t SensorService::SensorEventConnection::sendEvents(
//...
ssize_t size = SensorEventQueue::write(mChannel,
reinterpret_cast(scratch), count);
//...
return size < 0 ? status_t(size) : status_t(NO_ERROR);
}
到这里传感器数据的写入,读取流程分析完毕.
这里在简述一下数据的完整流程:SensorService的threadLoop线程,循环通过SensorDevice的poll接口,从HAL层获取传感器数据,然后调用已建立好的传感器连接通道SensorEventConnection的sendEvents方法,写入到BitTube的socketpai通道中,Looper函数的epoll_wait被唤醒,然后回调Receiver的handleEvent方法,在该方法中SensorEventQueue会读取socketpai通道里的数据,调用JNI调用Framework层的SensorEventQueue的dispatchSensorEvent方法,在此方法中回调SensorEventListener的onSensorChanged方法和onAccuracyChanged,这两个方法就是应用程序注册的方法.
传感器HAL层的AOSP部分包括sensor.h,接下来看一下这个文件内容.
HAL层中关键的结构和接口存在sensor.h文件中,包括:sensor_module_t、sensors_poll_device_1、get_sensors_list等
//HAL层硬件模块必须实现的接口
struct sensors_module_t {
struct hw_module_t common;
//获取传感器列表
int (*get_sensors_list)(struct sensors_module_t* module,
struct sensor_t const** list);
//设置操作模式.0:正常模式.1:回环测试模式
int (*set_operation_mode)(unsigned int mode);
};
hw_modult_t里填充标准HAL层参数(版本,名字,id等),hw_module_methods_t指向一个打开sensor的方法,然后返回hw_device_t **,供上层操作具体硬件
//对硬件进行访问控制的结构体
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 sensor_handle, int enabled);
//设置传感器延时时间,1.0版本使用,后续弃用
int (*setDelay)(struct sensors_poll_device_t *dev,
int sensor_handle, int64_t sampling_period_ns);
//SensorService通过SensorDevice调用poll接口来获取数据.
int (*poll)(struct sensors_poll_device_t *dev,
sensors_event_t* data, int count);
};
};
//batch方法完全替代了setDelay的功能,设置采样周期和最大延迟时间.
int (*batch)(struct sensors_poll_device_1* dev,
int sensor_handle, int flags, int64_t sampling_period_ns,
int64_t max_report_latency_ns);
//用来flush FIFO 配合batch使用
int (*flush)(struct sensors_poll_device_1* dev, int sensor_handle);
//注入传感器数据
int (*inject_sensor_data)(struct sensors_poll_device_1 *dev, const sensors_event_t *data);
void (*reserved_procs[7])(void);
} sensors_poll_device_1_t;
sensors_poll_device_1_t兼容老1.0版本sensors_poll_device_t,并提供了新版本接口batch,flush,inject_sensor_data接口.
- get_sensors_list
//获取所有传感器列表
int (*get_sensors_list)(struct sensors_module_t* module,
struct sensor_t const** list);
获取所有sensor的列表,由*list指向,传递给上层使用.又的平台是静态方式注册list,有的平台动态方式注册.
//设置操作模式
int (*set_operation_mode)(unsigned int mode);
模式设置接口,用来将sensor service注入的数据返回.因传感器数据来自于底层硬件,这个方式多用于调试或特殊功能,多数平台不实现这个接口.
struct sensor_t {
//传感器名字
const char* name;
//传感器厂商信息
const char* vendor;
//版本号
int version;
//handle,用来关联sensor,重要
int handle;
//传感器类型
int type;
//最大范围
float maxRange;
//传感器采样的最小差值
float resolution;
//传感器功耗,mA
float power;
//最快采样周期
int32_t minDelay;
//硬件中保留的FIFO最大数目
uint32_t fifoReservedEventCount;
//单个传感器最大事件数
uint32_t fifoMaxEventCount;
//类型字符串
const char* stringType;
//代表应用要查看传感器、注册到传感器和接收传感器数据所必须具备的权限的字符串
const char* requiredPermission;
/* This value is defined only for continuous mode and on-change sensors. It is the delay between
* two sensor events corresponding to the lowest frequency that this sensor supports. When lower
* frequencies are requested through batch()/setDelay() the events will be generated at this
* frequency instead. It can be used by the framework or applications to estimate when the batch
* FIFO may be full.
*
* NOTE: 1) period_ns is in nanoseconds where as maxDelay/minDelay are in microseconds.
* continuous, on-change: maximum sampling period allowed in microseconds.
* one-shot, special : 0
* 2) maxDelay should always fit within a 32 bit signed integer. It is declared as 64 bit
* on 64 bit architectures only for binary compatibility reasons.
* Availability: SENSORS_DEVICE_API_VERSION_1_3
*/
#ifdef __LP64__
int64_t maxDelay;
#else
int32_t maxDelay;
#endif
/* Flags for sensor. See SENSOR_FLAG_* above. Only the least significant 32 bits are used here.
* It is declared as 64 bit on 64 bit architectures only for binary compatibility reasons.
* Availability: SENSORS_DEVICE_API_VERSION_1_3
*/
#ifdef __LP64__
uint64_t flags;
#else
uint32_t flags;
#endif
/* reserved fields, must be zero */
void* reserved[2];
}
这个结构体在实现hal层代码时,参数已又英文注释,重点关注handle、type、minDelay、flags.
typedef struct sensors_event_t {
//必须设置为sizeof(struct sensors_event_t)
int32_t version;
//传感器标识
int32_t sensor;
//传感器类型
int32_t type;
//保留为
int32_t reserved0;
//时间戳,单位ns
int64_t timestamp;
//传感器数据共用体,
union {
union {
float data[16];
/* acceleration values are in meter per second per second (m/s^2) */
sensors_vec_t acceleration;
/* magnetic vector values are in micro-Tesla (uT) */
sensors_vec_t magnetic;
/* orientation values are in degrees */
sensors_vec_t orientation;
/* gyroscope values are in rad/s */
sensors_vec_t gyro;
/* temperature is in degrees centigrade (Celsius) */
float temperature;
/* distance in centimeters */
float distance;
/* light in SI lux units */
float light;
/* pressure in hectopascal (hPa) */
float pressure;
/* relative humidity in percent */
float relative_humidity;
/* uncalibrated gyroscope values are in rad/s */
uncalibrated_event_t uncalibrated_gyro;
/* uncalibrated magnetometer values are in micro-Teslas */
uncalibrated_event_t uncalibrated_magnetic;
/* heart rate data containing value in bpm and status */
heart_rate_event_t heart_rate;
/* this is a special event. see SENSOR_TYPE_META_DATA above.
* sensors_meta_data_event_t events are all reported with a type of
* SENSOR_TYPE_META_DATA. The handle is ignored and must be zero.
*/
meta_data_event_t meta_data;
/* dynamic sensor meta event. See SENSOR_TYPE_DYNAMIC_SENSOR_META type for details */
dynamic_sensor_meta_event_t dynamic_sensor_meta;
/*
* special additional sensor information frame, see
* SENSOR_TYPE_ADDITIONAL_INFO for details.
*/
additional_info_event_t additional_info;
};
union {
uint64_t data[8];
/* step-counter */
uint64_t step_counter;
} u64;
};
/* Reserved flags for internal use. Set to zero. */
uint32_t flags;
uint32_t reserved1[3];
}
传感器数据上报的结构体,注意sensor和sensors_vec_t,sensor变量对应的是handle,如果不匹配将无法被上层enable,sensors_vec_t中的status默认为0,需要设置为大于0的状态,否则上层会将数据丢弃,status可选参数如下
#define SENSOR_STATUS_NO_CONTACT -1
#define SENSOR_STATUS_UNRELIABLE 0
#define SENSOR_STATUS_ACCURACY_LOW 1
#define SENSOR_STATUS_ACCURACY_MEDIUM 2
#define SENSOR_STATUS_ACCURACY_HIGH 3
HAL层以下部分各SOC厂商实现方式不同(有些走input,有些走IIO,有些走share memory),这里不继续追述.