赞
踩
Android Service是一种应用程序组件,可以在后台执行长时间运行的操作而不提供用户界面。
从native层调用connectHidlService()连接service,调用initializeSensorList();进行初始化
SensorDevice.cpp (linux\android\frameworks\native\services\sensorservice) 37979 2022/8/9
SensorDevice::SensorDevice()
: mHidlTransportErrors(20),
mRestartWaiter(new HidlServiceRegistrationWaiter()),
mEventQueueFlag(nullptr),
mWakeLockQueueFlag(nullptr),
mReconnecting(false) {
if (!connectHidlService()) {
return;
}
initializeSensorList();
mIsDirectReportSupported =
(checkReturnAndGetStatus(mSensors->unregisterDirectChannel(-1)) != INVALID_OPERATION);
}
connectHidlService()连接service
bool SensorDevice::connectHidlService() {
HalConnectionStatus status = connectHidlServiceV2_0();
if (status == HalConnectionStatus::DOES_NOT_EXIST) {
status = connectHidlServiceV1_0();
}
return (status == HalConnectionStatus::CONNECTED);
}
获取service接口
SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV2_0() {
HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
sp<V2_0::ISensors> sensors = V2_0::ISensors::getService();
if (sensors == nullptr) {
connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
} else {
mSensors = new SensorServiceUtil::SensorsWrapperV2_0(sensors);
mEventQueue = std::make_unique<EventMessageQueue>(
SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
true /* configureEventFlagWord */);
mWakeLockQueue = std::make_unique<WakeLockQueue>(
SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
true /* configureEventFlagWord */);
hardware::EventFlag::deleteEventFlag(&mEventQueueFlag);
hardware::EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag);
hardware::EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
hardware::EventFlag::createEventFlag(mWakeLockQueue->getEventFlagWord(),
&mWakeLockQueueFlag);
CHECK(mSensors != nullptr && mEventQueue != nullptr &&
mWakeLockQueue != nullptr && mEventQueueFlag != nullptr &&
mWakeLockQueueFlag != nullptr);
status_t status = checkReturnAndGetStatus(mSensors->initialize(
*mEventQueue->getDesc(),
*mWakeLockQueue->getDesc(),
new SensorsCallback()));
if (status != NO_ERROR) {
connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
ALOGE("Failed to initialize Sensors HAL (%s)", strerror(-status));
} else {
connectionStatus = HalConnectionStatus::CONNECTED;
mSensorsHalDeathReceiver = new SensorsHalDeathReceivier();
sensors->linkToDeath(mSensorsHalDeathReceiver, 0 /* cookie */);
}
}
return connectionStatus;
}
service 启动
Service.cpp (linux\android\vendor\qcom\proprietary\sensors-see\hal-2.0-hidl-impl) 967 2022/8/9
int main(int /* argc */, char** /* argv */) {
configureRpcThreadpool(1, true);
android::sp<ISensors> sensor_module = new sensors_hw_module;
if (sensor_module->registerAsService() != ::android::OK) {
ALOGE("Failed to register Sensors HAL instance");
return -1;
}
joinRpcThreadpool();
return 1; // joinRpcThreadpool shouldn't exit
}
获取 hal层接口
Sensors_hw_module.cpp (linux\android\vendor\qcom\proprietary\sensors-see\hal-2.0-hidl-impl) 12913 2022/8/9
sensors_hw_module::sensors_hw_module()
{
_hal = sensors_hal::get_instance();
_is_hal_configured = false;
}
Sensors_hal.cpp (linux\android\vendor\qcom\proprietary\sensors-see\sensors-hal-2.0\framework)
sensors_hal* sensors_hal::get_instance()
{
if(nullptr != _self) {
return _self;
} else {
_self = new sensors_hal();
return _self;
}
}
sensors_hal构造函数创建sensors_hal对象
sensors_hal::sensors_hal()
: _ssr_handler(nullptr)
{
using namespace std::chrono;
auto tp_start = steady_clock::now();
sensors_log::set_tag("sensors-hal");
get_system_config();
sensors_log::set_level(_sysconfig.log_level);
check_ssc_trace_support_flag();
_is_rt_thread_enable = is_rt_thread_enabled();
_is_worker_bypass_enable = is_worker_bypass_enabled();
_atrace_delay_checktime_ms = get_atrace_delay_checktime_ms();
#ifdef SNS_DIRECT_REPORT_SUPPORT
pthread_mutex_init(&open_direct_channels_mutex, NULL);
_offset_update_timer = NULL;
_dlhandler = NULL;
_llcmstubhandler = NULL;
#endif
if (false == sensors_restricted()) {
sns_logi("initializing sensors_hal");
try {
init_sensors();
#ifdef SNS_DIRECT_REPORT_SUPPORT
open_direct_channels = std::list<direct_channel *>();
struct sigevent sigev = {};
sigev.sigev_notify = SIGEV_THREAD;
sigev.sigev_notify_attributes = nullptr;
sigev.sigev_value.sival_ptr = (void *) this;
sigev.sigev_notify_function = on_offset_timer_update;
if (timer_create(CLOCK_BOOTTIME, &sigev, &_offset_update_timer) != 0) {
sns_loge("offset update timer creation failed: %s", strerror(errno));
}
#endif
} catch (const runtime_error& e) {
sns_loge("FATAL: failed to initialize sensors_hal: %s", e.what());
return;
}
}
else{
sns_logi(" enabling sensors from HAL is restricted ");
}
auto tp_end = steady_clock::now();
sns_logi("sensors_hal initialized, init_time = %fs",
duration_cast<duration<double>>(tp_end - tp_start).count());
_crashon_qmierror = crashon_qmierror();
}
initializeSensorList();进行初始化
调用mSensors->getSensorsList获取有哪些sensor,调用mSensors->activate进行初始化使能
void SensorDevice::initializeSensorList() {
float minPowerMa = 0.001; // 1 microAmp
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) {
ALOGI("Reported power %f not deemed sane, clamping to %f",
sensor.power, minPowerMa);
sensor.power = minPowerMa;
}
mSensorList.push_back(sensor);
mActivationCount.add(list[i].sensorHandle, model);
checkReturn(mSensors->activate(list[i].sensorHandle, 0 /* enabled */));
}
}));
}
使能流程如下:
Sensors_hw_module.cpp (linux\android\vendor\qcom\proprietary\sensors-see\hal-2.0-hidl-impl) 12913 2022/8/9
Return<Result> sensors_hw_module::activate(int32_t handle, bool en)
{
return ResultFromStatus(_hal->activate((int)handle,(int)en));
}
int sensors_hal::activate(int handle, int enable)
{
auto it = _sensors.find(handle);//_sensors来自哪里
if (it == _sensors.end()) {
sns_loge("handle %d not supported", handle);
return -EINVAL;
}
auto& sensor = it->second;
try {
sns_logi("%s/%d en=%d", sensor->get_sensor_info().stringType,
handle, enable);
if (enable) {
sensor->activate();
} else {
sensor->deactivate();
}
} catch (const exception& e) {
sns_loge("failed: %s", e.what());
if (true == _crashon_qmierror)
trigger_ssr();
return -1;
}
sns_logi("%s/%d en=%d completed", sensor->get_sensor_info().stringType,
handle, enable);
return 0;
}
以Accelerometer为例
Accelerometer.cpp (linux\android\vendor\qcom\proprietary\sensors-see\sensors-hal-2.0\sensors) 19681 2022/8/9
void accelerometer::activate()
{
_process_in_qmicallback = _is_rt_thread_enable;
if(_is_worker_bypass){
_process_in_qmicallback = _is_worker_bypass;
}
if (!is_active()) {
if (_accelcal_available) {
sns_logd("start accelcal");
start_accelcal();
}
ssc_sensor::activate();
}
}
Accelerometer.cpp (linux\android\vendor\qcom\proprietary\sensors-see\sensors-hal-2.0\sensors) 19681 2022/8/9
void ssc_sensor::activate()
{
_previous_ts = 0;
std::memset(&_prev_sample, 0x00, sizeof(sensors_event_t));
_activate_ts = android::elapsedRealtimeNano();
std::lock_guard<mutex> lk(_mutex);
if (!is_active()) {
/* establish a new connection to ssc */
_ssc_conn = make_unique<ssc_connection>(
[this](const uint8_t *data, size_t size, uint64_t ts)
{
ssc_conn_event_cb(data, size, ts);
});
string thread_name = "see_"+to_string(get_sensor_info().handle) ;
_ssc_conn->set_worker_name(thread_name.c_str());
_ssc_conn->ssc_configuration(_is_rt_thread_enable , _atrace_delay_checktime_ms );
if ( _wakeup_type == SENSOR_WAKEUP)
_ssc_conn->set_unsuspendable_channel();
_ssc_conn->register_error_cb([this](auto e){ this->ssc_conn_error_cb(e); });
_ssc_conn->register_resp_cb([this](uint32_t resp_value){ ssc_conn_resp_cb(resp_value); });
if(true == _is_stats_enable) {
_ts_diff_acc = 0;
_sample_cnt = 0;
_max_ts_rxved = 0;
_min_ts_rxved = MAX_UINT64;
_ts_diff_acc_hal = 0;
_max_ts_rxved_hal = 0;
_min_ts_rxved_hal = MAX_UINT64;
_ts_diff_acc_qmi = 0;
_max_ts_rxved_qmi = 0;
_min_ts_rxved_qmi = MAX_UINT64;
_previous_ssc_ts = 0;
_current_ssc_ts = 0;
_ssc_ts_diff_bw_samples = 0;
_acc_ssc_ts = 0;
_min_ssc_ts_diff = MAX_INT64;
_max_ssc_ts_diff = 0;
}
if(true == _is_ssc_latency_enable) {
_slpi_delay_til_CM = 0;
_slpi_sample_cnt = 0;
}
send_sensor_config_request();
_set_thread_name = true;
}
}
send_sensor_config_request();函数将发送请求到sensorhub中。
_sensors来自哪里?
Sensors_hal.cpp (linux\android\vendor\qcom\proprietary\sensors-see\sensors-hal-2.0\framework)
void sensors_hal::init_sensors()
{
auto sensors = sensor_factory::instance().get_all_available_sensors();
sns_logi("initializing sensors");
for (unique_ptr<sensor>& s : sensors) {
s->update_system_prop_details(_is_rt_thread_enable, _atrace_delay_checktime_ms, _is_worker_bypass_enable);
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);
_hal_sensors.push_back(sensor_info);
_sensors[sensor_info.handle] = std::move(s);
}
#ifdef SNS_DIRECT_REPORT_SUPPORT
update_remote_handlers();
#endif
//make persist QMI connection to catch SSR
if (_ssr_handler == nullptr) {
_ssr_handler = new ssc_connection(
[](const uint8_t *data, size_t size, uint64_t ts) {
sns_logd("don't expect anything here");
});
if (_ssr_handler != nullptr) {
_ssr_handler->ssc_configuration(false, 0);
_ssr_handler->register_resp_cb(
[](uint32_t resp_value) {
sns_logd("don't expect anything here");
});
_ssr_handler->register_error_cb(
[this](ssc_error_type e) {
if (e == SSC_CONNECTION_RESET) {
sns_logi("connection is reset. it's SSR");
for (auto& it : _sensors) {
auto& sensor = it.second;
const sensor_t& sensor_info = sensor->get_sensor_info();
sns_logd("%s: %s/%d : reset sensor", sensor_info.name,
sensor_info.stringType, sensor_info.handle);
sensor->reset();
}
#ifdef SNS_DIRECT_REPORT_SUPPORT
close_all_direct_channels();
sns_close_staticpd_channel();
sns_logi("dlcose(%s) llcmhandler=%p !", SNS_LOW_LAT_STUB_NAME, _llcmstubhandler);
dlclose(_llcmstubhandler);
_llcmstubhandler = NULL;
sns_logi("dlcose(%s) _dlhandler =%p !", _rpclib_name.c_str(), _dlhandler);
dlclose(_dlhandler);
_dlhandler = NULL;
update_remote_handlers();
#endif
};
});
sns_logi("SSR handler is registered");
} else {
sns_loge("fails to register SSR Handler");
}
}
}
Sensor_factory.cpp (linux\android\vendor\qcom\proprietary\sensors-see\sensors-hal\framework) 25865 2022/8/9
vector<unique_ptr<sensor>> sensor_factory::get_all_available_sensors() const
{
vector<unique_ptr<sensor>> all_sensors;
for (const auto& item : callbacks()) {
const auto& get_sensors = item.second;
vector<unique_ptr<sensor>> sensors = get_sensors();
if(sensors.size() == 0){
continue;
}
sns_logd("type=%d, num_sensors=%u", item.first, (unsigned int)sensors.size());
for (auto&& s : sensors) {
if(nullptr != s ) {
all_sensors.push_back(std::move(s));
}
}
}
return all_sensors;
}
static void register_sensor(int type, get_available_sensors_func func)
{
try {
callbacks().emplace(type, func);
} catch (const std::exception& e) {
sns_loge("failed to register type %d", type);
}
}
Accelerometer.cpp (linux\android\vendor\qcom\proprietary\sensors-see\sensors-hal-2.0\sensors) 19681 2022/8/9
static bool accelerometer_module_init()
{
/* register supported sensor types with factory */
sensor_factory::register_sensor(SENSOR_TYPE_ACCELEROMETER,
get_available_accel_calibrated);
sensor_factory::register_sensor(SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED,
get_available_accel_uncalibrated);
sensor_factory::request_datatype(SSC_DATATYPE_ACCEL, false);
char debug_prop[PROPERTY_VALUE_MAX];
int enable_accel_cal = 0;
int len;
len = property_get("persist.vendor.sensors.accel_cal", debug_prop, "0");
if (len > 0) {
enable_accel_cal = atoi(debug_prop);
}
if (enable_accel_cal)
{
sensor_factory::request_datatype(SSC_DATATYPE_ACCELCAL, false);
}
return true;
}
Accelerometer.cpp (linux\android\vendor\qcom\proprietary\sensors-see\sensors-hal-2.0\sensors) 19681 2022/8/9
static vector<unique_ptr<sensor>> get_available_accel_calibrated()
{
const vector<sensor_uid>& accel_suids =
sensor_factory::instance().get_suids(SSC_DATATYPE_ACCEL);
vector<unique_ptr<sensor>> sensors;
for (const auto& suid : accel_suids) {
bool default_sensor = sensor_factory::instance().is_default_sensor(SSC_DATATYPE_ACCEL, suid);
if (!(sensor_factory::instance().get_settings()
& DISABLE_WAKEUP_SENSORS_FLAG)) {
try {
sensors.push_back(make_unique<accelerometer>(suid, SENSOR_WAKEUP,
SENSOR_CALIBRATED, default_sensor));
} catch (const exception& e) {
sns_loge("failed for wakeup, %s", e.what());
}
}
try {
sensors.push_back(make_unique<accelerometer>(suid, SENSOR_NO_WAKEUP,
SENSOR_CALIBRATED, default_sensor));
} catch (const exception& e) {
sns_loge("failed for nowakeup, %s", e.what());
}
}
return sensors;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。