Android sensor整体框架
Java层到sensor service
java层SystemSensorManager的构造函数通过 jni接口函数:nativeCreate调到native层进而调用lib函数getInstanceForPackage, 该函数调用getService("sensorservice").获得了sensorservice的client.
sensor service的启动和实现
jlong
146nativeCreate
147(JNIEnv *env, jclass clazz, jstring opPackageName)
148{
149 ScopedUtfChars opPackageNameUtf(env, opPackageName);
150 return (jlong) &SensorManager::getInstanceForPackage(String16(opPackageNameUtf.c_str()));
151}
45SensorManager& SensorManager::getInstanceForPackage(const String16& packageName) {
46 waitForSensorService(nullptr);}
105status_t SensorManager::waitForSensorService(sp<ISensorServer> *server) {
106 // try for 300 seconds (60*5(getService() tries for 5 seconds)) before giving up ...
107 sp<ISensorServer> s;
108 const String16 name("sensorservice");
109 for (int i = 0; i < 60; i++) {
110 status_t err = getService(name, &s);
111 switch (err) {
112 case NAME_NOT_FOUND:
113 sleep(1);
114 continue;
115 case NO_ERROR:
116 if (server != nullptr) {
117 *server = s;
118 }
119 return NO_ERROR;
120 default:
121 return err;
122 }
123 }
124 return TIMED_OUT;
125}
Sensor Service层到 Sensor HAL层
java层SystemServer.java文件调用startBootstrapService: startBootstrapService: startSensorService 调用jni 函数启动SensorService, SensorService 也获得了hal sensor service的client, 去获得hal sersor service 的服务。
hal sensor service的实现和启动、调用到sensor具体实现so
代码路径:hardware/interfaces/sensors/1.0/default/
做为一个damon运行
1service vendor.sensors-hal-1-0 /vendor/bin/hw/android.hardware.sensors@1.0-service
2 class hal
3 user system
4 group system wakelock input
5 capabilities BLOCK_SUSPEND
6 rlimit rtprio 10 10
hardware/interfaces/sensors/1.0/default/service.cpp
42 int main() {
46 /* Sensors framework service needs at least two threads.
47 * One thread blocks on a "poll"
48 * The second thread is needed for all other HAL methods.
49 */
50 return defaultPassthroughServiceImplementation<ISensors>(2);
51}
defaultPassthroughServiceImplementation创建hidl服务并调用
344ISensors *HIDL_FETCH_ISensors(const char * /* hal */) {
345 Sensors *sensors = new Sensors;
352
353 return sensors;
354}
56Sensors::Sensors()
57 : mInitCheck(NO_INIT),
58 mSensorModule(nullptr),
59 mSensorDevice(nullptr) {
60 status_t err = OK;
61 if (UseMultiHal()) {
//mSensorModule的赋值, 已知的全局变量
62 mSensorModule = ::get_multi_hal_module_info();
63 }
82 //mSensorDevice的赋值
83 err = sensors_open_1(&mSensorModule->common, &mSensorDevice);
108
109 mInitCheck = OK;
110}
multiHal相关的实现在文件
libhardware/modules/sensors/multihal.cpp
764static struct hw_module_methods_t sensors_module_methods = {
765 .open = open_sensors
766};
767
768struct sensors_module_t HAL_MODULE_INFO_SYM = {
769 .common = {
770 .tag = HARDWARE_MODULE_TAG,
771 .version_major = 1,
772 .version_minor = 1,
773 .id = SENSORS_HARDWARE_MODULE_ID,
774 .name = "MultiHal Sensor Module",
775 .author = "Google, Inc",
776 .methods = &sensors_module_methods,
777 .dso = NULL,
778 .reserved = {0},
779 },
780 .get_sensors_list = module__get_sensors_list
781};
783 struct sensors_module_t *get_multi_hal_module_info() {
784 return (&HAL_MODULE_INFO_SYM);
785}
调到sensors_open_1(&mSensorModule->common, &mSensorDevice);
48/**
49 * The id of this module
50 */
51#define SENSORS_HARDWARE_MODULE_ID "sensors"
52
53/**
54 * Name of the sensors device to open
55 */
56#define SENSORS_HARDWARE_POLL "poll" //这里的名字怎么是poll
205#define TO_HW_DEVICE_T_OPEN(x) reinterpret_cast<struct hw_device_t**>(x)
724 static inline int sensors_open_1(const struct hw_module_t* module,
725 sensors_poll_device_1_t** device) {
726 return module->methods->open(module,
727 SENSORS_HARDWARE_POLL, TO_HW_DEVICE_T_OPEN(device));
728}
//1. 哪里找到 multihal?
//2. 怎样找到对应的hal?
787static int open_sensors(const struct hw_module_t* hw_module, const char* name,
788 struct hw_device_t** hw_device_out) {
789 ALOGV("open_sensors begin...");
790
791 lazy_init_modules();
792
793 // Create proxy device, to return later.
794 sensors_poll_context_t *dev = new sensors_poll_context_t();
795 memset(dev, 0, sizeof(sensors_poll_device_1_t));
796 dev->proxy_device.common.tag = HARDWARE_DEVICE_TAG;
797 dev->proxy_device.common.version = SENSORS_DEVICE_API_VERSION_1_4;
798 dev->proxy_device.common.module = const_cast<hw_module_t*>(hw_module);
799 dev->proxy_device.common.close = device__close;
800 dev->proxy_device.activate = device__activate;
801 dev->proxy_device.setDelay = device__setDelay;
802 dev->proxy_device.poll = device__poll;
803 dev->proxy_device.batch = device__batch;
804 dev->proxy_device.flush = device__flush;
805 dev->proxy_device.inject_sensor_data = device__inject_sensor_data;
806 dev->proxy_device.register_direct_channel = device__register_direct_channel;
807 dev->proxy_device.config_direct_report = device__config_direct_report;
808
809 dev->nextReadIndex = 0;
810
811 // Open() the subhal modules. Remember their devices in a vector parallel to sub_hw_modules.
812 for (std::vector<hw_module_t*>::iterator it = sub_hw_modules->begin();
813 it != sub_hw_modules->end(); it++) {
814 sensors_module_t *sensors_module = (sensors_module_t*) *it;
815 struct hw_device_t* sub_hw_device;
816 int sub_open_result = sensors_module->common.methods->open(*it, name, &sub_hw_device);
826 }
827
828 // Prepare the output param and return
829 *hw_device_out = &dev->proxy_device.common;
830 ALOGV("...open_sensors end");
831 return 0;
832}
629/*
630 * Ensures that the sub-module array is initialized.
631 * This can be first called from get_sensors_list or from open_sensors.
632 */
static const char* MULTI_HAL_CONFIG_FILE_PATH = "/vendor/etc/sensors/hals.conf";
633 static void lazy_init_modules() {
639 std::vector<std::string> so_paths(get_so_paths());
640
641 // dlopen the module files and cache their module symbols in sub_hw_modules
642 sub_hw_modules = new std::vector<hw_module_t *>();
643 so_handles = new std::vector<void *>();
644 dlerror(); // clear any old errors
645 const char* sym = HAL_MODULE_INFO_SYM_AS_STR;
646 for (const auto &s : so_paths) {
647 const char* path = s.c_str();
648 void* lib_handle = dlopen(path, RTLD_LAZY);
649 if (lib_handle == NULL) {
650 ALOGW("dlerror(): %s", dlerror());
651 } else {
652 ALOGI("Loaded library from %s", path);
653 ALOGV("Opening symbol \"%s\"", sym);
656 struct hw_module_t* module = (hw_module_t*) dlsym(lib_handle, sym);
657 const char* error;
658 if ((error = dlerror()) != NULL) {
659 ALOGW("Error calling dlsym: %s", error);
660
662 } else {
663 ALOGV("Loaded symbols from \"%s\"", sym);
664 sub_hw_modules->push_back(module);
665 so_handles->push_back(lib_handle);
666 lib_handle = nullptr;
667 }
668 }
669 if (lib_handle != nullptr) {
670 dlclose(lib_handle);
671 }
672 }
}
//找到所有sensor hal .so文件对应的路径
590/*
591 * Adds valid paths from the config file to the vector passed in.
592 * The vector must not be null.
593 */
594static std::vector<std::string> get_so_paths() {
595 std::vector<std::string> so_paths;
596
597 const std::vector<const char *> config_path_list(
598 { MULTI_HAL_CONFIG_FILE_PATH, DEPRECATED_MULTI_HAL_CONFIG_FILE_PATH });
599
600 std::ifstream stream;
601 const char *path = nullptr;
602 for (auto i : config_path_list) {
603 std::ifstream f(i);
604 if (f) {
605 stream = std::move(f);
606 path = i;
607 break;
608 }
609 }
614
615 ALOGE_IF(strcmp(path, DEPRECATED_MULTI_HAL_CONFIG_FILE_PATH) == 0,
616 "Multihal configuration file path %s is not compatible with Treble "
617 "requirements. Please move it to %s.",
618 path, MULTI_HAL_CONFIG_FILE_PATH);
619
620 ALOGV("Multihal config file found at %s", path);
621 std::string line;
622 while (std::getline(stream, line)) {
623 ALOGV("config file line: '%s'", line.c_str());
624 so_paths.push_back(line);
625 }
626 return so_paths;
627}
到此调用到hal的so实现,假设是SEE hal
SEE HAL的实现
和HAL接口
proprietary/sensors-see/sensors-hal/framework/sensors_hw_module.cpp
149struct sensors_module_t HAL_MODULE_INFO_SYM = {
150 .common = {
151 .tag = HARDWARE_MODULE_TAG,
152 .module_api_version = (uint16_t)SENSORS_DEVICE_API_VERSION_1_4,
153 .hal_api_version = HARDWARE_HAL_API_VERSION,
154 .id = SENSORS_HARDWARE_MODULE_ID,
155 .name = "QTI Sensors HAL Module",
156 .author = "Qualcomm Technologies, Inc.",
157 .methods = &sensors_module_methods,
158 .dso = NULL,
159 .reserved = {0},
160 },
161 .get_sensors_list = get_sensors_list,
162 .set_operation_mode = sensors_set_operation_mode,
163};
102 static int
103 sensors_open(const struct hw_module_t* module, const char* id,
104 struct hw_device_t** device)
105{
106 static sensors_hal_device_t sensors_hal_device;
107 sensors_poll_device_1_t* dev = &sensors_hal_device.device;
108 memset(dev, 0x00, sizeof(sensors_poll_device_1_t));
109 dev->common.tag = HARDWARE_DEVICE_TAG;
110 dev->common.version = SENSORS_DEVICE_API_VERSION_1_3;
111 dev->common.module = const_cast<hw_module_t*>(module);
112 dev->common.close = sensors_close;
113 dev->activate = sensors_activate;
114 dev->setDelay = sensors_set_delay;
115 dev->poll = sensors_poll;
116 dev->batch = sensors_batch;
117 dev->flush = sensors_flush;
118 dev->inject_sensor_data = sensors_inject_sensor_data;
128 sensors_hal_device.is_open = true;
129 *device = &dev->common;
130 return 0;
131}
1/**
32 * @brief class to represent entire sensors HAL. This class is
33 * the single entry-point for all HAL API calls.
34 *
35 */
36class sensors_hal
37{
38public:
39
40 /**
41 * @brief returns the singleton instance of the sensors_hal
42 * object
43 * @return sensors_hal& instance
44 */
45 static sensors_hal& get1/**
32 * @brief class to represent entire sensors HAL. This class is
33 * the single entry-point for all HAL API calls.
34 *
35 */
36class sensors_hal
37{
38public:
39
40 /**
41 * @brief returns the singleton instance of the sensors_hal
42 * object
43 * @return sensors_hal& instance
44 */
45 static sensors_hal& get_instance()
46 {
47 static sensors_hal hal;
48 return hal;
49 }
}
94sensors_hal::sensors_hal()
95{
109 if (false == sensors_restricted()) {
110 sns_logi("initializing sensors_hal");
111 try {
112 init_sensors();
}
}
238void sensors_hal::init_sensors()
239{
240 auto sensors = sensor_factory::instance().get_all_available_sensors();
242
243 sns_logi("initializing sensors");
}
SEE HAL和SEE的通信
//和SEE通信必须和SEE建立连接,具体实现就是ssc_qmi_connection
proprietary/commonsys-intf/sensors-see/ssc/ssc_connection.h
33/**
34 * @brief This class represents a live connection to SSC.
35 *
36 * All communication to sensors core happens using an instance
37 * of this class. Mupliple instances of this class are allowed
38 * and can work concurrently in a multi-threaded environment.
39 *
40 */
41class ssc_connection
42{
43public:
44 /**
45 * @brief creates a new connection to SSC and registers a
46 * callback funtion for events.
47 *
48 * @param event_cb register this function as a callback. this
49 * will be called when an event from ssc is
50 * received over this connection.
51 */
52 ssc_connection(ssc_event_cb event_cb);
86 private:
87 std::unique_ptr<ssc_qmi_connection> _qmi_conn;
88};
具体某个功能sensor的实现
49/**
50 * @brief abstract class representing a single physical or
51 * virtual sensor.
52 *
53 * This class defines an interface that is implemented by all
54 * sensors to be supported in HAL. This is used as a base class
55 * for all sensor implementations
56 *
57 */
58 class sensor
{
public:
61 sensor(sensor_wakeup_type wakeup_type);
62 virtual ~sensor() = default;
63
64 /**
65 * @brief activate sensor hardware, start streaming of the
66 * sensor events
67 */
68 virtual void activate() = 0;
}
31/**
32 * @brief Abstract class of all sensors which are implemented on
33 * SSC.
34 *
35 * This class provides common implementation for activating,
36 * deactivating and configuring sensors. This also contains
37 * logic for handling wakeup/nowakeup and batching
38 * functionality.
39 */
40class ssc_sensor : public sensor
41{
}
//这里建立的连接、设置的配置
159void ssc_sensor::activate()
160{
166 if (!is_active()) {
167 /* establish a new connection to ssc */
168 _ssc_conn = make_unique<ssc_connection>(
169 [this](const uint8_t *data, size_t size, uint64_t ts)
170 {
171 ssc_conn_event_cb(data, size, ts);
172 });
173 _ssc_conn->ssc_configuration(_is_rt_thread_enable , _atrace_delay_checktime_ms );
}
}
class sensor_factory的功能?
45/**
46 * @brief singleton class for creating sensor objects of
47 * multiple types, querying information such as SUIDs,
48 * attributes. Classes that implement sensors are
49 * registered here.
50 */
51class sensor_factory
52{
}
81 /**
82 * @brief generic function template for creating ssc_sensors of
83 * a given typename S
84 */
85 template<typename S>
86 static std::vector<std::unique_ptr<sensor>> get_available_sensors()
87 {
88 const char *datatype = S::ssc_datatype(); //静态成员
89 const std::vector<sensor_uid>& suids =
90 sensor_factory::instance().get_suids(datatype);
91 std::vector<std::unique_ptr<sensor>> sensors;
92 for (const auto& suid : suids) {
93 if (!(sensor_factory::instance().get_settings()
94 & DISABLE_WAKEUP_SENSORS_FLAG)) {
95 try {
96 sensors.push_back(std::make_unique<S>(suid, SENSOR_WAKEUP));//调用构造函数(suid, isWakup)
97 }
101 }
102 try {
103 sensors.push_back(std::make_unique<S>(suid, SENSOR_NO_WAKEUP));
104 }
108 }
109 return sensors;
110 }
// 创建了xxx_sensor, 并和type(int)关联
65 /**
66 * @brief register a new sensor type to be supported
67 *
68 * @param type sensor type as defined in sensors.h
69 * @param func factory function for creating sensors of this
70 * type
71 *
72 */
73 static void register_sensor(int type, get_available_sensors_func func)
74 {
75 try {
76 callbacks().emplace(type, func);
77 } catch (const std::exception& e) {
78 sns_loge("failed to register type %d", type);
79 }
80 }
113 /**
114 * @brief request a datatype to be queried when factory is
115 * initialized
116 *
117 * @param datatype
118 */
119 static void request_datatype(const char *datatype)
120 {
121 try {
122 datatypes().insert(std::string(datatype));
123 } catch (const std::exception& e) {
124 sns_loge("failed to insert %s", datatype);
125 }
126 }
SEE sensor 在HAL层具体的实现
1. 创建ssc_sensor的派生类
把SEE层实现的sensor data type, 传入ssc_sensor
实现private的接收、处理来着SEE的数据, 并调用submit_sensor_event上传数据到hal 层---
2. 构造函数
其中 sensor_type, sensor_datatype, sensor_string 名字相似,容易混淆
sensor_type(int): java API 注册sensor时使用
sensor_datatype(和SEE层定义的一致,用于和SUID对应,查找SUID)
sensor_sring类似 #define SENSOR_STRING_TYPE_HEART_BEAT "android.sensor.heart_beat"
heart_beat::heart_beat(sensor_uid suid, sensor_wakeup_type wakeup):
ssc_sensor(suid, wakeup)
{
set_type(SENSOR_TYPE_HEART_BEAT);
set_string_type(SENSOR_STRING_TYPE_HEART_BEAT);
}
2. 实现固定的结构函数
27static bool heart_beat_module_init()
28{
29 /* register supported sensor types with factory */
30 sensor_factory::register_sensor(SENSOR_TYPE_HEART_BEAT,
31 ssc_sensor::get_available_sensors<heart_beat>);
32 sensor_factory::request_datatype(SSC_DATATYPE_HEART_BEAT);
33 return true;
34}
35
36SENSOR_MODULE_INIT(heart_beat_module_init);
SEE层到 Sensor HAL
参考:
深入分析Android SensorService_goodnight1994的博客-CSDN博客_android sensorservice