diff --git a/frameworks/js/napi/include/async_callback_info.h b/frameworks/js/napi/include/async_callback_info.h index 017ea65a86cb965f2c9ec6208d0a7ac815bb79a2..57dd4a1d4de2b50d26e693d7e4f5d459d65e90bc 100644 --- a/frameworks/js/napi/include/async_callback_info.h +++ b/frameworks/js/napi/include/async_callback_info.h @@ -55,6 +55,7 @@ enum CallbackDataType { SUBSCRIBE_CALLBACK = 14, SUBSCRIBE_COMPASS = 15, GET_BODY_STATE = 16, + SENSOR_STATE_CHANGE = 17, }; struct GeomagneticData { @@ -110,6 +111,7 @@ public: BusinessError error; CallbackDataType type; vector sensorInfos; + SensorStatusEvent sensorStatusEvent; AsyncCallbackInfo(napi_env env, CallbackDataType type) : env(env), type(type) {} ~AsyncCallbackInfo() { diff --git a/frameworks/js/napi/include/sensor_js.h b/frameworks/js/napi/include/sensor_js.h index 5e8b0bacec91b4fa9a43eb5213df32a3d94dcd9b..ac9839ea45090390e9b1583df2b650330c0cae47 100644 --- a/frameworks/js/napi/include/sensor_js.h +++ b/frameworks/js/napi/include/sensor_js.h @@ -21,17 +21,18 @@ #include "napi/native_node_api.h" #include "async_callback_info.h" +#include "sensor.h" #include "sensor_agent.h" namespace OHOS { namespace Sensors { -int32_t UnsubscribeSensor(int32_t sensorTypeId); +int32_t UnsubscribeSensor(SensorDescription sensorDesc); void DataCallbackImpl(SensorEvent *event); -int32_t SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback); +int32_t SubscribeSensor(SensorDescription sensorDesc, int64_t interval, RecordSensorCallback callback); napi_value Subscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId, CallbackDataType type); napi_value Unsubscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId); napi_value GetBodyState(napi_env env, napi_callback_info info); -void CleanCallbackInfo(napi_env env, std::map>> &callbackInfo); +void CleanCallbackInfo(napi_env env, std::map>> &callbackInfo); void CleanOnCallbackInfo(napi_env env); void CleanOnceCallbackInfo(napi_env env); void CleanSubscribeCallbackInfo(napi_env env); diff --git a/frameworks/js/napi/include/sensor_napi_utils.h b/frameworks/js/napi/include/sensor_napi_utils.h index cbd70ed370f51ceeab3f05336e30f9695b4daa95..1b5ce939f644d65ea47bb6140789a2ab684d7631 100644 --- a/frameworks/js/napi/include/sensor_napi_utils.h +++ b/frameworks/js/napi/include/sensor_napi_utils.h @@ -60,6 +60,7 @@ bool ConvertToBodyData(const napi_env &env, sptr asyncCallbac bool ConvertToCompass(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); void ReleaseCallback(sptr asyncCallbackInfo); bool GetSelfTargetVersion(uint32_t &targetVersion); +bool ConvertToSensorState(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]); #define CHKNCF(env, cond, message) \ diff --git a/frameworks/js/napi/src/sensor_js.cpp b/frameworks/js/napi/src/sensor_js.cpp index f1d3140adf2709ec3ec7174fb9927f74812451e3..dc4f9b32a0735d605c23b152a6c563eee3f89325 100644 --- a/frameworks/js/napi/src/sensor_js.cpp +++ b/frameworks/js/napi/src/sensor_js.cpp @@ -36,12 +36,21 @@ namespace { constexpr int32_t QUATERNION_LENGTH = 4; constexpr int32_t ROTATION_VECTOR_LENGTH = 3; constexpr int32_t REPORTING_INTERVAL = 200000000; -constexpr int32_t INVALID_SENSOR_ID = -1; +constexpr int32_t INVALID_SENSOR_TYPE = -1; +constexpr int32_t DEFAULT_DEVICE_ID = -1; +constexpr int32_t DEFAULT_SENSOR_ID = 0; +constexpr int32_t IS_LOCAL_DEVICE = 1; +constexpr int32_t NON_LOCAL_DEVICE = 0; +constexpr int32_t INVALID_SUBSCRIBE_SIZE = -1; +constexpr int32_t DEFAULT_SUBSCRIBE_SIZE = 0; constexpr int32_t SENSOR_SUBSCRIBE_FAILURE = 1001; constexpr int32_t INPUT_ERROR = 202; constexpr float BODY_STATE_EXCEPT = 1.0f; constexpr float THRESHOLD = 0.000001f; constexpr uint32_t COMPATIBILITY_CHANGE_VERSION_API12 = 12; +constexpr int32_t ARGC_NUM_TWO = 2; +constexpr int32_t ARGC_NUM_THREE = 3; +constexpr int32_t ARGS_NUM_TWO = 2; } // namespace static std::map g_samplingPeriod = { {"normal", 200000000}, @@ -51,16 +60,18 @@ static std::map g_samplingPeriod = { static std::mutex g_mutex; static std::mutex g_bodyMutex; static float g_bodyState = -1.0f; -static std::map>> g_subscribeCallbacks; +static std::map>> g_subscribeCallbacks; static std::mutex g_onMutex; static std::mutex g_onceMutex; -static std::map>> g_onceCallbackInfos; -static std::map>> g_onCallbackInfos; +static std::mutex g_plugMutex; +static std::map>> g_onceCallbackInfos; +static std::map>> g_onCallbackInfos; +static std::vector> g_plugCallbackInfo; -static bool CheckSubscribe(int32_t sensorTypeId) +static bool CheckSubscribe(SensorDescription sensorDesc) { std::lock_guard onCallbackLock(g_onMutex); - auto iter = g_onCallbackInfos.find(sensorTypeId); + auto iter = g_onCallbackInfos.find(sensorDesc); return iter != g_onCallbackInfos.end(); } @@ -98,25 +109,21 @@ static bool copySensorData(sptr callbackInfo, SensorEvent *ev return true; } -static bool CheckSystemSubscribe(int32_t sensorTypeId) +static bool CheckSystemSubscribe(SensorDescription sensorDesc) { std::lock_guard subscribeLock(g_mutex); - auto iter = g_subscribeCallbacks.find(sensorTypeId); - if (iter == g_subscribeCallbacks.end()) { - return false; - } - return true; + auto iter = g_subscribeCallbacks.find(sensorDesc); + return iter != g_subscribeCallbacks.end(); } static void EmitSubscribeCallback(SensorEvent *event) { CHKPV(event); - int32_t sensorTypeId = event->sensorTypeId; - if (!CheckSystemSubscribe(sensorTypeId)) { + if (!CheckSystemSubscribe({event->deviceId, event->sensorTypeId, event->sensorId, event->location})) { return; } std::lock_guard subscribeLock(g_mutex); - auto callbacks = g_subscribeCallbacks[sensorTypeId]; + auto callbacks = g_subscribeCallbacks[{event->deviceId, event->sensorTypeId, event->sensorId, event->location}]; for (auto &callback : callbacks) { if (!copySensorData(callback, event)) { SEN_HILOGE("Copy sensor data failed"); @@ -129,12 +136,11 @@ static void EmitSubscribeCallback(SensorEvent *event) static void EmitOnCallback(SensorEvent *event) { CHKPV(event); - int32_t sensorTypeId = event->sensorTypeId; - if (!CheckSubscribe(sensorTypeId)) { + if (!CheckSubscribe({event->deviceId, event->sensorTypeId, event->sensorId, event->location})) { return; } std::lock_guard onCallbackLock(g_onMutex); - auto onCallbackInfos = g_onCallbackInfos[sensorTypeId]; + auto onCallbackInfos = g_onCallbackInfos[{event->deviceId, event->sensorTypeId, event->sensorId, event->location}]; for (auto &onCallbackInfo : onCallbackInfos) { if (!copySensorData(onCallbackInfo, event)) { SEN_HILOGE("Copy sensor data failed"); @@ -147,9 +153,8 @@ static void EmitOnCallback(SensorEvent *event) static void EmitOnceCallback(SensorEvent *event) { CHKPV(event); - int32_t sensorTypeId = event->sensorTypeId; std::lock_guard onceCallbackLock(g_onceMutex); - auto iter = g_onceCallbackInfos.find(sensorTypeId); + auto iter = g_onceCallbackInfos.find({event->deviceId, event->sensorTypeId, event->sensorId, event->location}); if (iter == g_onceCallbackInfos.end()) { return; } @@ -164,11 +169,13 @@ static void EmitOnceCallback(SensorEvent *event) } EmitUvEventLoop(std::move(onceCallbackInfo)); } - g_onceCallbackInfos.erase(sensorTypeId); + g_onceCallbackInfos.erase({event->deviceId, event->sensorTypeId, event->sensorId, event->location}); - CHKCV((!CheckSubscribe(sensorTypeId)), "Has client subscribe, not need cancel subscribe"); - CHKCV((!CheckSystemSubscribe(sensorTypeId)), "Has client subscribe system api, not need cancel subscribe"); - UnsubscribeSensor(sensorTypeId); + CHKCV((!CheckSubscribe({event->deviceId, event->sensorTypeId, event->sensorId, event->location})), + "Has client subscribe, not need cancel subscribe"); + CHKCV((!CheckSystemSubscribe({event->deviceId, event->sensorTypeId, event->sensorId, event->location})), + "Has client subscribe system api, not need cancel subscribe"); + UnsubscribeSensor({event->deviceId, event->sensorTypeId, event->sensorId, event->location}); } void DataCallbackImpl(SensorEvent *event) @@ -179,38 +186,65 @@ void DataCallbackImpl(SensorEvent *event) EmitOnceCallback(event); } +static void UpdatePlugInfo(SensorStatusEvent *plugEvent, sptr &asyncCallbackInfo) +{ + CALL_LOG_ENTER; + CHKPV(plugEvent); + asyncCallbackInfo->sensorStatusEvent = *plugEvent; + SEN_HILOGD("asyncCallbackInfo->sensorStatus : [ deviceId = %{public}d, isSensorOnline = %{public}d]", + asyncCallbackInfo->sensorStatusEvent.deviceId, asyncCallbackInfo->sensorStatusEvent.isSensorOnline); + return; +} + +void PlugDataCallbackImpl(SensorStatusEvent *plugEvent) +{ + CALL_LOG_ENTER; + CHKPV(plugEvent); + std::lock_guard plugCallbackLock(g_plugMutex); + for (auto& callback : g_plugCallbackInfo) { + UpdatePlugInfo(plugEvent, callback); + EmitUvEventLoop(callback); + } +} + const SensorUser user = { - .callback = DataCallbackImpl + .callback = DataCallbackImpl, + .plugCallback = PlugDataCallbackImpl }; -int32_t UnsubscribeSensor(int32_t sensorTypeId) +int32_t UnsubscribeSensor(SensorDescription sensorDesc) { CALL_LOG_ENTER; - int32_t ret = DeactivateSensor(sensorTypeId, &user); + int32_t ret = DeactivateSensorEnhanced({sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location}, &user); if (ret != ERR_OK) { SEN_HILOGE("DeactivateSensor failed"); return ret; } - return UnsubscribeSensor(sensorTypeId, &user); + return UnsubscribeSensorEnhanced({sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location}, &user); } -int32_t SubscribeSensor(int32_t sensorTypeId, int64_t interval, RecordSensorCallback callback) +int32_t SubscribeSensor(SensorDescription sensorDesc, int64_t interval, RecordSensorCallback callback) { CALL_LOG_ENTER; - int32_t ret = SubscribeSensor(sensorTypeId, &user); + int32_t ret = SubscribeSensorEnhanced({sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location}, &user); if (ret != ERR_OK) { SEN_HILOGE("SubscribeSensor failed"); return ret; } - ret = SetBatch(sensorTypeId, &user, interval, 0); + ret = SetBatchEnhanced({sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location}, &user, interval, 0); if (ret != ERR_OK) { SEN_HILOGE("SetBatch failed"); return ret; } - return ActivateSensor(sensorTypeId, &user); + return ActivateSensorEnhanced({sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location}, &user); } -void CleanCallbackInfo(napi_env env, std::map>> &callbackInfo) +void CleanCallbackInfo(napi_env env, std::map>> &callbackInfo) { for (auto &event : callbackInfo) { auto &vecCallbackInfo = event.second; @@ -250,14 +284,16 @@ void CleanUp(void *data) data = nullptr; } -static bool IsOnceSubscribed(napi_env env, int32_t sensorTypeId, napi_value callback) +static bool IsOnceSubscribed(napi_env env, SensorDescription sensorDesc, napi_value callback) { CALL_LOG_ENTER; - if (auto iter = g_onceCallbackInfos.find(sensorTypeId); iter == g_onceCallbackInfos.end()) { - SEN_HILOGW("Already subscribed, sensorTypeId:%{public}d", sensorTypeId); + auto iter = g_onceCallbackInfos.find(sensorDesc); + if (iter == g_onceCallbackInfos.end()) { + SEN_HILOGW("Already subscribed, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return false; } - std::vector> callbackInfos = g_onceCallbackInfos[sensorTypeId]; + std::vector> callbackInfos = g_onceCallbackInfos[sensorDesc]; for (auto callbackInfo : callbackInfos) { CHKPC(callbackInfo); if (callbackInfo->env != env) { @@ -273,11 +309,11 @@ static bool IsOnceSubscribed(napi_env env, int32_t sensorTypeId, napi_value call return false; } -static void UpdateOnceCallback(napi_env env, int32_t sensorTypeId, napi_value callback) +static void UpdateOnceCallback(napi_env env, SensorDescription sensorDesc, napi_value callback) { CALL_LOG_ENTER; std::lock_guard onceCallbackLock(g_onceMutex); - CHKCV((!IsOnceSubscribed(env, sensorTypeId, callback)), "The callback has been subscribed"); + CHKCV((!IsOnceSubscribed(env, sensorDesc, callback)), "The callback has been subscribed"); sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, ONCE_CALLBACK); CHKPV(asyncCallbackInfo); napi_status status = napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]); @@ -285,16 +321,63 @@ static void UpdateOnceCallback(napi_env env, int32_t sensorTypeId, napi_value ca ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); return; } - std::vector> callbackInfos = g_onceCallbackInfos[sensorTypeId]; + std::vector> callbackInfos = g_onceCallbackInfos[sensorDesc]; callbackInfos.push_back(asyncCallbackInfo); - g_onceCallbackInfos[sensorTypeId] = callbackInfos; + g_onceCallbackInfos[sensorDesc] = callbackInfos; +} + +static bool GetDeviceId(napi_env env, napi_value value, int32_t &deviceId) +{ + napi_value napi_deviceId = GetNamedProperty(env, value, "deviceId"); + if (!IsMatchType(env, napi_deviceId, napi_number)) { + SEN_HILOGE("deviceId failed"); + return false; + } + if (!GetNativeInt32(env, napi_deviceId, deviceId)) { + SEN_HILOGE("GetNativeInt64 failed"); + return false; + } + return true; +} + +static bool GetSensorId(napi_env env, napi_value value, int32_t &sensorId) +{ + napi_value napi_sensorId = GetNamedProperty(env, value, "sensorIndex"); + if (!IsMatchType(env, napi_sensorId, napi_number)) { + SEN_HILOGE("sensorIndex failed"); + return false; + } + if (!GetNativeInt32(env, napi_sensorId, sensorId)) { + SEN_HILOGE("GetNativeInt64 failed"); + return false; + } + return true; +} + +static bool GetLocationDeviceId(int32_t &deviceId) +{ + SensorInfo *sensorInfos = nullptr; + int32_t count = 0; + int32_t ret = GetAllSensors(&sensorInfos, &count); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("GetAllSensors failed"); + return false; + } + for (int32_t i = 0; i < count; ++i) { + if (sensorInfos[i].location == IS_LOCAL_DEVICE) { + SEN_HILOGD("The location deviceId is %{public}d", sensorInfos[i].deviceId); + deviceId = sensorInfos[i].deviceId; + return true; + } + } + return false; } static napi_value Once(napi_env env, napi_callback_info info) { CALL_LOG_ENTER; - size_t argc = 2; - napi_value args[2] = { 0 }; + size_t argc = 3; + napi_value args[3] = { 0 }; napi_value thisVar = nullptr; napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); if (status != napi_ok || argc < 2) { @@ -305,31 +388,34 @@ static napi_value Once(napi_env env, napi_callback_info info) ThrowErr(env, PARAMETER_ERROR, "Wrong argument type"); return nullptr; } - int32_t sensorTypeId = INVALID_SENSOR_ID; - if (!GetNativeInt32(env, args[0], sensorTypeId)) { + int32_t sensorType = INVALID_SENSOR_TYPE; + if (!GetNativeInt32(env, args[0], sensorType)) { ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get number fail"); return nullptr; } - if (!CheckSubscribe(sensorTypeId)) { + if (!CheckSubscribe({DEFAULT_DEVICE_ID, sensorType, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE})) { SEN_HILOGD("No subscription to change sensor data, registration is required"); - int32_t ret = SubscribeSensor(sensorTypeId, REPORTING_INTERVAL, DataCallbackImpl); + int32_t ret = SubscribeSensor({DEFAULT_DEVICE_ID, sensorType, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE}, + REPORTING_INTERVAL, DataCallbackImpl); if (ret != ERR_OK) { ThrowErr(env, ret, "SubscribeSensor fail"); return nullptr; } } - UpdateOnceCallback(env, sensorTypeId, args[1]); + UpdateOnceCallback(env, {DEFAULT_DEVICE_ID, sensorType, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE}, args[1]); return nullptr; } -static bool IsSubscribed(napi_env env, int32_t sensorTypeId, napi_value callback) +static bool IsSubscribed(napi_env env, SensorDescription sensorDesc, napi_value callback) { CALL_LOG_ENTER; - if (auto iter = g_onCallbackInfos.find(sensorTypeId); iter == g_onCallbackInfos.end()) { - SEN_HILOGW("No client subscribe, sensorTypeId:%{public}d", sensorTypeId); + auto iter = g_onCallbackInfos.find(sensorDesc); + if (iter == g_onCallbackInfos.end()) { + SEN_HILOGW("No client subscribe, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return false; } - std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; + std::vector> callbackInfos = g_onCallbackInfos[sensorDesc]; for (auto callbackInfo : callbackInfos) { CHKPC(callbackInfo); if (callbackInfo->env != env) { @@ -345,11 +431,11 @@ static bool IsSubscribed(napi_env env, int32_t sensorTypeId, napi_value callback return false; } -static void UpdateCallbackInfos(napi_env env, int32_t sensorTypeId, napi_value callback) +static void UpdateCallbackInfos(napi_env env, SensorDescription sensorDesc, napi_value callback) { CALL_LOG_ENTER; std::lock_guard onCallbackLock(g_onMutex); - CHKCV((!IsSubscribed(env, sensorTypeId, callback)), "The callback has been subscribed"); + CHKCV((!IsSubscribed(env, sensorDesc, callback)), "The callback has been subscribed"); sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, ON_CALLBACK); CHKPV(asyncCallbackInfo); napi_status status = napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]); @@ -357,9 +443,9 @@ static void UpdateCallbackInfos(napi_env env, int32_t sensorTypeId, napi_value c ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); return; } - std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; + std::vector> callbackInfos = g_onCallbackInfos[sensorDesc]; callbackInfos.push_back(asyncCallbackInfo); - g_onCallbackInfos[sensorTypeId] = callbackInfos; + g_onCallbackInfos[sensorDesc] = callbackInfos; } static bool GetInterval(napi_env env, napi_value value, int64_t &interval) @@ -390,6 +476,123 @@ static bool GetInterval(napi_env env, napi_value value, int64_t &interval) return true; } +static bool IsPlugSubscribed(napi_env env, napi_value callback) +{ + CALL_LOG_ENTER; + for (auto callbackInfo : g_plugCallbackInfo) { + CHKPC(callbackInfo); + if (callbackInfo->env != env) { + continue; + } + napi_value plugCallback = nullptr; + CHKNRF(env, napi_get_reference_value(env, callbackInfo->callback[0], &plugCallback), + "napi_get_reference_value"); + if (IsSameValue(env, callback, plugCallback)) { + return true; + } + } + return false; +} + +static void UpdatePlugCallbackInfos(const napi_env& env, napi_value callback) +{ + CALL_LOG_ENTER; + std::lock_guard plugCallbackLock(g_plugMutex); + CHKCV((!IsPlugSubscribed(env, callback)), "The plugCallback has been subscribed"); + sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, SENSOR_STATE_CHANGE); + CHKPV(asyncCallbackInfo); + napi_status status = napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]); + if (status != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail"); + return; + } + g_plugCallbackInfo.push_back(asyncCallbackInfo); +} + +int32_t SubscribeSensorPlug(SensorPlugCallback callback) +{ + CALL_LOG_ENTER; + int32_t ret = SubscribeSensorPlug(&user); + if (ret != ERR_OK) { + SEN_HILOGE("SubscribeSensorPlug failed"); + } + return ret; +} + +static napi_value OnPlugSensor(napi_env env, const napi_value type, const napi_value callback) +{ + CALL_LOG_ENTER; + std::string plugType; + CHKCP(GetStringValue(env, type, plugType), "get plugType fail"); + if (plugType != "sensorStatusChange") { + ThrowErr(env, PARAMETER_ERROR, "Wrong sensorStatusChange type"); + return nullptr; + } + int32_t ret = SubscribeSensorPlug(PlugDataCallbackImpl); + if (ret != ERR_OK) { + ThrowErr(env, ret, "SubscribeSensorPlug fail"); + return nullptr; + } + UpdatePlugCallbackInfos(env, callback); + return nullptr; +} + +static bool GetDeviceIdBySensorInfoParam(napi_env env, napi_value value, int32_t &deviceId) +{ + napi_value napiSensorInfoParam = GetNamedProperty(env, value, "sensorInfoParam"); + if (!IsMatchType(env, napiSensorInfoParam, napi_object)) { + SEN_HILOGW("sensorInfoParam failed"); + return false; + } + if (!GetDeviceId(env, napiSensorInfoParam, deviceId)) { + return false; + } + return true; +} + +static bool GetSensorIdBySensorInfoParam(napi_env env, napi_value value, int32_t &sensorId) +{ + napi_value napiSensorInfoParam = GetNamedProperty(env, value, "sensorInfoParam"); + if (!IsMatchType(env, napiSensorInfoParam, napi_object)) { + SEN_HILOGW("sensorInfoParam failed"); + return false; + } + if (!GetSensorId(env, napiSensorInfoParam, sensorId)) { + return false; + } + return true; +} + +static bool GetOptionalParameter(napi_env env, size_t argc, napi_value args, int64_t &interval, + SensorDescription &sensorDesc) +{ + int32_t localDeviceId = DEFAULT_DEVICE_ID; + if (!GetLocationDeviceId(localDeviceId)) { + SEN_HILOGW("Cant fand local deviceId, default loacl deviceId :%{public}d", localDeviceId); + } + sensorDesc.deviceId = localDeviceId; + sensorDesc.sensorId = DEFAULT_SENSOR_ID; + sensorDesc.location = IS_LOCAL_DEVICE; + if (argc >= ARGC_NUM_THREE && IsMatchType(env, args, napi_object)) { + if (!GetInterval(env, args, interval)) { + SEN_HILOGW("Get interval failed"); + } + if (!GetDeviceIdBySensorInfoParam(env, args, sensorDesc.deviceId)) { + SEN_HILOGW("No deviceId, This device is selected by default"); + sensorDesc.deviceId = localDeviceId; + } + if (!GetSensorIdBySensorInfoParam(env, args, sensorDesc.sensorId)) { + sensorDesc.sensorId = DEFAULT_SENSOR_ID; + SEN_HILOGW("No sensorId, The first sensor of the type is selected by default"); + } + } + if (sensorDesc.deviceId != localDeviceId) { + sensorDesc.location = NON_LOCAL_DEVICE; + } + SEN_HILOGD("Interval is %{public}" PRId64, interval); + return true; +} + static napi_value On(napi_env env, napi_callback_info info) { CALL_LOG_ENTER; @@ -401,36 +604,118 @@ static napi_value On(napi_env env, napi_callback_info info) ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); return nullptr; } + if (IsMatchType(env, args[0], napi_string) && IsMatchType(env, args[1], napi_function)) { + return OnPlugSensor(env, args[0], args[1]); + } if ((!IsMatchType(env, args[0], napi_number)) || (!IsMatchType(env, args[1], napi_function))) { ThrowErr(env, PARAMETER_ERROR, "Wrong argument type"); return nullptr; } - int32_t sensorTypeId = INVALID_SENSOR_ID; - if (!GetNativeInt32(env, args[0], sensorTypeId)) { + SensorDescription sensorDesc; + sensorDesc.sensorType = INVALID_SENSOR_TYPE; + if (!GetNativeInt32(env, args[0], sensorDesc.sensorType)) { ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get number fail"); return nullptr; } int64_t interval = REPORTING_INTERVAL; - if (argc >= 3 && IsMatchType(env, args[2], napi_object)) { - if (!GetInterval(env, args[2], interval)) { - SEN_HILOGW("Get interval failed"); - } + if (!GetOptionalParameter(env, argc, args[ARGS_NUM_TWO], interval, sensorDesc)) { + SEN_HILOGE("location deviceId fail"); + return nullptr; } - SEN_HILOGD("Interval is %{public}" PRId64, interval); - int32_t ret = SubscribeSensor(sensorTypeId, interval, DataCallbackImpl); + int32_t ret = SubscribeSensor(sensorDesc, interval, DataCallbackImpl); if (ret != ERR_OK) { ThrowErr(env, ret, "SubscribeSensor fail"); return nullptr; } - UpdateCallbackInfos(env, sensorTypeId, args[1]); + UpdateCallbackInfos(env, sensorDesc, args[1]); + return nullptr; +} + +static int32_t RemoveAllPlugCallback(napi_env env) +{ + CALL_LOG_ENTER; + std::lock_guard plugCallbackLock(g_plugMutex); + for (auto iter = g_plugCallbackInfo.begin(); iter != g_plugCallbackInfo.end();) { + CHKPC(*iter); + if ((*iter)->env != env) { + ++iter; + continue; + } + iter = g_plugCallbackInfo.erase(iter); + } + if (g_plugCallbackInfo.empty()) { + SEN_HILOGD("No subscription to change sensor data"); + return DEFAULT_SUBSCRIBE_SIZE; + } + return g_plugCallbackInfo.size(); +} + +static int32_t RemovePlugCallback(napi_env env, napi_value callback) +{ + CALL_LOG_ENTER; + std::lock_guard plugCallbackLock(g_plugMutex); + for (auto iter = g_plugCallbackInfo.begin(); iter != g_plugCallbackInfo.end();) { + CHKPC(*iter); + if ((*iter)->env != env) { + continue; + } + napi_value sensorCallback = nullptr; + if (napi_get_reference_value(env, (*iter)->callback[0], &sensorCallback) != napi_ok) { + SEN_HILOGE("napi_get_reference_value fail"); + continue; + } + if (IsSameValue(env, callback, sensorCallback)) { + iter = g_plugCallbackInfo.erase(iter); + SEN_HILOGD("Remove callback success"); + break; + } else { + ++iter; + } + } + if (g_plugCallbackInfo.empty()) { + SEN_HILOGD("No subscription to change sensor data"); + return DEFAULT_SUBSCRIBE_SIZE; + } + return g_plugCallbackInfo.size(); +} + +static napi_value OffPlugSensor(napi_env env, size_t argc, const napi_value type, const napi_value callback) +{ + CALL_LOG_ENTER; + std::string plugType; + CHKCP(GetStringValue(env, type, plugType), "get plugType fail"); + if (plugType != "sensorStatusChange") { + ThrowErr(env, PARAMETER_ERROR, "Wrong sensorStatusChange type"); + return nullptr; + } + int32_t subscribeSize = INVALID_SUBSCRIBE_SIZE; + if (argc == 1) { + subscribeSize = RemoveAllPlugCallback(env); + } else if (IsMatchType(env, callback, napi_undefined) || IsMatchType(env, callback, napi_null)) { + subscribeSize = RemoveAllPlugCallback(env); + } else if (IsMatchType(env, callback, napi_function)) { + subscribeSize = RemovePlugCallback(env, callback); + } else { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, args[1] should is napi_function"); + return nullptr; + } + if (subscribeSize > DEFAULT_SUBSCRIBE_SIZE) { + SEN_HILOGW("There are other client subscribe system js api as well, not need unsubscribe"); + return nullptr; + } + int32_t ret = UnsubscribeSensorPlug(&user); + if (ret != ERR_OK) { + ThrowErr(env, ret, "UnSubscribeSensorPlug fail"); + return nullptr; + } return nullptr; } -static int32_t RemoveAllCallback(napi_env env, int32_t sensorTypeId) +static int32_t RemoveAllCallback(napi_env env, SensorDescription sensorDesc) { CALL_LOG_ENTER; std::lock_guard onCallbackLock(g_onMutex); - std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; + std::vector> callbackInfos = g_onCallbackInfos[sensorDesc]; for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) { CHKPC(*iter); if ((*iter)->env != env) { @@ -441,18 +726,18 @@ static int32_t RemoveAllCallback(napi_env env, int32_t sensorTypeId) } if (callbackInfos.empty()) { SEN_HILOGD("No subscription to change sensor data"); - g_onCallbackInfos.erase(sensorTypeId); - return 0; + g_onCallbackInfos.erase(sensorDesc); + return DEFAULT_SUBSCRIBE_SIZE; } - g_onCallbackInfos[sensorTypeId] = callbackInfos; + g_onCallbackInfos[sensorDesc] = callbackInfos; return callbackInfos.size(); } -static int32_t RemoveCallback(napi_env env, int32_t sensorTypeId, napi_value callback) +static int32_t RemoveCallback(napi_env env, SensorDescription sensorDesc, napi_value callback) { CALL_LOG_ENTER; std::lock_guard onCallbackLock(g_onMutex); - std::vector> callbackInfos = g_onCallbackInfos[sensorTypeId]; + std::vector> callbackInfos = g_onCallbackInfos[sensorDesc]; for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) { CHKPC(*iter); if ((*iter)->env != env) { @@ -473,45 +758,103 @@ static int32_t RemoveCallback(napi_env env, int32_t sensorTypeId, napi_value cal } if (callbackInfos.empty()) { SEN_HILOGD("No subscription to change sensor data"); - g_onCallbackInfos.erase(sensorTypeId); - return 0; + g_onCallbackInfos.erase(sensorDesc); + return DEFAULT_SUBSCRIBE_SIZE; } - g_onCallbackInfos[sensorTypeId] = callbackInfos; + g_onCallbackInfos[sensorDesc] = callbackInfos; return callbackInfos.size(); } +static bool GetSensorInfoParameter(napi_env env, size_t argc, napi_value args, SensorDescription &sensorDesc) +{ + int32_t localDeviceId = DEFAULT_DEVICE_ID; + if (!GetLocationDeviceId(localDeviceId)) { + SEN_HILOGW("Cant fand local deviceId, default loacl deviceId :%{public}d", localDeviceId); + } + sensorDesc.deviceId = localDeviceId; + sensorDesc.sensorId = DEFAULT_SENSOR_ID; + sensorDesc.location = IS_LOCAL_DEVICE; + if (argc >= ARGC_NUM_TWO && IsMatchType(env, args, napi_object)) { + if (!GetDeviceId(env, args, sensorDesc.deviceId)) { + SEN_HILOGW("No deviceId, This device is selected by default"); + sensorDesc.deviceId = localDeviceId; + } + if (!GetSensorId(env, args, sensorDesc.sensorId)) { + sensorDesc.sensorId = DEFAULT_SENSOR_ID; + SEN_HILOGW("No sensorId, The first sensor of the type is selected by default"); + } + } else if ((argc == 1) || IsMatchType(env, args, napi_undefined) || + IsMatchType(env, args, napi_null)) { + SEN_HILOGW("no deviceId, sensorIndex, Select the default deviceId and sensorIndex."); + } else { + return false; + } + if (sensorDesc.deviceId != localDeviceId) { + sensorDesc.location = NON_LOCAL_DEVICE; + } + return true; +} + +static bool GetSensorType(napi_env env, napi_value args, SensorDescription &sensorDesc) +{ + sensorDesc.sensorType = INVALID_SENSOR_TYPE; + if ((!IsMatchType(env, args, napi_number)) || (!GetNativeInt32(env, args, sensorDesc.sensorType))) { + return false; + } + int32_t localDeviceId = DEFAULT_DEVICE_ID; + if (!GetLocationDeviceId(localDeviceId)) { + SEN_HILOGW("Cant fand local deviceId, default loacl deviceId :%{public}d", localDeviceId); + } + sensorDesc.deviceId = localDeviceId; + sensorDesc.sensorId = DEFAULT_SENSOR_ID; + sensorDesc.location = IS_LOCAL_DEVICE; + return true; +} + static napi_value Off(napi_env env, napi_callback_info info) { CALL_LOG_ENTER; - size_t argc = 2; - napi_value args[2] = { 0 }; + size_t argc = 3; + napi_value args[3] = { 0 }; napi_value thisVar = nullptr; napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); if (status != napi_ok || argc < 1) { ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); return nullptr; } - int32_t sensorTypeId = INVALID_SENSOR_ID; - if ((!IsMatchType(env, args[0], napi_number)) || (!GetNativeInt32(env, args[0], sensorTypeId))) { + if (IsMatchType(env, args[0], napi_string)) { + return OffPlugSensor(env, argc, args[0], args[1]); + } + SensorDescription sensorDesc; + if (!GetSensorType(env, args[0], sensorDesc)) { ThrowErr(env, PARAMETER_ERROR, "Wrong argument type or get number fail"); return nullptr; } - int32_t subscribeSize = -1; + napi_value args_tmp = args[1]; + if (!IsMatchType(env, args_tmp, napi_function)) { + args_tmp = args[ARGS_NUM_TWO]; + if (!GetSensorInfoParameter(env, argc, args[1], sensorDesc)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, args[1] should is napi_object"); + return nullptr; + } + } + int32_t subscribeSize = INVALID_SUBSCRIBE_SIZE; if (argc == 1) { - subscribeSize = RemoveAllCallback(env, sensorTypeId); - } else if (IsMatchType(env, args[1], napi_undefined) || IsMatchType(env, args[1], napi_null)) { - subscribeSize = RemoveAllCallback(env, sensorTypeId); - } else if (IsMatchType(env, args[1], napi_function)) { - subscribeSize = RemoveCallback(env, sensorTypeId, args[1]); + subscribeSize = RemoveAllCallback(env, sensorDesc); + } else if (IsMatchType(env, args_tmp, napi_undefined) || + IsMatchType(env, args_tmp, napi_null)) { + subscribeSize = RemoveAllCallback(env, sensorDesc); + } else if (IsMatchType(env, args_tmp, napi_function)) { + subscribeSize = RemoveCallback(env, sensorDesc, args_tmp); } else { - ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, args[1] should is napi_function"); + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, args[2] should is napi_function"); return nullptr; } - if (CheckSystemSubscribe(sensorTypeId) || (subscribeSize > 0)) { + if (CheckSystemSubscribe(sensorDesc) || (subscribeSize > DEFAULT_SUBSCRIBE_SIZE)) { SEN_HILOGW("There are other client subscribe system js api as well, not need unsubscribe"); return nullptr; } - int32_t ret = UnsubscribeSensor(sensorTypeId); + int32_t ret = UnsubscribeSensor(sensorDesc); if (ret == PARAMETER_ERROR || ret == PERMISSION_DENIED) { ThrowErr(env, ret, "UnsubscribeSensor fail"); } @@ -1091,7 +1434,7 @@ static napi_value GetSingleSensor(napi_env env, napi_callback_info info) ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); return nullptr; } - int32_t sensorTypeId = INVALID_SENSOR_ID; + int32_t sensorTypeId = INVALID_SENSOR_TYPE; if (!GetNativeInt32(env, args[0], sensorTypeId)) { ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get number fail"); return nullptr; @@ -1147,7 +1490,7 @@ static napi_value GetSingleSensorSync(napi_env env, napi_callback_info info) ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); return result; } - int32_t sensorTypeId = INVALID_SENSOR_ID; + int32_t sensorTypeId = INVALID_SENSOR_TYPE; if (!GetNativeInt32(env, args[0], sensorTypeId)) { ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get number fail"); return result; @@ -1182,6 +1525,166 @@ static napi_value GetSingleSensorSync(napi_env env, napi_callback_info info) return result; } +static void FilteringSensorList(SensorInfo *sensorInfos, vector &callbackSensorInfo, int32_t count) +{ + for (int32_t i = 0; i < count; ++i) { + if ((sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_AMBIENT_LIGHT1) || + (sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_PROXIMITY1) || + (sensorInfos[i].sensorTypeId > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE)) { + SEN_HILOGD("This sensor is secondary ambient light"); + continue; + } + callbackSensorInfo.push_back(*(sensorInfos + i)); + } + return; +} + +static napi_value GetSensorListByDeviceSync(napi_env env, napi_callback_info info) +{ + CALL_LOG_ENTER; + size_t argc = 1; + napi_value args[1] = { 0 }; + napi_value result = nullptr; + napi_get_undefined(env, &result); + napi_value thisVar = nullptr; + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if (status != napi_ok) { + SEN_HILOGE("napi_get_cb_info fail or number of parameter invalid"); + return result; + } + int32_t deviceId = DEFAULT_DEVICE_ID; + if (!GetNativeInt32(env, args[0], deviceId)) { + SEN_HILOGW("Get deviceId failed"); + if (!GetLocationDeviceId(deviceId)) { + SEN_HILOGW("Cant fand local deviceId, default deviceId :%{public}d", deviceId); + } + } + SensorInfo *sensorInfos = nullptr; + int32_t count = 0; + int32_t ret = GetDeviceSensors(deviceId, &sensorInfos, &count); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Get deviceSensorList failed, ret:%{public}d", deviceId); + return result; + } + vector sensorInfoVec; + FilteringSensorList(sensorInfos, sensorInfoVec, count); + if (napi_create_array(env, &result) != napi_ok) { + SEN_HILOGE("napi_create_array fail"); + return result; + } + for (uint32_t i = 0; i < sensorInfoVec.size(); ++i) { + napi_value value = nullptr; + if (!ConvertToSensorInfo(env, sensorInfoVec[i], value)) { + SEN_HILOGE("Convert sensor info fail"); + return result; + } + if (napi_set_element(env, result, i, value) != napi_ok) { + SEN_HILOGE("napi_set_element fail"); + } + } + return result; +} + +static void FilteringSingleSensorList(SensorInfo *sensorInfos, vector &callbackSensorInfo, int32_t count, + int32_t sensorTypeId) +{ + for (int32_t i = 0; i < count; ++i) { + if ((sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_AMBIENT_LIGHT1) || + (sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_PROXIMITY1) || + (sensorInfos[i].sensorTypeId > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE)) { + SEN_HILOGD("This sensor is secondary ambient light"); + continue; + } + if (sensorInfos[i].sensorTypeId == sensorTypeId) { + callbackSensorInfo.push_back(*(sensorInfos + i)); + } + } + return; +} + +static napi_value GetSingleSensorByDeviceSync(napi_env env, napi_callback_info info) +{ + CALL_LOG_ENTER; + size_t argc = 2; + napi_value args[2] = { 0 }; + napi_value result = nullptr; + napi_get_undefined(env, &result); + napi_value thisVar = nullptr; + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if (status != napi_ok || argc < 1) { + SEN_HILOGE("napi_get_cb_info fail or number of parameter invalid"); + return result; + } + int32_t sensorTypeId = INVALID_SENSOR_TYPE; + if (!GetNativeInt32(env, args[0], sensorTypeId)) { + SEN_HILOGE("Wrong argument type, get number fail"); + return result; + } + int32_t deviceId = DEFAULT_DEVICE_ID; + if (!GetNativeInt32(env, args[1], deviceId)) { + SEN_HILOGW("Get deviceId failed"); + if (!GetLocationDeviceId(deviceId)) { + SEN_HILOGW("Cant fand local deviceId, default deviceId :%{public}d", deviceId); + } + } + SensorInfo *sensorInfos = nullptr; + int32_t count = 0; + int32_t ret = GetDeviceSensors(deviceId, &sensorInfos, &count); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Get sensor list fail"); + return result; + } + vector sensorInfoVec; + FilteringSingleSensorList(sensorInfos, sensorInfoVec, count, sensorTypeId); + if (napi_create_array(env, &result) != napi_ok) { + SEN_HILOGE("napi_create_array fail"); + return result; + } + for (uint32_t i = 0; i < sensorInfoVec.size(); ++i) { + napi_value value = nullptr; + if (!ConvertToSensorInfo(env, sensorInfoVec[i], value)) { + SEN_HILOGE("Convert sensor info fail"); + return result; + } + if (napi_set_element(env, result, i, value) != napi_ok) { + SEN_HILOGE("napi_set_element fail"); + } + } + return result; +} + +bool RegisterSubscribeCallback(napi_env env, napi_value args, sptr &asyncCallbackInfo, + napi_value &napiFail, string interval) +{ + napi_value napiSuccess = GetNamedProperty(env, args, "success"); + if (!IsMatchType(env, napiSuccess, napi_function)) { + SEN_HILOGE("get napiSuccess fail"); + return false; + } + if (!RegisterNapiCallback(env, napiSuccess, asyncCallbackInfo->callback[0])) { + SEN_HILOGE("register success callback fail"); + return false; + } + napiFail = GetNamedProperty(env, args, "fail"); + if (IsMatchType(env, napiFail, napi_function)) { + SEN_HILOGD("Has fail callback"); + if (!RegisterNapiCallback(env, napiFail, asyncCallbackInfo->callback[1])) { + SEN_HILOGE("register fail callback fail"); + return false; + } + } + if (auto iter = g_samplingPeriod.find(interval); iter == g_samplingPeriod.end()) { + if (!IsMatchType(env, napiFail, napi_function)) { + SEN_HILOGE("input error, interval is invalid"); + return false; + } + CreateFailMessage(SUBSCRIBE_FAIL, INPUT_ERROR, "input error", asyncCallbackInfo); + EmitAsyncCallbackWork(asyncCallbackInfo); + return false; + } + return true; +} + napi_value Subscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId, CallbackDataType type) { CALL_LOG_ENTER; @@ -1206,21 +1709,14 @@ napi_value Subscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId } sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, type); CHKPP(asyncCallbackInfo); - napi_value napiSuccess = GetNamedProperty(env, args[0], "success"); - CHKCP(IsMatchType(env, napiSuccess, napi_function), "get napiSuccess fail"); - CHKCP(RegisterNapiCallback(env, napiSuccess, asyncCallbackInfo->callback[0]), "register success callback fail"); - napi_value napiFail = GetNamedProperty(env, args[0], "fail"); - if (IsMatchType(env, napiFail, napi_function)) { - SEN_HILOGD("Has fail callback"); - CHKCP(RegisterNapiCallback(env, napiFail, asyncCallbackInfo->callback[1]), "register fail callback fail"); - } - if (auto iter = g_samplingPeriod.find(interval); iter == g_samplingPeriod.end()) { - CHKCP(IsMatchType(env, napiFail, napi_function), "input error, interval is invalid"); - CreateFailMessage(SUBSCRIBE_FAIL, INPUT_ERROR, "input error", asyncCallbackInfo); - EmitAsyncCallbackWork(asyncCallbackInfo); - return nullptr; - } - int32_t ret = SubscribeSensor(sensorTypeId, g_samplingPeriod[interval], DataCallbackImpl); + napi_value napiFail; + CHKCP(RegisterSubscribeCallback(env, args[0], asyncCallbackInfo, napiFail, interval), "register callback failed"); + int32_t deviceId = DEFAULT_DEVICE_ID; + if (!GetLocationDeviceId(deviceId)) { + SEN_HILOGW("Cant fand local deviceId, default deviceId :%{public}d", deviceId); + } + int32_t ret = SubscribeSensor({deviceId, sensorTypeId, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE}, + g_samplingPeriod[interval], DataCallbackImpl); if (ret != OHOS::ERR_OK) { CHKCP(IsMatchType(env, napiFail, napi_function), "subscribe fail"); CreateFailMessage(SUBSCRIBE_FAIL, SENSOR_SUBSCRIBE_FAILURE, "subscribe fail", asyncCallbackInfo); @@ -1228,17 +1724,18 @@ napi_value Subscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId return nullptr; } std::lock_guard subscribeLock(g_mutex); - std::vector> callbackInfos = g_subscribeCallbacks[sensorTypeId]; + std::vector> callbackInfos = g_subscribeCallbacks[{deviceId, sensorTypeId, + DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE}]; callbackInfos.push_back(asyncCallbackInfo); - g_subscribeCallbacks[sensorTypeId] = callbackInfos; + g_subscribeCallbacks[{deviceId, sensorTypeId, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE}] = callbackInfos; return nullptr; } -static bool RemoveSubscribeCallback(napi_env env, int32_t sensorTypeId) +static bool RemoveSubscribeCallback(napi_env env, SensorDescription sensorDesc) { CALL_LOG_ENTER; std::lock_guard subscribeCallbackLock(g_mutex); - std::vector> callbackInfos = g_subscribeCallbacks[sensorTypeId]; + std::vector> callbackInfos = g_subscribeCallbacks[sensorDesc]; for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) { CHKPC(*iter); if ((*iter)->env != env) { @@ -1248,7 +1745,7 @@ static bool RemoveSubscribeCallback(napi_env env, int32_t sensorTypeId) iter = callbackInfos.erase(iter); } if (callbackInfos.empty()) { - g_subscribeCallbacks.erase(sensorTypeId); + g_subscribeCallbacks.erase(sensorDesc); return true; } return false; @@ -1265,11 +1762,16 @@ napi_value Unsubscribe(napi_env env, napi_callback_info info, int32_t sensorType ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail"); return nullptr; } - if (!RemoveSubscribeCallback(env, sensorTypeId) || CheckSubscribe(sensorTypeId)) { + int32_t deviceId = DEFAULT_DEVICE_ID; + if (!GetLocationDeviceId(deviceId)) { + SEN_HILOGW("Cant fand local deviceId, default deviceId :%{public}d", deviceId); + } + if (!RemoveSubscribeCallback(env, {deviceId, sensorTypeId, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE}) || + CheckSubscribe({deviceId, sensorTypeId, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE})) { SEN_HILOGW("There are other client subscribe as well, not need unsubscribe"); return nullptr; } - if (UnsubscribeSensor(sensorTypeId) != OHOS::ERR_OK) { + if (UnsubscribeSensor({deviceId, sensorTypeId, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE}) != OHOS::ERR_OK) { SEN_HILOGW("UnsubscribeSensor failed"); return nullptr; } @@ -1436,6 +1938,8 @@ static napi_value Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("getSensorListSync", GetSensorListSync), DECLARE_NAPI_FUNCTION("getSingleSensor", GetSingleSensor), DECLARE_NAPI_FUNCTION("getSingleSensorSync", GetSingleSensorSync), + DECLARE_NAPI_FUNCTION("getSensorListbyDeviceSync", GetSensorListByDeviceSync), + DECLARE_NAPI_FUNCTION("getSingleSensorByDeviceSync", GetSingleSensorByDeviceSync), DECLARE_NAPI_FUNCTION("subscribeAccelerometer", SubscribeAccelerometer), DECLARE_NAPI_FUNCTION("unsubscribeAccelerometer", UnsubscribeAccelerometer), DECLARE_NAPI_FUNCTION("subscribeCompass", SubscribeCompass), diff --git a/frameworks/js/napi/src/sensor_napi_utils.cpp b/frameworks/js/napi/src/sensor_napi_utils.cpp index 66d14d784bb7301e0c63eb5fc910100cbb32a614..a62895176d180251040286b50ab834bcc42f7e72 100644 --- a/frameworks/js/napi/src/sensor_napi_utils.cpp +++ b/frameworks/js/napi/src/sensor_napi_utils.cpp @@ -209,6 +209,7 @@ std::map g_convertfuncList = { {GET_BODY_STATE, ConvertToBodyData}, {SUBSCRIBE_CALLBACK, ConvertToSensorData}, {SUBSCRIBE_COMPASS, ConvertToCompass}, + {SENSOR_STATE_CHANGE, ConvertToSensorState}, }; bool getJsonObject(const napi_env &env, sptr asyncCallbackInfo, napi_value &result) @@ -265,8 +266,17 @@ bool ConvertToSensorInfo(const napi_env &env, const SensorInfo &sensorInfo, napi CHKNRF(env, napi_set_named_property(env, result, "hardwareVersion", value), "napi_set_named_property"); value = nullptr; CHKNRF(env, napi_create_double(env, sensorInfo.sensorId, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "sensorIndex", value), "napi_set_named_property"); + value = nullptr; + CHKNRF(env, napi_create_double(env, sensorInfo.sensorTypeId, &value), "napi_create_double"); CHKNRF(env, napi_set_named_property(env, result, "sensorId", value), "napi_set_named_property"); value = nullptr; + CHKNRF(env, napi_create_double(env, sensorInfo.deviceId, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "deviceId", value), "napi_set_named_property"); + value = nullptr; + CHKNRF(env, napi_create_double(env, sensorInfo.location, &value), "napi_create_double"); + CHKNRF(env, napi_set_named_property(env, result, "location", value), "napi_set_named_property"); + value = nullptr; CHKNRF(env, napi_create_double(env, sensorInfo.maxRange, &value), "napi_create_double"); CHKNRF(env, napi_set_named_property(env, result, "maxRange", value), "napi_set_named_property"); value = nullptr; @@ -319,6 +329,42 @@ bool ConvertToFailData(const napi_env &env, sptr asyncCallbac return (result[0] != nullptr); } +bool ConvertToSensorState(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) +{ + CALL_LOG_ENTER; + CHKPF(asyncCallbackInfo); + CHKNRF(env, napi_create_object(env, &result[1]), "napi_create_object"); + napi_value value = nullptr; + CHKNRF(env, napi_create_int64(env, asyncCallbackInfo->sensorStatusEvent.timestamp, &value), + "napi_create_int64"); + CHKNRF(env, napi_set_named_property(env, result[1], "timestamp", value), "napi_set_named_property"); + value = nullptr; + CHKNRF(env, napi_create_int32(env, asyncCallbackInfo->sensorStatusEvent.sensorType, &value), + "napi_create_int32"); + CHKNRF(env, napi_set_named_property(env, result[1], "sensorId", value), "napi_set_named_property"); + value = nullptr; + CHKNRF(env, napi_create_int32(env, asyncCallbackInfo->sensorStatusEvent.sensorId, &value), + "napi_create_int32"); + CHKNRF(env, napi_set_named_property(env, result[1], "sensorIndex", value), "napi_set_named_property"); + value = nullptr; + CHKNRF(env, napi_get_boolean(env, asyncCallbackInfo->sensorStatusEvent.isSensorOnline, &value), + "napi_get_boolean"); + CHKNRF(env, napi_set_named_property(env, result[1], "isSensorOnline", value), "napi_set_named_property"); + value = nullptr; + CHKNRF(env, napi_create_int32(env, asyncCallbackInfo->sensorStatusEvent.deviceId, &value), + "napi_create_int32"); + CHKNRF(env, napi_set_named_property(env, result[1], "deviceId", value), "napi_set_named_property"); + value = nullptr; + CHKNRF(env, napi_create_string_utf8(env, asyncCallbackInfo->sensorStatusEvent.deviceName.c_str(), + NAPI_AUTO_LENGTH, &value), "napi_create_string_utf8"); + CHKNRF(env, napi_set_named_property(env, result[1], "deviceName", value), "napi_set_named_property"); + value = nullptr; + CHKNRF(env, napi_get_boolean(env, asyncCallbackInfo->sensorStatusEvent.location, &value), + "napi_get_boolean"); + CHKNRF(env, napi_set_named_property(env, result[1], "isLocalSensor", value), "napi_set_named_property"); + return true; +} + bool ConvertToSensorData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]) { CHKPF(asyncCallbackInfo); diff --git a/frameworks/native/ISensorService.idl b/frameworks/native/ISensorService.idl index e1d4ad4b9a62212005eeff6b4df2bcabf4d3decc..6e0706a88cabce2b8c142d72165967db5fd331b9 100644 --- a/frameworks/native/ISensorService.idl +++ b/frameworks/native/ISensorService.idl @@ -16,11 +16,13 @@ sequenceable active_info..OHOS.Sensors.ActiveInfo; sequenceable OHOS.IRemoteObject; sequenceable sensor..OHOS.Sensors.Sensor; +sequenceable sensor..OHOS.Sensors.SensorDescriptionIPC; interface OHOS.Sensors.ISensorService { - void EnableSensor([in] int sensorId, [in] long samplingPeriodNs, [in] long maxReportDelayNs); - void DisableSensor([in] int sensorId); + void EnableSensor([in] struct SensorDescriptionIPC sensorDesc, [in] long samplingPeriodNs, [in] long maxReportDelayNs); + void DisableSensor([in] struct SensorDescriptionIPC sensorDesc); void GetSensorList([out] Sensor[] sensorList); + void GetSensorListByDevice([in] int deviceId, [out] Sensor[] singleDevSensors); void TransferDataChannel([in] FileDescriptor sendFd, [in] IRemoteObject sensorClient); void DestroySensorChannel([in] IRemoteObject sensorClient); void SuspendSensors([in] int pid); @@ -32,4 +34,6 @@ interface OHOS.Sensors.ISensorService { void DisableActiveInfoCB(); void ResetSensors(); void SetDeviceStatus([in] unsigned int deviceStatus); + void TransferClientRemoteObject([in] IRemoteObject sensorClient); + void DestroyClientRemoteObject([in] IRemoteObject sensorClient); } \ No newline at end of file diff --git a/frameworks/native/include/i_sensor_client.h b/frameworks/native/include/i_sensor_client.h index 438a688dd984ebe4a5116d6399b5bf19966c2c95..7cec668ec0b966c3cafb37e076a79bd20d12a42a 100755 --- a/frameworks/native/include/i_sensor_client.h +++ b/frameworks/native/include/i_sensor_client.h @@ -17,13 +17,18 @@ #define I_SENSOR_CLIENT_H #include "iremote_broker.h" +#include "sensor_data_event.h" namespace OHOS { namespace Sensors { class ISensorClient : public IRemoteBroker { public: + enum SensorClientInterfaceId { + PROCESS_PLUG_EVENT = 1, + }; ISensorClient() = default; virtual ~ISensorClient() = default; + virtual int32_t ProcessPlugEvent(const SensorPlugData &info) = 0; DECLARE_INTERFACE_DESCRIPTOR(u"ISensorClient"); }; } // namespace Sensors diff --git a/frameworks/native/include/sensor_agent_proxy.h b/frameworks/native/include/sensor_agent_proxy.h index 7c2353c0cc58aea412a058644d0e57492e2d7375..4121bb43257a14d1b244f36253320958b3a96e99 100644 --- a/frameworks/native/include/sensor_agent_proxy.h +++ b/frameworks/native/include/sensor_agent_proxy.h @@ -18,6 +18,7 @@ #include #include +#include "sensor.h" #include "singleton.h" #include "sensor_data_channel.h" @@ -31,15 +32,18 @@ typedef int32_t (*SensorDataCallback)(struct SensorNativeData *events, uint32_t class SensorAgentProxy { DECLARE_DELAYED_SINGLETON(SensorAgentProxy); public: - int32_t ActivateSensor(int32_t sensorId, const SensorUser *user); - int32_t DeactivateSensor(int32_t sensorId, const SensorUser *user); - int32_t SetBatch(int32_t sensorId, const SensorUser *user, int64_t samplingInterval, int64_t reportInterval); - int32_t SubscribeSensor(int32_t sensorId, const SensorUser *user); - int32_t UnsubscribeSensor(int32_t sensorId, const SensorUser *user); - int32_t SetMode(int32_t sensorId, const SensorUser *user, int32_t mode); - int32_t SetOption(int32_t sensorId, const SensorUser *user, int32_t option); + int32_t ActivateSensor(const SensorDescription &sensorDesc, const SensorUser *user); + int32_t DeactivateSensor(const SensorDescription &sensorDesc, const SensorUser *user); + int32_t SetBatch(const SensorDescription &sensorDesc, const SensorUser *user, int64_t samplingInterval, + int64_t reportInterval); + int32_t SubscribeSensor(const SensorDescription &sensorDesc, const SensorUser *user); + int32_t UnsubscribeSensor(const SensorDescription &sensorDesc, const SensorUser *user); + int32_t SetMode(const SensorDescription &sensorDesc, const SensorUser *user, int32_t mode); + int32_t SetOption(const SensorDescription &sensorDesc, const SensorUser *user, int32_t option); void SetIsChannelCreated(bool isChannelCreated); int32_t GetAllSensors(SensorInfo **sensorInfo, int32_t *count) const; + int32_t GetDeviceSensors(int32_t deviceId, SensorInfo **singleDevSensorInfo, int32_t *count); + int32_t GetLocalDeviceId(int32_t &deviceId) const; int32_t SuspendSensors(int32_t pid); int32_t ResumeSensors(int32_t pid); int32_t GetSensorActiveInfos(int32_t pid, SensorActiveInfo **sensorActiveInfos, int32_t *count) const; @@ -48,22 +52,33 @@ public: void HandleSensorData(SensorEvent *events, int32_t num, void *data); int32_t ResetSensors() const; void SetDeviceStatus(uint32_t deviceStatus) const; + int32_t SubscribeSensorPlug(const SensorUser *user); + int32_t UnsubscribeSensorPlug(const SensorUser *user); + bool HandlePlugSensorData(const SensorPlugData &info); private: int32_t CreateSensorDataChannel(); int32_t DestroySensorDataChannel(); int32_t ConvertSensorInfos() const; void ClearSensorInfos() const; - std::set GetSubscribeUserCallback(int32_t sensorId); + std::set GetSubscribeUserCallback(const SensorDescription &sensorDesc); bool IsSubscribeMapEmpty() const; + int32_t UpdateSensorInfo(SensorInfo* sensorInfo, const Sensor& sensor); + int32_t UpdateSensorInfosCache(const std::vector& deviceSensorList); + bool FindSensorInfo(int32_t deviceId, int32_t sensorId, int32_t sensorTypeId); + void UpdataSensorStatusEvent(SensorStatusEvent &event, SensorPlugData info); + bool UpdataSensorInfo(SensorPlugData info); + void EraseCacheSensorInfos(SensorPlugData info); static std::recursive_mutex subscribeMutex_; + static std::recursive_mutex subscribePlugMutex_; static std::mutex chanelMutex_; OHOS::sptr dataChannel_ = nullptr; std::atomic_bool isChannelCreated_ = false; int64_t samplingInterval_ = -1; int64_t reportInterval_ = -1; - std::map> subscribeMap_; - std::map> unsubscribeMap_; + std::map> subscribeMap_; + std::map> unsubscribeMap_; + std::set subscribeSet_; static std::mutex createChannelMutex_; }; diff --git a/frameworks/native/include/sensor_client_proxy.h b/frameworks/native/include/sensor_client_proxy.h index 04b01f5618e94b0b1e3ab371a7b72f598927b38e..8f7674c028a042cbc34eff1dd627a4b871e1a0f8 100755 --- a/frameworks/native/include/sensor_client_proxy.h +++ b/frameworks/native/include/sensor_client_proxy.h @@ -19,6 +19,7 @@ #include "iremote_proxy.h" #include "sensor_agent_type.h" +#include "sensor_log.h" namespace OHOS { namespace Sensors { @@ -27,6 +28,55 @@ public: explicit SensorClientProxy(const sptr &impl) : IRemoteProxy(impl) {} virtual ~SensorClientProxy() = default; + int32_t ProcessPlugEvent(const SensorPlugData &info) override + { + MessageOption option; + MessageParcel dataParcel; + MessageParcel replyParcel; + if (!dataParcel.WriteInterfaceToken(GetDescriptor())) { + SEN_HILOGD("Failed to write descriptor to parcelable"); + return PARAMETER_ERROR; + } + if (!dataParcel.WriteInt32(info.deviceId)) { + SEN_HILOGD("Failed to write deviceId to parcelable"); + return PARAMETER_ERROR; + } + if (!dataParcel.WriteInt32(info.sensorTypeId)) { + SEN_HILOGD("Failed to write sensorTypeId to parcelable"); + return PARAMETER_ERROR; + } + if (!dataParcel.WriteInt32(info.sensorId)) { + SEN_HILOGD("Failed to write sensorId to parcelable"); + return PARAMETER_ERROR; + } + if (!dataParcel.WriteInt32(info.location)) { + SEN_HILOGD("Failed to write location to parcelable"); + return PARAMETER_ERROR; + } + if (!dataParcel.WriteString(info.deviceName)) { + SEN_HILOGD("Failed to write deviceName to parcelable"); + return PARAMETER_ERROR; + } + if (!dataParcel.WriteInt32(info.status)) { + SEN_HILOGD("Failed to write status to parcelable"); + return PARAMETER_ERROR; + } + if (!dataParcel.WriteInt32(info.reserved)) { + SEN_HILOGD("Failed to write reserved to parcelable"); + return PARAMETER_ERROR; + } + if (!dataParcel.WriteInt64(info.timestamp)) { + SEN_HILOGD("Failed to write timestamp to parcelable"); + return PARAMETER_ERROR; + } + int error = Remote()->SendRequest(PROCESS_PLUG_EVENT, dataParcel, replyParcel, option); + if (error != ERR_NONE) { + SEN_HILOGD("failed, error code is: %{public}d", error); + return PARAMETER_ERROR; + } + int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1; + return result; + } private: DISALLOW_COPY_AND_MOVE(SensorClientProxy); diff --git a/frameworks/native/include/sensor_client_stub.h b/frameworks/native/include/sensor_client_stub.h index 674558e3d581ebc951a0ab1968381a63c5a69098..3c04e6007975e019e2af0e6d8e68c417deb22773 100755 --- a/frameworks/native/include/sensor_client_stub.h +++ b/frameworks/native/include/sensor_client_stub.h @@ -28,6 +28,7 @@ public: virtual ~SensorClientStub() = default; virtual int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + int32_t ProcessPlugEvent(const SensorPlugData &info) override; }; } // namespace Sensors } // namespace OHOS diff --git a/frameworks/native/include/sensor_service_client.h b/frameworks/native/include/sensor_service_client.h index 713ec60292696a945368f702687aba4e26ac96be..084c07977fa0333b877ebb98cc4c8f33bb3646c9 100755 --- a/frameworks/native/include/sensor_service_client.h +++ b/frameworks/native/include/sensor_service_client.h @@ -33,12 +33,14 @@ class SensorServiceClient : public StreamSocket, public Singleton GetSensorList(); - int32_t EnableSensor(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay); - int32_t DisableSensor(int32_t sensorId); + std::vector GetSensorListByDevice(int32_t deviceId); + int32_t GetSensorListByDevice(int32_t deviceId, std::vector &singleDevSensors); + int32_t EnableSensor(const SensorDescription &sensorDesc, int64_t samplingPeriod, int64_t maxReportDelay); + int32_t DisableSensor(const SensorDescription &sensorDesc); int32_t TransferDataChannel(sptr sensorDataChannel); int32_t DestroyDataChannel(); void ProcessDeathObserver(const wptr &object); - bool IsValid(int32_t sensorId); + bool IsValid(const SensorDescription &sensorDesc); int32_t SuspendSensors(int32_t pid); int32_t ResumeSensors(int32_t pid); int32_t GetActiveInfoList(int32_t pid, std::vector &activeInfoList); @@ -49,15 +51,21 @@ public: void Disconnect(); void HandleNetPacke(NetPacket &pkt); void SetDeviceStatus(uint32_t deviceStatus); + int32_t CreateClientRemoteObject(); + int32_t TransferClientRemoteObject(); + int32_t DestroyClientRemoteObject(); + bool EraseCacheSensorList(SensorPlugData info); + int32_t GetLocalDeviceId(int32_t &deviceId); private: int32_t InitServiceClient(); - void UpdateSensorInfoMap(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay); - void DeleteSensorInfoItem(int32_t sensorId); + void UpdateSensorInfoMap(const SensorDescription &sensorDesc, int64_t samplingPeriod, int64_t maxReportDelay); + void DeleteSensorInfoItem(const SensorDescription &sensorDesc); int32_t CreateSocketClientFd(int32_t &clientFd); int32_t CreateSocketChannel(); void ReenableSensor(); void WriteHiSysIPCEvent(ISensorServiceIpcCode code, int32_t ret); + void WriteHiSysIPCEventSplit(ISensorServiceIpcCode code, int32_t ret); std::mutex clientMutex_; sptr serviceDeathObserver_ = nullptr; sptr sensorServer_ = nullptr; @@ -66,7 +74,7 @@ private: sptr dataChannel_ = nullptr; sptr sensorClientStub_ = nullptr; std::mutex mapMutex_; - std::map sensorInfoMap_; + std::map sensorInfoMap_; std::atomic_bool isConnected_ = false; CircleStreamBuffer circBuf_; std::mutex activeInfoCBMutex_; diff --git a/frameworks/native/src/sensor_agent.cpp b/frameworks/native/src/sensor_agent.cpp index f4088949f427ce49243e57cb0fc4a400b0e41c10..5be4cebc75e48fcb88898cf7b3c3961ebee81673 100644 --- a/frameworks/native/src/sensor_agent.cpp +++ b/frameworks/native/src/sensor_agent.cpp @@ -25,6 +25,9 @@ using OHOS::Sensors::SERVICE_EXCEPTION; using OHOS::Sensors::PARAMETER_ERROR; using OHOS::Sensors::PERMISSION_DENIED; using OHOS::Sensors::NON_SYSTEM_API; +constexpr int32_t DEFAULT_SENSOR_ID = 0; +constexpr int32_t DEFAULT_LOCATION = 1; +constexpr int32_t DEFAULT_DEVICE_ID = -1; static int32_t NormalizeErrCode(int32_t code) { @@ -54,9 +57,24 @@ int32_t GetAllSensors(SensorInfo **sensorInfo, int32_t *count) return ret; } +int32_t GetDeviceSensors(int32_t deviceId, SensorInfo **sensorInfo, int32_t *count) +{ + int32_t ret = SENSOR_AGENT_IMPL->GetDeviceSensors(deviceId, sensorInfo, count); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("GetDeviceSensors failed"); + return NormalizeErrCode(ret); + } + return ret; +} + int32_t ActivateSensor(int32_t sensorId, const SensorUser *user) { - int32_t ret = SENSOR_AGENT_IMPL->ActivateSensor(sensorId, user); + int32_t deviceId; + if (SENSOR_AGENT_IMPL->GetLocalDeviceId(deviceId) != OHOS::ERR_OK) { + SEN_HILOGW("The local deviceId cannot be found"); + deviceId = DEFAULT_DEVICE_ID; + } + int32_t ret = SENSOR_AGENT_IMPL->ActivateSensor({deviceId, sensorId, DEFAULT_SENSOR_ID, DEFAULT_LOCATION}, user); if (ret != OHOS::ERR_OK) { SEN_HILOGE("ActivateSensor failed"); return NormalizeErrCode(ret); @@ -66,7 +84,12 @@ int32_t ActivateSensor(int32_t sensorId, const SensorUser *user) int32_t DeactivateSensor(int32_t sensorId, const SensorUser *user) { - int32_t ret = SENSOR_AGENT_IMPL->DeactivateSensor(sensorId, user); + int32_t deviceId; + if (SENSOR_AGENT_IMPL->GetLocalDeviceId(deviceId) != OHOS::ERR_OK) { + SEN_HILOGW("The local deviceId cannot be found"); + deviceId = DEFAULT_DEVICE_ID; + } + int32_t ret = SENSOR_AGENT_IMPL->DeactivateSensor({deviceId, sensorId, DEFAULT_SENSOR_ID, DEFAULT_LOCATION}, user); if (ret != OHOS::ERR_OK) { SEN_HILOGE("DeactivateSensor failed"); return NormalizeErrCode(ret); @@ -76,7 +99,13 @@ int32_t DeactivateSensor(int32_t sensorId, const SensorUser *user) int32_t SetBatch(int32_t sensorId, const SensorUser *user, int64_t samplingInterval, int64_t reportInterval) { - int32_t ret = SENSOR_AGENT_IMPL->SetBatch(sensorId, user, samplingInterval, reportInterval); + int32_t deviceId; + if (SENSOR_AGENT_IMPL->GetLocalDeviceId(deviceId) != OHOS::ERR_OK) { + SEN_HILOGW("The local deviceId cannot be found"); + deviceId = DEFAULT_DEVICE_ID; + } + int32_t ret = SENSOR_AGENT_IMPL->SetBatch({deviceId, sensorId, DEFAULT_SENSOR_ID, DEFAULT_LOCATION}, + user, samplingInterval, reportInterval); if (ret != OHOS::ERR_OK) { SEN_HILOGE("SetBatch failed"); return NormalizeErrCode(ret); @@ -86,7 +115,12 @@ int32_t SetBatch(int32_t sensorId, const SensorUser *user, int64_t samplingInter int32_t SubscribeSensor(int32_t sensorId, const SensorUser *user) { - int32_t ret = SENSOR_AGENT_IMPL->SubscribeSensor(sensorId, user); + int32_t deviceId; + if (SENSOR_AGENT_IMPL->GetLocalDeviceId(deviceId) != OHOS::ERR_OK) { + SEN_HILOGW("The local deviceId cannot be found"); + deviceId = DEFAULT_DEVICE_ID; + } + int32_t ret = SENSOR_AGENT_IMPL->SubscribeSensor({deviceId, sensorId, DEFAULT_SENSOR_ID, DEFAULT_LOCATION}, user); if (ret != OHOS::ERR_OK) { SEN_HILOGE("SubscribeSensor failed"); return NormalizeErrCode(ret); @@ -96,7 +130,13 @@ int32_t SubscribeSensor(int32_t sensorId, const SensorUser *user) int32_t UnsubscribeSensor(int32_t sensorId, const SensorUser *user) { - int32_t ret = SENSOR_AGENT_IMPL->UnsubscribeSensor(sensorId, user); + int32_t deviceId; + if (SENSOR_AGENT_IMPL->GetLocalDeviceId(deviceId) != OHOS::ERR_OK) { + SEN_HILOGW("The local deviceId cannot be found"); + deviceId = DEFAULT_DEVICE_ID; + } + int32_t ret = SENSOR_AGENT_IMPL->UnsubscribeSensor( + {deviceId, sensorId, DEFAULT_SENSOR_ID, DEFAULT_LOCATION}, user); if (ret != OHOS::ERR_OK) { SEN_HILOGE("UnsubscribeSensor failed"); return NormalizeErrCode(ret); @@ -106,7 +146,12 @@ int32_t UnsubscribeSensor(int32_t sensorId, const SensorUser *user) int32_t SetMode(int32_t sensorId, const SensorUser *user, int32_t mode) { - return SENSOR_AGENT_IMPL->SetMode(sensorId, user, mode); + int32_t deviceId; + if (SENSOR_AGENT_IMPL->GetLocalDeviceId(deviceId) != OHOS::ERR_OK) { + SEN_HILOGW("The local deviceId cannot be found"); + deviceId = DEFAULT_DEVICE_ID; + } + return SENSOR_AGENT_IMPL->SetMode({deviceId, sensorId, DEFAULT_SENSOR_ID, DEFAULT_LOCATION}, user, mode); } int32_t SuspendSensors(int32_t pid) @@ -174,4 +219,86 @@ int32_t ResetSensors() void SetDeviceStatus(uint32_t deviceStatus) { SENSOR_AGENT_IMPL->SetDeviceStatus(deviceStatus); +} + +int32_t ActivateSensorEnhanced(const SensorIdentifier &sensorIdentifier, const SensorUser *user) +{ + int32_t ret = SENSOR_AGENT_IMPL->ActivateSensor({sensorIdentifier.deviceId, sensorIdentifier.sensorType, + sensorIdentifier.sensorId, sensorIdentifier.location}, user); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("ActivateSensor failed"); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t DeactivateSensorEnhanced(const SensorIdentifier &sensorIdentifier, const SensorUser *user) +{ + int32_t ret = SENSOR_AGENT_IMPL->DeactivateSensor({sensorIdentifier.deviceId, sensorIdentifier.sensorType, + sensorIdentifier.sensorId, sensorIdentifier.location}, user); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("DeactivateSensor failed"); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t SetBatchEnhanced(const SensorIdentifier &sensorIdentifier, const SensorUser *user, int64_t samplingInterval, + int64_t reportInterval) +{ + int32_t ret = SENSOR_AGENT_IMPL->SetBatch({sensorIdentifier.deviceId, sensorIdentifier.sensorType, + sensorIdentifier.sensorId, sensorIdentifier.location}, user, samplingInterval, reportInterval); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("SetBatch failed"); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t SubscribeSensorEnhanced(const SensorIdentifier &sensorIdentifier, const SensorUser *user) +{ + int32_t ret = SENSOR_AGENT_IMPL->SubscribeSensor({sensorIdentifier.deviceId, sensorIdentifier.sensorType, + sensorIdentifier.sensorId, sensorIdentifier.location}, user); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("SubscribeSensor failed"); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t UnsubscribeSensorEnhanced(const SensorIdentifier &sensorIdentifier, const SensorUser *user) +{ + int32_t ret = SENSOR_AGENT_IMPL->UnsubscribeSensor({sensorIdentifier.deviceId, sensorIdentifier.sensorType, + sensorIdentifier.sensorId, sensorIdentifier.location}, user); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("UnsubscribeSensor failed"); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t SetModeEnhanced(const SensorIdentifier &sensorIdentifier, const SensorUser *user, int32_t mode) +{ + return SENSOR_AGENT_IMPL->SetMode({sensorIdentifier.deviceId, sensorIdentifier.sensorType, + sensorIdentifier.sensorId, sensorIdentifier.location}, user, mode); +} + +int32_t SubscribeSensorPlug(const SensorUser *user) +{ + int32_t ret = SENSOR_AGENT_IMPL->SubscribeSensorPlug(user); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("SubscribeSensorPlug failed"); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t UnsubscribeSensorPlug(const SensorUser *user) +{ + int32_t ret = SENSOR_AGENT_IMPL->UnsubscribeSensorPlug(user); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("UnSubscribeSensorPlug failed"); + return NormalizeErrCode(ret); + } + return ret; } \ No newline at end of file diff --git a/frameworks/native/src/sensor_agent_proxy.cpp b/frameworks/native/src/sensor_agent_proxy.cpp index dfb11bc27ea87c65d5e184e255383add3718f3b7..fb191157cafa4d30990f2c8e9307c8e65a5cfbc0 100644 --- a/frameworks/native/src/sensor_agent_proxy.cpp +++ b/frameworks/native/src/sensor_agent_proxy.cpp @@ -25,6 +25,8 @@ namespace OHOS { namespace Sensors { namespace { constexpr uint32_t MAX_SENSOR_LIST_SIZE = 0Xffff; +constexpr int32_t IS_LOCAL_DEVICE = 1; +constexpr int32_t SENSOR_ONLINE = 1; std::mutex sensorInfoMutex_; SensorInfoCheck sensorInfoCheck_; std::mutex sensorActiveInfoMutex_; @@ -34,6 +36,7 @@ int32_t sensorInfoCount_ = 0; #define SEN_CLIENT SensorServiceClient::GetInstance() std::recursive_mutex SensorAgentProxy::subscribeMutex_; +std::recursive_mutex SensorAgentProxy::subscribePlugMutex_; std::mutex SensorAgentProxy::chanelMutex_; std::mutex SensorAgentProxy::createChannelMutex_; @@ -47,10 +50,10 @@ SensorAgentProxy::~SensorAgentProxy() ClearSensorInfos(); } -std::set SensorAgentProxy::GetSubscribeUserCallback(int32_t sensorId) +std::set SensorAgentProxy::GetSubscribeUserCallback(const SensorDescription &sensorDesc) { std::lock_guard subscribeLock(subscribeMutex_); - auto iter = subscribeMap_.find(sensorId); + auto iter = subscribeMap_.find(sensorDesc); if (iter == subscribeMap_.end()) { SEN_HILOGE("Sensor is not subscribed"); return {}; @@ -76,7 +79,8 @@ void SensorAgentProxy::HandleSensorData(SensorEvent *events, SensorEvent eventStream; for (int32_t i = 0; i < num; ++i) { eventStream = events[i]; - auto callbacks = GetSubscribeUserCallback(eventStream.sensorTypeId); + auto callbacks = GetSubscribeUserCallback({eventStream.deviceId, eventStream.sensorTypeId, + eventStream.sensorId, eventStream.location}); for (const auto &callback : callbacks) { CHKPV(callback); if (eventStream.sensorTypeId == SENSOR_TYPE_ID_HALL_EXT) { @@ -157,25 +161,27 @@ int32_t SensorAgentProxy::DestroySensorDataChannel() return ERR_OK; } -int32_t SensorAgentProxy::ActivateSensor(int32_t sensorId, const SensorUser *user) +int32_t SensorAgentProxy::ActivateSensor(const SensorDescription &sensorDesc, const SensorUser *user) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); + SEN_HILOGI("In, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); CHKPR(user, OHOS::Sensors::ERROR); CHKPR(user->callback, OHOS::Sensors::ERROR); if (samplingInterval_ < 0 || reportInterval_ < 0) { SEN_HILOGE("SamplingPeriod or reportInterval_ is invalid"); return ERROR; } - if (!SEN_CLIENT.IsValid(sensorId)) { - SEN_HILOGE("sensorId is invalid, %{public}d", sensorId); + if (!SEN_CLIENT.IsValid(sensorDesc)) { + SEN_HILOGE("sensorDesc is invalid, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return PARAMETER_ERROR; } std::lock_guard subscribeLock(subscribeMutex_); - if (subscribeMap_.find(sensorId) == subscribeMap_.end()) { + if (subscribeMap_.find(sensorDesc) == subscribeMap_.end()) { SEN_HILOGE("Subscribe sensorId first"); return ERROR; } - auto& subscribeSet = subscribeMap_[sensorId]; + auto& subscribeSet = subscribeMap_[sensorDesc]; if (subscribeSet.find(user) == subscribeSet.end()) { SEN_HILOGE("Subscribe user first"); return ERROR; @@ -183,66 +189,71 @@ int32_t SensorAgentProxy::ActivateSensor(int32_t sensorId, const SensorUser *use int32_t ret = 0; { SensorXcollie SensorXcollie("SensorAgentProxy:EnableSensor", XCOLLIE_TIMEOUT_15S); - ret = SEN_CLIENT.EnableSensor(sensorId, samplingInterval_, reportInterval_); + ret = SEN_CLIENT.EnableSensor(sensorDesc, samplingInterval_, reportInterval_); } if (ret != 0) { SEN_HILOGE("Enable sensor failed, ret:%{public}d", ret); subscribeSet.erase(user); if (subscribeSet.empty()) { - subscribeMap_.erase(sensorId); + subscribeMap_.erase(sensorDesc); } return ret; } - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + SEN_HILOGI("Done, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return ret; } -int32_t SensorAgentProxy::DeactivateSensor(int32_t sensorId, const SensorUser *user) +int32_t SensorAgentProxy::DeactivateSensor(const SensorDescription &sensorDesc, const SensorUser *user) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); + SEN_HILOGI("In, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d, location:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, sensorDesc.location); CHKPR(user, OHOS::Sensors::ERROR); CHKPR(user->callback, OHOS::Sensors::ERROR); - if (!SEN_CLIENT.IsValid(sensorId)) { - SEN_HILOGE("sensorId is invalid, %{public}d", sensorId); + if (!SEN_CLIENT.IsValid(sensorDesc)) { + SEN_HILOGE("sensorDesc is invalid, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return PARAMETER_ERROR; } std::lock_guard subscribeLock(subscribeMutex_); - if (subscribeMap_.find(sensorId) == subscribeMap_.end()) { + if (subscribeMap_.find(sensorDesc) == subscribeMap_.end()) { SEN_HILOGE("Subscribe sensorId first"); return OHOS::Sensors::ERROR; } - auto& subscribeSet = subscribeMap_[sensorId]; + auto& subscribeSet = subscribeMap_[sensorDesc]; if (subscribeSet.find(user) == subscribeSet.end()) { SEN_HILOGE("Subscribe user first"); return OHOS::Sensors::ERROR; } - auto status = unsubscribeMap_[sensorId].insert(user); + auto status = unsubscribeMap_[sensorDesc].insert(user); if (!status.second) { SEN_HILOGE("User has been unsubscribed"); } subscribeSet.erase(user); if (subscribeSet.empty()) { - subscribeMap_.erase(sensorId); + subscribeMap_.erase(sensorDesc); int32_t ret = 0; { SensorXcollie SensorXcollie("SensorAgentProxy:DisableSensor", XCOLLIE_TIMEOUT_15S); - ret = SEN_CLIENT.DisableSensor(sensorId); + ret = SEN_CLIENT.DisableSensor(sensorDesc); } if (ret != 0) { SEN_HILOGE("DisableSensor failed, ret:%{public}d", ret); return ret; } } - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + SEN_HILOGI("Done, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return OHOS::Sensors::SUCCESS; } -int32_t SensorAgentProxy::SetBatch(int32_t sensorId, const SensorUser *user, int64_t samplingInterval, - int64_t reportInterval) +int32_t SensorAgentProxy::SetBatch(const SensorDescription &sensorDesc, const SensorUser *user, + int64_t samplingInterval, int64_t reportInterval) { CHKPR(user, OHOS::Sensors::ERROR); - if (!SEN_CLIENT.IsValid(sensorId)) { - SEN_HILOGE("sensorId is invalid, %{public}d", sensorId); + if (!SEN_CLIENT.IsValid(sensorDesc)) { + SEN_HILOGE("sensorDesc is invalid, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return PARAMETER_ERROR; } if (samplingInterval < 0 || reportInterval < 0) { @@ -250,11 +261,11 @@ int32_t SensorAgentProxy::SetBatch(int32_t sensorId, const SensorUser *user, int return OHOS::Sensors::ERROR; } std::lock_guard subscribeLock(subscribeMutex_); - if (subscribeMap_.find(sensorId) == subscribeMap_.end()) { + if (subscribeMap_.find(sensorDesc) == subscribeMap_.end()) { SEN_HILOGE("Subscribe sensorId first"); return OHOS::Sensors::ERROR; } - auto& subscribeSet = subscribeMap_[sensorId]; + auto& subscribeSet = subscribeMap_[sensorDesc]; if (subscribeSet.find(user) == subscribeSet.end()) { SEN_HILOGE("Subscribe user first"); return OHOS::Sensors::ERROR; @@ -264,13 +275,15 @@ int32_t SensorAgentProxy::SetBatch(int32_t sensorId, const SensorUser *user, int return OHOS::Sensors::SUCCESS; } -int32_t SensorAgentProxy::SubscribeSensor(int32_t sensorId, const SensorUser *user) +int32_t SensorAgentProxy::SubscribeSensor(const SensorDescription &sensorDesc, const SensorUser *user) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); + SEN_HILOGI("In, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); CHKPR(user, OHOS::Sensors::ERROR); CHKPR(user->callback, OHOS::Sensors::ERROR); - if (!SEN_CLIENT.IsValid(sensorId)) { - SEN_HILOGE("sensorId is invalid, %{public}d", sensorId); + if (!SEN_CLIENT.IsValid(sensorDesc)) { + SEN_HILOGE("sensorDesc is invalid, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return PARAMETER_ERROR; } std::lock_guard createChannelLock(createChannelMutex_); @@ -280,15 +293,16 @@ int32_t SensorAgentProxy::SubscribeSensor(int32_t sensorId, const SensorUser *us return OHOS::Sensors::ERROR; } std::lock_guard subscribeLock(subscribeMutex_); - auto status = subscribeMap_[sensorId].insert(user); + auto status = subscribeMap_[sensorDesc].insert(user); if (!status.second) { SEN_HILOGE("User has been subscribed"); } - if (PrintSensorData::GetInstance().IsContinuousType(sensorId)) { + if (PrintSensorData::GetInstance().IsContinuousType(sensorDesc.sensorType)) { PrintSensorData::GetInstance().SavePrintUserInfo(user->callback); PrintSensorData::GetInstance().ResetClientTimes(); } - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + SEN_HILOGI("Done, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return OHOS::Sensors::SUCCESS; } @@ -298,29 +312,30 @@ bool SensorAgentProxy::IsSubscribeMapEmpty() const return subscribeMap_.empty(); } -int32_t SensorAgentProxy::UnsubscribeSensor(int32_t sensorId, const SensorUser *user) +int32_t SensorAgentProxy::UnsubscribeSensor(const SensorDescription &sensorDesc, const SensorUser *user) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); + SEN_HILOGI("In, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); CHKPR(user, OHOS::Sensors::ERROR); CHKPR(user->callback, OHOS::Sensors::ERROR); - if (!SEN_CLIENT.IsValid(sensorId)) { - SEN_HILOGE("sensorId is invalid, %{public}d", sensorId); + if (!SEN_CLIENT.IsValid(sensorDesc)) { + SEN_HILOGE("sensorId is invalid, %{public}d", sensorDesc.sensorType); return PARAMETER_ERROR; } { std::lock_guard subscribeLock(subscribeMutex_); - if (unsubscribeMap_.find(sensorId) == unsubscribeMap_.end()) { + if (unsubscribeMap_.find(sensorDesc) == unsubscribeMap_.end()) { SEN_HILOGE("Deactivate sensorId first"); return OHOS::Sensors::ERROR; } - auto& unsubscribeSet = unsubscribeMap_[sensorId]; + auto& unsubscribeSet = unsubscribeMap_[sensorDesc]; if (unsubscribeSet.find(user) == unsubscribeSet.end()) { SEN_HILOGE("Deactivate user first"); return OHOS::Sensors::ERROR; } unsubscribeSet.erase(user); if (unsubscribeSet.empty()) { - unsubscribeMap_.erase(sensorId); + unsubscribeMap_.erase(sensorDesc); } } std::lock_guard createChannelLock(createChannelMutex_); @@ -331,28 +346,30 @@ int32_t SensorAgentProxy::UnsubscribeSensor(int32_t sensorId, const SensorUser * return ret; } } - if (PrintSensorData::GetInstance().IsContinuousType(sensorId)) { + if (PrintSensorData::GetInstance().IsContinuousType(sensorDesc.sensorType)) { PrintSensorData::GetInstance().RemovePrintUserInfo(user->callback); PrintSensorData::GetInstance().ResetClientTimes(); } - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + SEN_HILOGI("Done, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return OHOS::Sensors::SUCCESS; } -int32_t SensorAgentProxy::SetMode(int32_t sensorId, const SensorUser *user, int32_t mode) +int32_t SensorAgentProxy::SetMode(const SensorDescription &sensorDesc, const SensorUser *user, int32_t mode) { CHKPR(user, OHOS::Sensors::ERROR); CHKPR(user->callback, OHOS::Sensors::ERROR); - if (!SEN_CLIENT.IsValid(sensorId)) { - SEN_HILOGE("sensorId is invalid, %{public}d", sensorId); + if (!SEN_CLIENT.IsValid(sensorDesc)) { + SEN_HILOGE("sensorDesc is invalid,deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return ERROR; } std::lock_guard subscribeLock(subscribeMutex_); - if (subscribeMap_.find(sensorId) == subscribeMap_.end()) { + if (subscribeMap_.find(sensorDesc) == subscribeMap_.end()) { SEN_HILOGE("Subscribe sensorId first"); return OHOS::Sensors::ERROR; } - auto& subscribeSet = subscribeMap_[sensorId]; + auto& subscribeSet = subscribeMap_[sensorDesc]; if (subscribeSet.find(user) == subscribeSet.end()) { SEN_HILOGE("Subscribe user first"); return OHOS::Sensors::ERROR; @@ -418,20 +435,157 @@ int32_t SensorAgentProxy::ConvertSensorInfos() const ret = strcpy_s(sensorInfo->firmwareVersion, VERSION_MAX_LEN, sensorList[i].GetFirmwareVersion().c_str()); CHKCR(ret == EOK, ERROR); + sensorInfo->deviceId = sensorList[i].GetDeviceId(); sensorInfo->sensorId = sensorList[i].GetSensorId(); sensorInfo->sensorTypeId = sensorList[i].GetSensorTypeId(); + sensorInfo->location = sensorList[i].GetLocation(); sensorInfo->maxRange = sensorList[i].GetMaxRange(); sensorInfo->precision = sensorList[i].GetResolution(); sensorInfo->power = sensorList[i].GetPower(); sensorInfo->minSamplePeriod = sensorList[i].GetMinSamplePeriodNs(); sensorInfo->maxSamplePeriod = sensorList[i].GetMaxSamplePeriodNs(); - SEN_HILOGI("Sensor %{public}zu: sensorId is %{public}d, sensorTypeId is %{public}d", - i, sensorInfo->sensorId, sensorInfo->sensorTypeId); + SEN_HILOGI("deviceId %{public}d: sensorTypeId %{public}d, sensorId %{public}d", + sensorInfo->deviceId, sensorInfo->sensorTypeId, sensorInfo->sensorId); } sensorInfoCount_ = static_cast(count); return SUCCESS; } +int32_t SensorAgentProxy::GetDeviceSensors(int32_t deviceId, SensorInfo **singleDevSensorInfo, int32_t *count) +{ + CALL_LOG_ENTER; + CHKPR(singleDevSensorInfo, OHOS::Sensors::ERROR); + CHKPR(count, OHOS::Sensors::ERROR); + std::lock_guard listLock(sensorInfoMutex_); + if (sensorInfoCheck_.sensorInfos == nullptr) { + int32_t ret = ConvertSensorInfos(); + if (ret != ERR_OK) { + SEN_HILOGE("Convert sensor lists failed"); + ClearSensorInfos(); + return ERROR; + } + } + std::vector singleDevSensors; + SensorXcollie SensorXcollie("SensorAgentProxy:ConvertSensorInfosByDevice", XCOLLIE_TIMEOUT_5S); + int32_t ret = SEN_CLIENT.GetSensorListByDevice(deviceId, singleDevSensors); + if (ret != ERR_OK || singleDevSensors.empty()) { + SEN_HILOGE("Get device sensor lists failed"); + return ERROR; + } + ret = UpdateSensorInfosCache(singleDevSensors); + if (ret != ERR_OK) { + SEN_HILOGE("Update sensor infos cache failed"); + return ERROR; + } + std::vector filteredSensorInfos; + for (int32_t i = 0; i < sensorInfoCount_; ++i) { + if (sensorInfoCheck_.sensorInfos[i].deviceId == deviceId) { + filteredSensorInfos.push_back(sensorInfoCheck_.sensorInfos[i]); + } + } + int32_t filteredCount = static_cast(filteredSensorInfos.size()); + auto newSensorInfo = std::make_unique(filteredCount); + if (!newSensorInfo) { + SEN_HILOGE("Failed to allocate memory for filtered sensorInfos"); + return ERROR; + } + for (int32_t i = 0; i < filteredCount; ++i) { + newSensorInfo[i] = filteredSensorInfos[i]; + } + free(*singleDevSensorInfo); + *singleDevSensorInfo = newSensorInfo.release(); + *count = filteredCount; + return SUCCESS; +} + +int32_t SensorAgentProxy::UpdateSensorInfo(SensorInfo* sensorInfo, const Sensor& sensor) +{ + CALL_LOG_ENTER; + CHKPR(sensorInfo, OHOS::Sensors::ERROR); + errno_t ret = strcpy_s(sensorInfo->sensorName, NAME_MAX_LEN, + sensor.GetSensorName().c_str()); + CHKCR(ret == EOK, ERROR); + ret = strcpy_s(sensorInfo->vendorName, NAME_MAX_LEN, + sensor.GetVendorName().c_str()); + CHKCR(ret == EOK, ERROR); + ret = strcpy_s(sensorInfo->hardwareVersion, VERSION_MAX_LEN, + sensor.GetHardwareVersion().c_str()); + CHKCR(ret == EOK, ERROR); + ret = strcpy_s(sensorInfo->firmwareVersion, VERSION_MAX_LEN, + sensor.GetFirmwareVersion().c_str()); + CHKCR(ret == EOK, ERROR); + sensorInfo->deviceId = sensor.GetDeviceId(); + sensorInfo->sensorId = sensor.GetSensorId(); + sensorInfo->sensorTypeId = sensor.GetSensorTypeId(); + sensorInfo->location = sensor.GetLocation(); + sensorInfo->maxRange = sensor.GetMaxRange(); + sensorInfo->precision = sensor.GetResolution(); + sensorInfo->power = sensor.GetPower(); + sensorInfo->minSamplePeriod = sensor.GetMinSamplePeriodNs(); + sensorInfo->maxSamplePeriod = sensor.GetMaxSamplePeriodNs(); + return SUCCESS; +} + +bool SensorAgentProxy::FindSensorInfo(int32_t deviceId, int32_t sensorId, int32_t sensorTypeId) +{ + CALL_LOG_ENTER; + if (sensorInfoCheck_.sensorInfos == nullptr) { + return false; + } + for (int32_t i = 0; i < sensorInfoCount_; ++i) { + if (sensorInfoCheck_.sensorInfos[i].deviceId == deviceId && + sensorInfoCheck_.sensorInfos[i].sensorId == sensorId && + sensorInfoCheck_.sensorInfos[i].sensorTypeId == sensorTypeId) { + SEN_HILOGI("FindSensorInfo deviceId:%{public}d, sensorTypeId:%{public}d, sensorId:%{public}d", + deviceId, sensorTypeId, sensorId); + return true; + } + } + return false; +} + +int32_t SensorAgentProxy::UpdateSensorInfosCache(const std::vector& singleDevSensors) +{ + CALL_LOG_ENTER; + size_t newSensorsCount = 0; + for (const auto& sensor : singleDevSensors) { + if (!FindSensorInfo(sensor.GetDeviceId(), sensor.GetSensorId(), sensor.GetSensorTypeId())) { + newSensorsCount++; + } + } + if (newSensorsCount == 0) { + return SUCCESS; + } + size_t newTotalCount = sensorInfoCount_ + newSensorsCount; + if (newTotalCount > MAX_SENSOR_LIST_SIZE) { + SEN_HILOGE("The number of sensors exceeds the maximum value"); + return ERROR; + } + std::unique_ptr newSensorInfos = std::make_unique(newTotalCount); + if (newSensorInfos == nullptr) { + SEN_HILOGE("Failed to allocate memory for newSensorInfos"); + return ERROR; + } + if (sensorInfoCheck_.sensorInfos) { + std::copy(sensorInfoCheck_.sensorInfos, sensorInfoCheck_.sensorInfos + sensorInfoCount_, newSensorInfos.get()); + } + size_t currentIndex = sensorInfoCount_; + for (const auto& sensor : singleDevSensors) { + if (!FindSensorInfo(sensor.GetDeviceId(), sensor.GetSensorId(), sensor.GetSensorTypeId())) { + UpdateSensorInfo(&newSensorInfos[currentIndex++], sensor); + } + } + sensorInfoCheck_.sensorInfos = newSensorInfos.release(); + sensorInfoCount_ = static_cast(newTotalCount); + return SUCCESS; +} + +int32_t SensorAgentProxy::GetLocalDeviceId(int32_t& deviceId) const +{ + CALL_LOG_ENTER; + return SEN_CLIENT.GetLocalDeviceId(deviceId); +} + int32_t SensorAgentProxy::GetAllSensors(SensorInfo **sensorInfo, int32_t *count) const { CALL_LOG_ENTER; @@ -589,5 +743,119 @@ void SensorAgentProxy::SetDeviceStatus(uint32_t deviceStatus) const SEN_HILOGI("SetDeviceStatus in, deviceStatus:%{public}d", deviceStatus); SEN_CLIENT.SetDeviceStatus(deviceStatus); } + +int32_t SensorAgentProxy::SubscribeSensorPlug(const SensorUser *user) +{ + CALL_LOG_ENTER; + CHKPR(user, OHOS::Sensors::ERROR); + CHKPR(user->plugCallback, OHOS::Sensors::ERROR); + + int32_t ret = 0; + { + SensorXcollie SensorXcollie("SensorAgentProxy:CreateClientRemoteObject()", XCOLLIE_TIMEOUT_5S); + ret = SEN_CLIENT.CreateClientRemoteObject(); + } + if (ret != ERR_OK) { + SEN_HILOGE("CreateClientRemoteObject failed, ret:%{public}d", ret); + return ret; + } + + std::lock_guard subscribePlugLock(subscribePlugMutex_); + auto status = subscribeSet_.insert(user); + if (!status.second) { + SEN_HILOGD("User has been subscribed"); + } + return OHOS::Sensors::SUCCESS; +} + +int32_t SensorAgentProxy::UnsubscribeSensorPlug(const SensorUser *user) +{ + CALL_LOG_ENTER; + CHKPR(user, OHOS::Sensors::ERROR); + CHKPR(user->plugCallback, OHOS::Sensors::ERROR); + + std::lock_guard subscribePlugLock(subscribePlugMutex_); + if (subscribeSet_.find(user) == subscribeSet_.end()) { + SEN_HILOGD("Deactivate user first"); + return OHOS::Sensors::ERROR; + } + subscribeSet_.erase(user); + return OHOS::Sensors::SUCCESS; +} + +void SensorAgentProxy::UpdataSensorStatusEvent(SensorStatusEvent &event, SensorPlugData info) +{ + event.sensorType = info.sensorTypeId; + event.sensorId = info.sensorId; + if (info.status == SENSOR_ONLINE) { + event.isSensorOnline = true; + } else { + event.isSensorOnline = false; + } + event.deviceId = info.deviceId; + event.deviceName = info.deviceName; + if (info.location == IS_LOCAL_DEVICE) { + event.location = true; + } + event.location = false; + event.timestamp = info.timestamp; +} + +bool SensorAgentProxy::UpdataSensorInfo(SensorPlugData info) +{ + CALL_LOG_ENTER; + if (info.status == SENSOR_ONLINE) { + SensorInfo *sensorInfos = nullptr; + int32_t count = 0; + int32_t ret = GetDeviceSensors(info.deviceId, &sensorInfos, &count); + if (ret != ERR_OK) { + SEN_HILOGE("UpdataSensorInfo failed"); + return false; + } + free(sensorInfos); + sensorInfos = nullptr; + } else { + if (!(SEN_CLIENT.EraseCacheSensorList(info))) { + SEN_HILOGE("EraseCacheSensorList failed"); + return false; + } + EraseCacheSensorInfos(info); + } + return true; +} + +void SensorAgentProxy::EraseCacheSensorInfos(SensorPlugData info) +{ + std::lock_guard listLock(sensorInfoMutex_); + for (int32_t i = 0; i < sensorInfoCount_; ++i) { + if ((sensorInfoCheck_.sensorInfos[i].deviceId == info.deviceId) && + (sensorInfoCheck_.sensorInfos[i].sensorTypeId == info.sensorTypeId) && + (sensorInfoCheck_.sensorInfos[i].sensorId == info.sensorId)) { + for (int j = i; j < sensorInfoCount_ - 1; ++j) { + sensorInfoCheck_.sensorInfos[j] = sensorInfoCheck_.sensorInfos[j+1]; + } + sensorInfoCount_--; + break; + } + } +} + +bool SensorAgentProxy::HandlePlugSensorData(const SensorPlugData &info) __attribute__((no_sanitize("cfi"))) +{ + CALL_LOG_ENTER; + std::lock_guard subscribePlugLock(subscribePlugMutex_); + if (!UpdataSensorInfo(info)) { + return false; + } + SensorStatusEvent event; + UpdataSensorStatusEvent(event, info); + for (const auto &it : subscribeSet_) { + if (it->plugCallback != nullptr) { + SEN_HILOGD("plug callback is run"); + it->plugCallback(&event); + } + } + return true; +} } // namespace Sensors } // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/src/sensor_client_stub.cpp b/frameworks/native/src/sensor_client_stub.cpp index 6a6f44355ab29a992173bc3a7b0a572949d83913..630aa717b742ca705721416524f6cdccf18fb9af 100644 --- a/frameworks/native/src/sensor_client_stub.cpp +++ b/frameworks/native/src/sensor_client_stub.cpp @@ -15,6 +15,8 @@ #include "sensor_client_stub.h" +#include "sensor_agent_proxy.h" +#include "sensor_errors.h" #include "sensor_log.h" #undef LOG_TAG @@ -33,6 +35,56 @@ int32_t SensorClientStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Me return OBJECT_NULL; } SEN_HILOGD("Begin, cmd:%{public}u", code); + if (code != PROCESS_PLUG_EVENT) { + SEN_HILOGE("code parameter error."); + return PARAMETER_ERROR; + } + SensorPlugData info; + if (!data.ReadInt32(info.deviceId)) { + SEN_HILOGE("Read deviceId failed."); + return PARAMETER_ERROR; + } + if (!data.ReadInt32(info.sensorTypeId)) { + SEN_HILOGE("Read sensorTypeId failed."); + return PARAMETER_ERROR; + } + if (!data.ReadInt32(info.sensorId)) { + SEN_HILOGE("Read sensorId failed."); + return PARAMETER_ERROR; + } + if (!data.ReadInt32(info.location)) { + SEN_HILOGE("Read location failed."); + return PARAMETER_ERROR; + } + if (!data.ReadString(info.deviceName)) { + SEN_HILOGE("Read deviceName failed."); + return PARAMETER_ERROR; + } + if (!data.ReadInt32(info.status)) { + SEN_HILOGE("Read status failed."); + return PARAMETER_ERROR; + } + if (!data.ReadInt32(info.reserved)) { + SEN_HILOGE("Read reserved failed."); + return PARAMETER_ERROR; + } + if (!data.ReadInt64(info.timestamp)) { + SEN_HILOGE("Read timestamp failed."); + return PARAMETER_ERROR; + } + int32_t result = ProcessPlugEvent(info); + reply.WriteInt32(result); + return NO_ERROR; +} + +int32_t SensorClientStub::ProcessPlugEvent(const SensorPlugData &info) +{ + CALL_LOG_ENTER; + if (!(SENSOR_AGENT_IMPL->HandlePlugSensorData(info))) { + SEN_HILOGE("Handle sensor data failed"); + return PARAMETER_ERROR; + } + SEN_HILOGD("Success to process plug event"); return NO_ERROR; } } // namespace Sensors diff --git a/frameworks/native/src/sensor_file_descriptor_listener.cpp b/frameworks/native/src/sensor_file_descriptor_listener.cpp index 074ee3af44018cd8b55a2160aedd357e0a90d788..ec1a564f451104cfaf76e9eb2dfa79f559d1ba41 100644 --- a/frameworks/native/src/sensor_file_descriptor_listener.cpp +++ b/frameworks/native/src/sensor_file_descriptor_listener.cpp @@ -72,7 +72,10 @@ void SensorFileDescriptorListener::ExcuteCallback(int32_t length) .option = receiveDataBuff_[i].option, .mode = receiveDataBuff_[i].mode, .data = receiveDataBuff_[i].data, - .dataLen = receiveDataBuff_[i].dataLen + .dataLen = receiveDataBuff_[i].dataLen, + .deviceId = receiveDataBuff_[i].deviceId, + .sensorId = receiveDataBuff_[i].sensorId, + .location = receiveDataBuff_[i].location }; if (receiveDataBuff_[i].sensorTypeId == SENSOR_TYPE_ID_HALL_EXT) { PrintSensorData::GetInstance().PrintSensorDataLog("ExcuteCallback", receiveDataBuff_[i]); diff --git a/frameworks/native/src/sensor_service_client.cpp b/frameworks/native/src/sensor_service_client.cpp index b6a257c49f45ff8062c57aefacfa54f302db52af..2e4c761106557e4f949ee9eb2e0bc2a12c082fcc 100644 --- a/frameworks/native/src/sensor_service_client.cpp +++ b/frameworks/native/src/sensor_service_client.cpp @@ -55,6 +55,7 @@ SensorServiceClient::~SensorServiceClient() remoteObject->RemoveDeathRecipient(serviceDeathObserver_); } } + DestroyClientRemoteObject(); Disconnect(); } @@ -90,6 +91,11 @@ int32_t SensorServiceClient::InitServiceClient() if (sensorList_.empty()) { SEN_HILOGW("sensorList_ is empty when connecting to the service for the first time"); } + ret = TransferClientRemoteObject(); + if (ret != ERR_OK) { + SEN_HILOGE("TransferClientRemoteObject failed, ret:%{public}d", ret); + return ret; + } return ERR_OK; } SEN_HILOGW("Get service failed"); @@ -101,7 +107,7 @@ int32_t SensorServiceClient::InitServiceClient() return SENSOR_NATIVE_GET_SERVICE_ERR; } -bool SensorServiceClient::IsValid(int32_t sensorId) +bool SensorServiceClient::IsValid(const SensorDescription &sensorDesc) { int32_t ret = InitServiceClient(); if (ret != ERR_OK) { @@ -113,14 +119,16 @@ bool SensorServiceClient::IsValid(int32_t sensorId) return false; } for (auto &sensor : sensorList_) { - if (sensor.GetSensorId() == sensorId) { + if ((sensor.GetDeviceId() == sensorDesc.deviceId) && (sensor.GetSensorTypeId() == sensorDesc.sensorType) && + (sensor.GetSensorId() == sensorDesc.sensorId)) { return true; } } return false; } -int32_t SensorServiceClient::EnableSensor(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay) +int32_t SensorServiceClient::EnableSensor(const SensorDescription &sensorDesc, int64_t samplingPeriod, + int64_t maxReportDelay) { CALL_LOG_ENTER; int32_t ret = InitServiceClient(); @@ -133,18 +141,19 @@ int32_t SensorServiceClient::EnableSensor(int32_t sensorId, int64_t samplingPeri #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "EnableSensor"); #endif // HIVIEWDFX_HITRACE_ENABLE - ret = sensorServer_->EnableSensor(sensorId, samplingPeriod, maxReportDelay); + ret = sensorServer_->EnableSensor({sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location}, samplingPeriod, maxReportDelay); WriteHiSysIPCEvent(ISensorServiceIpcCode::COMMAND_ENABLE_SENSOR, ret); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE if (ret == ERR_OK) { - UpdateSensorInfoMap(sensorId, samplingPeriod, maxReportDelay); + UpdateSensorInfoMap(sensorDesc, samplingPeriod, maxReportDelay); } return ret; } -int32_t SensorServiceClient::DisableSensor(int32_t sensorId) +int32_t SensorServiceClient::DisableSensor(const SensorDescription &sensorDesc) { CALL_LOG_ENTER; int32_t ret = InitServiceClient(); @@ -157,13 +166,14 @@ int32_t SensorServiceClient::DisableSensor(int32_t sensorId) #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "DisableSensor"); #endif // HIVIEWDFX_HITRACE_ENABLE - ret = sensorServer_->DisableSensor(sensorId); + ret = sensorServer_->DisableSensor({sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location}); WriteHiSysIPCEvent(ISensorServiceIpcCode::COMMAND_DISABLE_SENSOR, ret); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE if (ret == ERR_OK) { - DeleteSensorInfoItem(sensorId); + DeleteSensorInfoItem(sensorDesc); } return ret; } @@ -183,6 +193,79 @@ std::vector SensorServiceClient::GetSensorList() return sensorList_; } +int32_t SensorServiceClient::GetSensorListByDevice(int32_t deviceId, std::vector &singleDevSensors) +{ + CALL_LOG_ENTER; + int32_t ret = InitServiceClient(); + if (ret != ERR_OK) { + SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret); + return ret; + } + std::lock_guard clientLock(clientMutex_); + for (const auto& sensor : sensorList_) { + if (sensor.GetDeviceId() == deviceId) { + SEN_HILOGD("sensor.GetDeviceId():%{public}d, deviceId:%{public}d", sensor.GetDeviceId(), deviceId); + singleDevSensors.push_back(sensor); + } + } + if (singleDevSensors.empty()) { + singleDevSensors = GetSensorListByDevice(deviceId); + if (singleDevSensors.empty()) { + SEN_HILOGE("GetSensorListByDevice failed, singleDevSensors cannot be empty"); + return SERVICE_EXCEPTION; + } + } + return ERR_OK; +} + +std::vector SensorServiceClient::GetSensorListByDevice(int32_t deviceId) +{ + CALL_LOG_ENTER; + std::vector singleDevSensors; + int32_t ret = sensorServer_->GetSensorListByDevice(deviceId, singleDevSensors); + if (ret != ERR_OK) { + SEN_HILOGE("GetSensorListByDevice failed, ret:%{public}d", ret); + return {}; + } + if (singleDevSensors.empty()) { + SEN_HILOGE("GetSensorListByDevice failed,singleDevSensors cannot be empty"); + return {}; + } + for (const auto& newSensor : singleDevSensors) { + bool found = false; + for (const auto& oldSensor : sensorList_) { + if (oldSensor.GetDeviceId() == newSensor.GetDeviceId() && + oldSensor.GetSensorId() == newSensor.GetSensorId() && + oldSensor.GetSensorTypeId() == newSensor.GetSensorTypeId()) { + found = true; + break; + } + } + if (!found) { + SEN_HILOGD("Sensor not found in sensorList_"); + sensorList_.push_back(newSensor); + } + } + return singleDevSensors; +} + +int32_t SensorServiceClient::GetLocalDeviceId(int32_t& deviceId) +{ + CALL_LOG_ENTER; + if (sensorList_.empty()) { + std::vector allSensors = GetSensorList(); + } + for (const auto& sensor : sensorList_) { + if (sensor.GetLocation() == 1) { + SEN_HILOGI("local deviceId is:%{public}d", sensor.GetDeviceId()); + deviceId = sensor.GetDeviceId(); + return ERR_OK; + } + } + SEN_HILOGE("Get local deviceId failed, sensor list size: %{public}zu", sensorList_.size()); + return SERVICE_EXCEPTION; +} + int32_t SensorServiceClient::TransferDataChannel(sptr sensorDataChannel) { SEN_HILOGI("In"); @@ -250,8 +333,8 @@ void SensorServiceClient::ReenableSensor() std::lock_guard mapLock(mapMutex_); for (const auto &it : sensorInfoMap_) { if (sensorServer_ != nullptr) { - int32_t ret = sensorServer_->EnableSensor(it.first, it.second.GetSamplingPeriodNs(), - it.second.GetMaxReportDelayNs()); + int32_t ret = sensorServer_->EnableSensor({it.first.deviceId, it.first.sensorType, it.first.sensorId, + it.first.location}, it.second.GetSamplingPeriodNs(), it.second.GetMaxReportDelayNs()); WriteHiSysIPCEvent(ISensorServiceIpcCode::COMMAND_ENABLE_SENSOR, ret); } } @@ -264,6 +347,60 @@ void SensorServiceClient::ReenableSensor() CreateSocketChannel(); } +int32_t SensorServiceClient::CreateClientRemoteObject() +{ + CALL_LOG_ENTER; + int32_t ret = InitServiceClient(); + if (ret != ERR_OK) { + SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret); + } + return ret; +} + +int32_t SensorServiceClient::TransferClientRemoteObject() +{ + CALL_LOG_ENTER; +#ifdef HIVIEWDFX_HITRACE_ENABLE + StartTrace(HITRACE_TAG_SENSORS, "TransferClientRemoteObject"); +#endif // HIVIEWDFX_HITRACE_ENABLE + CHKPR(sensorClientStub_, INVALID_POINTER); + auto remoteObject = sensorClientStub_->AsObject(); + CHKPR(remoteObject, INVALID_POINTER); + int32_t ret = sensorServer_->TransferClientRemoteObject(remoteObject); + SEN_HILOGI("TransferClientRemoteObject ret:%{public}d", ret); + WriteHiSysIPCEvent(ISensorServiceIpcCode::COMMAND_TRANSFER_CLIENT_REMOTE_OBJECT, ret); +#ifdef HIVIEWDFX_HITRACE_ENABLE + FinishTrace(HITRACE_TAG_SENSORS); +#endif // HIVIEWDFX_HITRACE_ENABLE + SEN_HILOGI("Done"); + return ret; +} + +int32_t SensorServiceClient::DestroyClientRemoteObject() +{ + CALL_LOG_ENTER; + int32_t ret = InitServiceClient(); + if (ret != ERR_OK) { + SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret); + } + std::lock_guard clientLock(clientMutex_); + CHKPR(sensorServer_, ERROR); +#ifdef HIVIEWDFX_HITRACE_ENABLE + StartTrace(HITRACE_TAG_SENSORS, "TransferClientRemoteObject"); +#endif // HIVIEWDFX_HITRACE_ENABLE + CHKPR(sensorClientStub_, INVALID_POINTER); + auto remoteObject = sensorClientStub_->AsObject(); + CHKPR(remoteObject, INVALID_POINTER); + ret = sensorServer_->DestroyClientRemoteObject(remoteObject); + SEN_HILOGI("DestroyClientRemoteObject ret:%{public}d", ret); + WriteHiSysIPCEvent(ISensorServiceIpcCode::COMMAND_DESTROY_CLIENT_REMOTE_OBJECT, ret); +#ifdef HIVIEWDFX_HITRACE_ENABLE + FinishTrace(HITRACE_TAG_SENSORS); +#endif // HIVIEWDFX_HITRACE_ENABLE + SEN_HILOGI("Done"); + return ret; +} + void SensorServiceClient::WriteHiSysIPCEvent(ISensorServiceIpcCode code, int32_t ret) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE @@ -305,10 +442,31 @@ void SensorServiceClient::WriteHiSysIPCEvent(ISensorServiceIpcCode code, int32_t HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SERVICE_IPC_EXCEPTION", HiSysEvent::EventType::FAULT, "PKG_NAME", "ResetSensors", "ERROR_CODE", ret); break; + default: + break; + } + } + WriteHiSysIPCEventSplit(code, ret); +#endif // HIVIEWDFX_HISYSEVENT_ENABLE +} + +void SensorServiceClient::WriteHiSysIPCEventSplit(ISensorServiceIpcCode code, int32_t ret) +{ +#ifdef HIVIEWDFX_HISYSEVENT_ENABLE + if (ret != NO_ERROR) { + switch (code) { case ISensorServiceIpcCode::COMMAND_SET_DEVICE_STATUS: HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SERVICE_IPC_EXCEPTION", HiSysEvent::EventType::FAULT, "PKG_NAME", "SetDeviceStatus", "ERROR_CODE", ret); break; + case ISensorServiceIpcCode::COMMAND_TRANSFER_CLIENT_REMOTE_OBJECT: + HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SERVICE_IPC_EXCEPTION", HiSysEvent::EventType::FAULT, + "PKG_NAME", "TransferClientRemoteObject", "ERROR_CODE", ret); + break; + case ISensorServiceIpcCode::COMMAND_DESTROY_CLIENT_REMOTE_OBJECT: + HiSysEventWrite(HiSysEvent::Domain::SENSOR, "SERVICE_IPC_EXCEPTION", HiSysEvent::EventType::FAULT, + "PKG_NAME", "DestroyClientRemoteObject", "ERROR_CODE", ret); + break; default: SEN_HILOGW("Code does not exist, code:%{public}d", static_cast(code)); break; @@ -362,7 +520,8 @@ void SensorServiceClient::ProcessDeathObserver(const wptr &object ReenableSensor(); } -void SensorServiceClient::UpdateSensorInfoMap(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay) +void SensorServiceClient::UpdateSensorInfoMap(const SensorDescription &sensorDesc, int64_t samplingPeriod, + int64_t maxReportDelay) { SEN_HILOGI("In"); SensorBasicInfo sensorInfo; @@ -370,16 +529,16 @@ void SensorServiceClient::UpdateSensorInfoMap(int32_t sensorId, int64_t sampling sensorInfo.SetMaxReportDelayNs(maxReportDelay); sensorInfo.SetSensorState(true); std::lock_guard mapLock(mapMutex_); - sensorInfoMap_[sensorId] = sensorInfo; + sensorInfoMap_[sensorDesc] = sensorInfo; SEN_HILOGI("Done"); return; } -void SensorServiceClient::DeleteSensorInfoItem(int32_t sensorId) +void SensorServiceClient::DeleteSensorInfoItem(const SensorDescription &sensorDesc) { SEN_HILOGI("In"); std::lock_guard mapLock(mapMutex_); - auto it = sensorInfoMap_.find(sensorId); + auto it = sensorInfoMap_.find(sensorDesc); if (it != sensorInfoMap_.end()) { sensorInfoMap_.erase(it); } @@ -686,5 +845,26 @@ void SensorServiceClient::SetDeviceStatus(uint32_t deviceStatus) FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE } + +bool SensorServiceClient::EraseCacheSensorList(SensorPlugData info) +{ + CALL_LOG_ENTER; + std::lock_guard clientLock(clientMutex_); + if (sensorList_.empty()) { + SEN_HILOGE("sensorList_ cannot be empty"); + return false; + } + auto it = std::find_if(sensorList_.begin(), sensorList_.end(), [&](const Sensor& sensor) { + return sensor.GetDeviceId() == info.deviceId && + sensor.GetSensorTypeId() == info.sensorTypeId && + sensor.GetSensorId() == info.sensorId; + }); + if (it != sensorList_.end()) { + sensorList_.erase(it); + return true; + } + SEN_HILOGD("sensorList_ cannot find the sensor"); + return true; +} } // namespace Sensors } // namespace OHOS diff --git a/interfaces/inner_api/sensor_agent.h b/interfaces/inner_api/sensor_agent.h index 6ce08dc72f416c7d3106b67bf011939d7c1ff335..d73bafdc1e6695d9cebe1ce4a184e44914b6a955 100755 --- a/interfaces/inner_api/sensor_agent.h +++ b/interfaces/inner_api/sensor_agent.h @@ -191,6 +191,124 @@ int32_t ResetSensors(); void SetDeviceStatus(uint32_t deviceStatus); +/** + * @brief Obtains information about all sensors in the specified device. + * + * @param sensorInfo Indicates the double pointer to the information about all sensors in the specified device. + * For details, see {@link SensorInfo}. + * @param count Indicates the pointer to the total number of sensors in the specified device. + * @param deviceId Indicates the ID of the device from which to obtain sensor information. + * @return Returns 0 if the information is obtained; returns a non-zero value otherwise. + * + * @since 19 + */ +int32_t GetDeviceSensors(int32_t deviceId, SensorInfo **sensorInfo, int32_t *count); + +/** + * @brief Subscribes to sensor data. The system will report the obtained sensor data to the subscriber. + * + * @param sensorIdentifier including the sensorid, deviceid, and sensortype required for dynamic multi-sensors, + * see {@link SensorIdentifier}. + * @param user Indicates the pointer to the sensor subscriber that requests sensor data. For details, + * see {@link SensorUser}. A subscriber can obtain data from only one sensor. + * @return Returns 0 if the subscription is successful; returns a non-zero value otherwise. + * + * @since 19 + */ +int32_t SubscribeSensorEnhanced(const SensorIdentifier &sensorIdentifier, const SensorUser *user); + +/** + * @brief Unsubscribes from sensor data. + * + * @param sensorIdentifier including the sensorid, deviceid, and sensortype required for dynamic multi-sensors, + * see {@link SensorIdentifier}. + * @param user Indicates the pointer to the sensor subscriber that requests sensor data. + * For details, see {@link SensorUser}. A subscriber can obtain data from only one sensor. + * @return Returns 0 if the unsubscription is successful; returns a non-zero value otherwise. + * + * @since 19 + */ +int32_t UnsubscribeSensorEnhanced(const SensorIdentifier &sensorIdentifier, const SensorUser *user); + +/** + * @brief Sets the data sampling interval and data reporting interval for the specified sensor. + * + * @param sensorIdentifier including the sensorid, deviceid, and sensortype required for dynamic multi-sensors, + * see {@link SensorIdentifier}. + * @param user Indicates the pointer to the sensor subscriber that requests sensor data. + * For details, see {@link SensorUser}. A subscriber can obtain data from only one sensor. + * @param samplingInterval Indicates the sensor data sampling interval to set, in nanoseconds. + * @param reportInterval Indicates the sensor data reporting interval, in nanoseconds. + * @return Returns 0 if the setting is successful; returns a non-zero value otherwise. + * + * @since 19 + */ +int32_t SetBatchEnhanced(const SensorIdentifier &sensorIdentifier, const SensorUser *user, int64_t samplingInterval, + int64_t reportInterval); + +/** + * @brief Enables the sensor that has been subscribed to. The subscriber can obtain the sensor data + * only after the sensor is enabled. + * + * @param sensorIdentifier including the sensorid, deviceid, and sensortype required for dynamic multi-sensors, + * see {@link SensorIdentifier}. + * @param user Indicates the pointer to the sensor subscriber that requests sensor data. + * For details, see {@link SensorUser}. A subscriber can obtain data from only one sensor. + * @return Returns 0 if the sensor is successfully enabled; returns a non-zero value otherwise. + * + * @since 19 + */ +int32_t ActivateSensorEnhanced(const SensorIdentifier &sensorIdentifier, const SensorUser *user); + +/** + * @brief Disables an enabled sensor. + * + * @param sensorIdentifier including the sensorid, deviceid, and sensortype required for dynamic multi-sensors, + * see {@link SensorIdentifier}. + * @param user Indicates the pointer to the sensor subscriber that requests sensor data. + * For details, see {@link SensorUser}. A subscriber can obtain data from only one sensor. + * @return Returns 0 if the sensor is successfully disabled; returns a non-zero value otherwise. + * + * @since 19 + */ +int32_t DeactivateSensorEnhanced(const SensorIdentifier &sensorIdentifier, const SensorUser *user); + +/** + * @brief Sets the data reporting mode for the specified sensor. + * + * @param sensorIdentifier including the sensorid, deviceid, and sensortype required for dynamic multi-sensors, + * see {@link SensorIdentifier}. + * @param user Indicates the pointer to the sensor subscriber that requests sensor data. + * For details, see {@link SensorUser}. A subscriber can obtain data from only one sensor. + * @param mode Indicates the data reporting mode to set. For details, see {@link SensorMode}. + * @return Returns 0 if the sensor data reporting mode is successfully set; returns a non-zero value otherwise. + * + * @since 19 + */ +int32_t SetModeEnhanced(const SensorIdentifier &sensorIdentifier, const SensorUser *user, int32_t mode); + +/** + * @brief Subscribes to sensor status updates. The system will report the obtained sensor status data + * to the subscriber. + * + * @param user Indicates the pointer to the sensor subscriber that requests sensor data. For details, + * @return Returns 0 if the subscription is successful; returns a non-zero value otherwise. + * + * @since 19 + */ +int32_t SubscribeSensorPlug(const SensorUser *user); + +/** + * @brief Unsubscribes from sensor status updates. + * + * @param user Indicates the pointer to the sensor subscriber that requests sensor data. + * For details, see {@link SensorUser}. + * @return Returns 0 if the unsubscription is successful; returns a non-zero value otherwise. + * + * @since 19 + */ +int32_t UnsubscribeSensorPlug(const SensorUser *user); + #ifdef __cplusplus #if __cplusplus } diff --git a/interfaces/inner_api/sensor_agent_type.h b/interfaces/inner_api/sensor_agent_type.h index 5d57cb2ebbcd277d214ad521042936dac75317b7..0a1d238e1ab84354265e61b7d8dc022f76b88bcf 100644 --- a/interfaces/inner_api/sensor_agent_type.h +++ b/interfaces/inner_api/sensor_agent_type.h @@ -38,6 +38,7 @@ #define SENSOR_AGENT_TYPE_H #include +#include #ifdef __cplusplus #if __cplusplus @@ -123,6 +124,8 @@ typedef struct SensorInfo { float power = 0.0; /**< Sensor power */ int64_t minSamplePeriod = -1; /**< Minimum sample period allowed, in ns */ int64_t maxSamplePeriod = -1; /**< Maximum sample period allowed, in ns */ + int32_t deviceId = -1; /**< Device ID */ + int32_t location = -1; /**< Is the device a local device or an external device */ } SensorInfo; /** @@ -158,6 +161,9 @@ typedef struct SensorEvent { int32_t mode = -1; /**< Sensor data reporting mode (described in {@link SensorMode}) */ uint8_t *data = nullptr; /**< Sensor data */ uint32_t dataLen = 0; /**< Sensor data length */ + int32_t deviceId = -1; /**< Device ID */ + int32_t sensorId = -1; /**< Sensor ID */ + int32_t location = -1; /**< Is the device a local device or an external device */ } SensorEvent; /** @@ -167,6 +173,23 @@ typedef struct SensorEvent { */ typedef void (*RecordSensorCallback)(SensorEvent *event); +typedef struct SensorStatusEvent { + int64_t timestamp = -1; /**< Time when sensor data was reported */ + int32_t sensorType = -1; /**< Sensor type ID */ + int32_t sensorId = -1; /**< Sensor ID */ + bool isSensorOnline = false; /**< Whether the sensor is online */ + int32_t deviceId = -1; /**< Device ID */ + std::string deviceName = ""; /**< Device name */ + int32_t location = -1; /**< Is the device a local device or an external device */ +} SensorStatusEvent; + +/** + * @brief Defines the callback for data reporting by the sensor plug in/out state. + * + * @since 18 + */ +typedef void (*SensorPlugCallback)(SensorStatusEvent *statusEvent); + /** * @brief Defines a reserved field for the sensor data subscriber. * @@ -184,6 +207,7 @@ typedef struct UserData { typedef struct SensorUser { char name[NAME_MAX_LEN]; /**< Name of the sensor data subscriber */ RecordSensorCallback callback; /**< Callback for reporting sensor data */ + SensorPlugCallback plugCallback; /**< Callback for reporting sensor plug data */ UserData *userData = nullptr; /**< Reserved field for the sensor data subscriber */ } SensorUser; @@ -524,6 +548,13 @@ typedef struct FusionPressureData { float fusionPressure = 0.0f; } FusionPressureData; +typedef struct SensorIdentifier { + int32_t deviceId = -1; /**< device ID */ + int32_t sensorType = -1; /**< sensor type ID */ + int32_t sensorId = -1; /**< sensor ID, defined by the sensor driver developer */ + int32_t location = -1; /**< Is the device a local device or an external device */ +} SensorIdentifier; + typedef void (*SensorActiveInfoCB)(SensorActiveInfo &sensorActiveInfo); #ifdef __cplusplus diff --git a/services/BUILD.gn b/services/BUILD.gn index eff39346643ffab23110907772998f34b759e93e..83c20ebac91c03246cfb49c7669edc794c21af38 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -104,6 +104,7 @@ ohos_shared_library("libsensor_service") { sources += [ "hdi_connection/adapter/src/hdi_connection.cpp", "hdi_connection/adapter/src/sensor_event_callback.cpp", + "hdi_connection/adapter/src/sensor_plug_callback.cpp", "hdi_connection/interface/src/sensor_hdi_connection.cpp", "src/sensor_data_processer.cpp", ] @@ -222,6 +223,7 @@ ohos_static_library("libsensor_service_static") { sources += [ "hdi_connection/adapter/src/hdi_connection.cpp", "hdi_connection/adapter/src/sensor_event_callback.cpp", + "hdi_connection/adapter/src/sensor_plug_callback.cpp", "hdi_connection/interface/src/sensor_hdi_connection.cpp", "src/sensor_data_processer.cpp", ] diff --git a/services/hdi_connection/adapter/include/compatible_connection.h b/services/hdi_connection/adapter/include/compatible_connection.h index 75460182ec1d71e95bbdaeb9b702b326f67f010f..0fe14a779f25f87438238cbd38a23e6f6a896d1b 100644 --- a/services/hdi_connection/adapter/include/compatible_connection.h +++ b/services/hdi_connection/adapter/include/compatible_connection.h @@ -27,18 +27,22 @@ public: virtual ~CompatibleConnection() {} int32_t ConnectHdi() override; int32_t GetSensorList(std::vector &sensorList) override; - int32_t EnableSensor(int32_t sensorId) override; - int32_t DisableSensor(int32_t sensorId) override; - int32_t SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) override; - int32_t SetMode(int32_t sensorId, int32_t mode) override; + int32_t GetSensorListByDevice(int32_t deviceId, std::vector &singleDevSensors) override; + int32_t EnableSensor(const SensorDescription &sensorDesc) override; + int32_t DisableSensor(const SensorDescription &sensorDesc) override; + int32_t SetBatch(const SensorDescription &sensorDesc, int64_t samplingInterval, int64_t reportInterval) override; + int32_t SetMode(const SensorDescription &sensorDesc, int32_t mode) override; int32_t RegisterDataReport(ReportDataCb cb, sptr reportDataCallback) override; int32_t DestroyHdiConnection() override; + int32_t RegSensorPlugCallback(DevicePlugCallback cb) override; + DevicePlugCallback GetSensorPlugCb() override; private: DISALLOW_COPY_AND_MOVE(CompatibleConnection); static void ReportSensorDataCallback(SensorEvent *event); static ReportDataCb reportDataCb_; static sptr reportDataCallback_; + static DevicePlugCallback reportPlugDataCb_; HdiServiceImpl &hdiServiceImpl_ = HdiServiceImpl::GetInstance(); }; } // namespace Sensors diff --git a/services/hdi_connection/adapter/include/hdi_connection.h b/services/hdi_connection/adapter/include/hdi_connection.h index fbc192b09fb2a6a6eed09dedc1a86a8123260133..867a2bfa7400c6e6c6bc00f961d379daf6bf2822 100644 --- a/services/hdi_connection/adapter/include/hdi_connection.h +++ b/services/hdi_connection/adapter/include/hdi_connection.h @@ -28,27 +28,31 @@ public: virtual ~HdiConnection() {} int32_t ConnectHdi() override; int32_t GetSensorList(std::vector &sensorList) override; - int32_t EnableSensor(int32_t sensorId) override; - int32_t DisableSensor(int32_t sensorId) override; - int32_t SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) override; - int32_t SetMode(int32_t sensorId, int32_t mode) override; + int32_t GetSensorListByDevice(int32_t deviceId, std::vector &singleDevSensors) override; + int32_t EnableSensor(const SensorDescription &sensorDesc) override; + int32_t DisableSensor(const SensorDescription &sensorDesc) override; + int32_t SetBatch(const SensorDescription &sensorDesc, int64_t samplingInterval, int64_t reportInterval) override; + int32_t SetMode(const SensorDescription &sensorDesc, int32_t mode) override; int32_t RegisterDataReport(ReportDataCb cb, sptr reportDataCallback) override; int32_t DestroyHdiConnection() override; ReportDataCb GetReportDataCb(); sptr GetReportDataCallback(); void ProcessDeathObserver(const wptr &object); + int32_t RegSensorPlugCallback(DevicePlugCallback cb) override; + DevicePlugCallback GetSensorPlugCb() override; private: DISALLOW_COPY_AND_MOVE(HdiConnection); static ReportDataCb reportDataCb_; + static DevicePlugCallback reportPlugDataCb_; static sptr reportDataCallback_; sptr hdiDeathObserver_ = nullptr; void RegisterHdiDeathRecipient(); void UnregisterHdiDeathRecipient(); void Reconnect(); - void UpdateSensorBasicInfo(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); - void SetSensorBasicInfoState(int32_t sensorId, bool state); - void DeleteSensorBasicInfoState(int32_t sensorId); + void UpdateSensorBasicInfo(const SensorDescription &sensorDesc, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + void SetSensorBasicInfoState(const SensorDescription &sensorDesc, bool state); + void DeleteSensorBasicInfoState(const SensorDescription &sensorDesc); }; } // namespace Sensors } // namespace OHOS diff --git a/services/hdi_connection/adapter/include/sensor_plug_callback.h b/services/hdi_connection/adapter/include/sensor_plug_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..5cb108a00bed58e0ec62c099cf83199c15dfde3e --- /dev/null +++ b/services/hdi_connection/adapter/include/sensor_plug_callback.h @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_PLUG_CALLBACK_H +#define SENSOR_PLUG_CALLBACK_H + +#include "v3_0/isensor_plug_callback.h" +#include "v3_0/sensor_types.h" + +using OHOS::HDI::Sensor::V3_0::SensorPlugInfo; +using OHOS::HDI::Sensor::V3_0::ISensorPlugCallback; + +namespace OHOS { +namespace Sensors { +class SensorPlugCallback : public ISensorPlugCallback { +public: + virtual ~SensorPlugCallback() {} + int32_t OnSensorPlugEvent(const SensorPlugInfo &plugEvent) override; +}; +} // namespace Sensors +} // namespace OHOS +#endif // SENSOR_PLUG_CALLBACK_H diff --git a/services/hdi_connection/adapter/src/compatible_connection.cpp b/services/hdi_connection/adapter/src/compatible_connection.cpp index a368fda1fdc1ac6a949af331c06aee83e4cc8e6e..8b5364737a9b7859b9ae20a2adfc60f0eae928be 100644 --- a/services/hdi_connection/adapter/src/compatible_connection.cpp +++ b/services/hdi_connection/adapter/src/compatible_connection.cpp @@ -51,10 +51,15 @@ int32_t CompatibleConnection::GetSensorList(std::vector &sensorList) const std::string firmwareVersion(sensorInfos[i].firmwareVersion); const std::string hardwareVersion(sensorInfos[i].hardwareVersion); const int32_t sensorId = sensorInfos[i].sensorId; + const int32_t sensorTypeId = sensorInfos[i].sensorTypeId; + const int32_t deviceId = sensorInfos[i].deviceId; + const int32_t location = sensorInfos[i].location; const float maxRange = sensorInfos[i].maxRange; Sensor sensor; + sensor.SetDeviceId(deviceId); sensor.SetSensorId(sensorId); - sensor.SetSensorTypeId(sensorId); + sensor.SetSensorTypeId(sensorTypeId); + sensor.SetLocation(location); sensor.SetFirmwareVersion(firmwareVersion); sensor.SetHardwareVersion(hardwareVersion); sensor.SetMaxRange(maxRange); @@ -69,41 +74,46 @@ int32_t CompatibleConnection::GetSensorList(std::vector &sensorList) return ERR_OK; } -int32_t CompatibleConnection::EnableSensor(int32_t sensorId) +int32_t CompatibleConnection::EnableSensor(const SensorDescription &sensorDesc) { - int32_t ret = hdiServiceImpl_.EnableSensor(sensorId); + int32_t ret = hdiServiceImpl_.EnableSensor(sensorDesc); if (ret != 0) { - SEN_HILOGE("Enable sensor failed, sensorId:%{public}d", sensorId); + SEN_HILOGE("Enable sensor failed, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return ret; } return ERR_OK; }; -int32_t CompatibleConnection::DisableSensor(int32_t sensorId) +int32_t CompatibleConnection::DisableSensor(const SensorDescription &sensorDesc) { - int32_t ret = hdiServiceImpl_.DisableSensor(sensorId); + int32_t ret = hdiServiceImpl_.DisableSensor(sensorDesc); if (ret != 0) { - SEN_HILOGE("Disable sensor failed, sensorId:%{public}d", sensorId); + SEN_HILOGE("Disable sensor failed, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return ret; } return ERR_OK; } -int32_t CompatibleConnection::SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) +int32_t CompatibleConnection::SetBatch(const SensorDescription &sensorDesc, int64_t samplingInterval, + int64_t reportInterval) { - int32_t ret = hdiServiceImpl_.SetBatch(sensorId, samplingInterval, reportInterval); + int32_t ret = hdiServiceImpl_.SetBatch(sensorDesc, samplingInterval, reportInterval); if (ret != 0) { - SEN_HILOGE("Set batch failed, sensorId:%{public}d", sensorId); + SEN_HILOGE("Set batch failed, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return ret; } return ERR_OK; } -int32_t CompatibleConnection::SetMode(int32_t sensorId, int32_t mode) +int32_t CompatibleConnection::SetMode(const SensorDescription &sensorDesc, int32_t mode) { - int32_t ret = hdiServiceImpl_.SetMode(sensorId, mode); + int32_t ret = hdiServiceImpl_.SetMode(sensorDesc, mode); if (ret != 0) { - SEN_HILOGI("Set mode failed, sensorId:%{public}d", sensorId); + SEN_HILOGI("Set mode failed, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return ret; } return ERR_OK; @@ -123,7 +133,10 @@ void CompatibleConnection::ReportSensorDataCallback(SensorEvent *event) .timestamp = event->timestamp, .option = event->option, .mode = event->mode, - .dataLen = event->dataLen + .dataLen = event->dataLen, + .deviceId = event->deviceId, + .sensorId = event->sensorId, + .location = event->location }; CHKPV(sensorData.data); errno_t ret = memcpy_s(sensorData.data, sizeof(sensorData.data), event->data, event->dataLen); @@ -161,5 +174,57 @@ int32_t CompatibleConnection::DestroyHdiConnection() } return ERR_OK; } + +int32_t CompatibleConnection::GetSensorListByDevice(int32_t deviceId, std::vector &singleDevSensors) +{ + std::vector sensorInfos; + int32_t ret = hdiServiceImpl_.GetSensorListByDevice(deviceId, sensorInfos); + if (ret != 0) { + SEN_HILOGE("Get sensor list by device failed"); + return ret; + } + size_t count = sensorInfos.size(); + if (count > MAX_SENSOR_COUNT) { + SEN_HILOGD("SensorInfos size:%{public}zu", count); + count = MAX_SENSOR_COUNT; + } + for (size_t i = 0; i < count; i++) { + const std::string sensorName(sensorInfos[i].sensorName); + const std::string vendorName(sensorInfos[i].vendorName); + const std::string firmwareVersion(sensorInfos[i].firmwareVersion); + const std::string hardwareVersion(sensorInfos[i].hardwareVersion); + const int32_t sensorId = sensorInfos[i].sensorId; + const int32_t sensorTypeId = sensorInfos[i].sensorTypeId; + const int32_t deviceId = sensorInfos[i].deviceId; + const int32_t location = sensorInfos[i].location; + const float maxRange = sensorInfos[i].maxRange; + Sensor sensor; + sensor.SetDeviceId(deviceId); + sensor.SetSensorId(sensorId); + sensor.SetSensorTypeId(sensorTypeId); + sensor.SetLocation(location); + sensor.SetFirmwareVersion(firmwareVersion); + sensor.SetHardwareVersion(hardwareVersion); + sensor.SetMaxRange(maxRange); + sensor.SetSensorName(sensorName); + sensor.SetVendorName(vendorName); + sensor.SetResolution(sensorInfos[i].precision); + sensor.SetPower(sensorInfos[i].power); + sensor.SetMinSamplePeriodNs(sensorInfos[i].minSamplePeriod); + sensor.SetMaxSamplePeriodNs(sensorInfos[i].maxSamplePeriod); + singleDevSensors.push_back(sensor); + } + return ERR_OK; +} + +int32_t CompatibleConnection::RegSensorPlugCallback(DevicePlugCallback cb) +{ + return ERR_OK; +} + +DevicePlugCallback CompatibleConnection::GetSensorPlugCb() +{ + return NULL; +} } // namespace Sensors } // namespace OHOS \ No newline at end of file diff --git a/services/hdi_connection/adapter/src/hdi_connection.cpp b/services/hdi_connection/adapter/src/hdi_connection.cpp index 967b6025c4dc71ae3609e4bba57cd7d2d7499c25..12eba9706577a549873004e423bd5a2126ede21b 100644 --- a/services/hdi_connection/adapter/src/hdi_connection.cpp +++ b/services/hdi_connection/adapter/src/hdi_connection.cpp @@ -26,6 +26,7 @@ #include "sensor_agent_type.h" #include "sensor_errors.h" #include "sensor_event_callback.h" +#include "sensor_plug_callback.h" #undef LOG_TAG #define LOG_TAG "HdiConnection" @@ -33,14 +34,15 @@ namespace OHOS { namespace Sensors { using namespace OHOS::HiviewDFX; -using OHOS::HDI::Sensor::V3_0::DeviceSensorInfo; using OHOS::HDI::Sensor::V3_0::ISensorInterface; using OHOS::HDI::Sensor::V3_0::ISensorCallback; using OHOS::HDI::Sensor::V3_0::HdfSensorInformation; +using OHOS::HDI::Sensor::V3_0::ISensorPlugCallback; namespace { sptr g_sensorInterface = nullptr; sptr g_eventCallback = nullptr; -std::map g_sensorBasicInfoMap; +sptr g_plugCallback = nullptr; +std::map g_sensorBasicInfoMap; std::mutex g_sensorBasicInfoMutex; constexpr int32_t GET_HDI_SERVICE_COUNT = 25; constexpr uint32_t WAIT_MS = 200; @@ -48,6 +50,7 @@ constexpr int32_t HEADPOSTURE_FIFO_COUNT = 5; } // namespace ReportDataCb HdiConnection::reportDataCb_ = nullptr; +DevicePlugCallback HdiConnection::reportPlugDataCb_ = nullptr; sptr HdiConnection::reportDataCallback_ = nullptr; int32_t HdiConnection::ConnectHdi() @@ -60,6 +63,8 @@ int32_t HdiConnection::ConnectHdi() SEN_HILOGI("Connect v3_0 hdi success"); g_eventCallback = new (std::nothrow) SensorEventCallback(); CHKPR(g_eventCallback, ERR_NO_INIT); + g_plugCallback = new (std::nothrow) SensorPlugCallback(); + CHKPR(g_plugCallback, ERR_NO_INIT); RegisterHdiDeathRecipient(); return ERR_OK; } @@ -96,8 +101,10 @@ int32_t HdiConnection::GetSensorList(std::vector &sensorList) } for (size_t i = 0; i < count; i++) { Sensor sensor; - sensor.SetSensorId(sensorInfos[i].deviceSensorInfo.sensorType); + sensor.SetDeviceId(sensorInfos[i].deviceSensorInfo.deviceId); + sensor.SetSensorId(sensorInfos[i].deviceSensorInfo.sensorId); sensor.SetSensorTypeId(sensorInfos[i].deviceSensorInfo.sensorType); + sensor.SetLocation(sensorInfos[i].deviceSensorInfo.location); sensor.SetFirmwareVersion(sensorInfos[i].firmwareVersion); sensor.SetHardwareVersion(sensorInfos[i].hardwareVersion); sensor.SetMaxRange(sensorInfos[i].maxRange); @@ -107,7 +114,7 @@ int32_t HdiConnection::GetSensorList(std::vector &sensorList) sensor.SetPower(sensorInfos[i].power); sensor.SetMinSamplePeriodNs(sensorInfos[i].minDelay); sensor.SetMaxSamplePeriodNs(sensorInfos[i].maxDelay); - if (sensorInfos[i].deviceSensorInfo.sensorId == SENSOR_TYPE_ID_HEADPOSTURE) { + if (sensorInfos[i].deviceSensorInfo.sensorType == SENSOR_TYPE_ID_HEADPOSTURE) { sensor.SetFifoMaxEventCount(HEADPOSTURE_FIFO_COUNT); } sensorList.push_back(sensor); @@ -115,17 +122,13 @@ int32_t HdiConnection::GetSensorList(std::vector &sensorList) return ERR_OK; } -int32_t HdiConnection::EnableSensor(int32_t sensorId) +int32_t HdiConnection::EnableSensor(const SensorDescription &sensorDesc) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); + SEN_HILOGI("In, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); CHKPR(g_sensorInterface, ERR_NO_INIT); - DeviceSensorInfo deviceSensorInfo = { - .deviceId = 0, - .sensorType = sensorId, - .sensorId = 0, - .location = 0 - }; - int32_t ret = g_sensorInterface->Enable(deviceSensorInfo); + int32_t ret = g_sensorInterface->Enable({sensorDesc.deviceId, sensorDesc.sensorType, + sensorDesc.sensorId, sensorDesc.location}); if (ret != 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "HDF_SERVICE_EXCEPTION", @@ -134,22 +137,19 @@ int32_t HdiConnection::EnableSensor(int32_t sensorId) SEN_HILOGE("Connect v3_0 hdi failed"); return ret; } - SetSensorBasicInfoState(sensorId, true); - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + SetSensorBasicInfoState(sensorDesc, true); + SEN_HILOGI("Done, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return ERR_OK; } -int32_t HdiConnection::DisableSensor(int32_t sensorId) +int32_t HdiConnection::DisableSensor(const SensorDescription &sensorDesc) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); + SEN_HILOGI("In, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); CHKPR(g_sensorInterface, ERR_NO_INIT); - DeviceSensorInfo deviceSensorInfo = { - .deviceId = 0, - .sensorType = sensorId, - .sensorId = 0, - .location = 0 - }; - int32_t ret = g_sensorInterface->Disable(deviceSensorInfo); + int32_t ret = g_sensorInterface->Disable({sensorDesc.deviceId, sensorDesc.sensorType, + sensorDesc.sensorId, sensorDesc.location}); if (ret != 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "HDF_SERVICE_EXCEPTION", @@ -158,21 +158,17 @@ int32_t HdiConnection::DisableSensor(int32_t sensorId) SEN_HILOGE("Disable is failed"); return ret; } - DeleteSensorBasicInfoState(sensorId); - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + DeleteSensorBasicInfoState(sensorDesc); + SEN_HILOGI("Done, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return ERR_OK; } -int32_t HdiConnection::SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) +int32_t HdiConnection::SetBatch(const SensorDescription &sensorDesc, int64_t samplingInterval, int64_t reportInterval) { CHKPR(g_sensorInterface, ERR_NO_INIT); - DeviceSensorInfo deviceSensorInfo = { - .deviceId = 0, - .sensorType = sensorId, - .sensorId = 0, - .location = 0 - }; - int32_t ret = g_sensorInterface->SetBatch(deviceSensorInfo, samplingInterval, reportInterval); + int32_t ret = g_sensorInterface->SetBatch({sensorDesc.deviceId, sensorDesc.sensorType, + sensorDesc.sensorId, sensorDesc.location}, samplingInterval, reportInterval); if (ret != 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "HDF_SERVICE_EXCEPTION", @@ -181,21 +177,16 @@ int32_t HdiConnection::SetBatch(int32_t sensorId, int64_t samplingInterval, int6 SEN_HILOGE("SetBatch is failed"); return ret; } - UpdateSensorBasicInfo(sensorId, samplingInterval, reportInterval); + UpdateSensorBasicInfo(sensorDesc, samplingInterval, reportInterval); return ERR_OK; } -int32_t HdiConnection::SetMode(int32_t sensorId, int32_t mode) +int32_t HdiConnection::SetMode(const SensorDescription &sensorDesc, int32_t mode) { CALL_LOG_ENTER; CHKPR(g_sensorInterface, ERR_NO_INIT); - DeviceSensorInfo deviceSensorInfo = { - .deviceId = 0, - .sensorType = sensorId, - .sensorId = 0, - .location = 0 - }; - int32_t ret = g_sensorInterface->SetMode(deviceSensorInfo, mode); + int32_t ret = g_sensorInterface->SetMode({sensorDesc.deviceId, sensorDesc.sensorType, + sensorDesc.sensorId, sensorDesc.location}, mode); if (ret != 0) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "HDF_SERVICE_EXCEPTION", @@ -239,11 +230,47 @@ int32_t HdiConnection::DestroyHdiConnection() SEN_HILOGE("UnregisterAsync is failed"); return ret; } + ret = g_sensorInterface->UnRegSensorPlugCallBack(g_plugCallback); + if (ret != 0) { +#ifdef HIVIEWDFX_HISYSEVENT_ENABLE + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "HDF_SERVICE_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "UnRegSensorPlugCallback", "ERROR_CODE", ret); +#endif // HIVIEWDFX_HISYSEVENT_ENABLE + SEN_HILOGE("UnRegSensorPlugCallback is failed"); + return ret; + } + g_plugCallback = nullptr; g_eventCallback = nullptr; UnregisterHdiDeathRecipient(); return ERR_OK; } +int32_t HdiConnection::RegSensorPlugCallback(DevicePlugCallback cb) +{ + CALL_LOG_ENTER; + CHKPR(cb, ERR_NO_INIT); + CHKPR(g_sensorInterface, ERR_NO_INIT); + reportPlugDataCb_ = cb; + int32_t ret = g_sensorInterface->RegSensorPlugCallBack(g_plugCallback); + if (ret != 0) { +#ifdef HIVIEWDFX_HISYSEVENT_ENABLE + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "HDF_SERVICE_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "RegSensorPlugCallback", "ERROR_CODE", ret); +#endif // HIVIEWDFX_HISYSEVENT_ENABLE + SEN_HILOGE("RegSensorPlugCallback is failed"); + return ret; + } + return ERR_OK; +} + +DevicePlugCallback HdiConnection::GetSensorPlugCb() +{ + if (reportPlugDataCb_ == nullptr) { + SEN_HILOGE("reportPlugDataCb_ cannot be null"); + } + return reportPlugDataCb_; +} + ReportDataCb HdiConnection::GetReportDataCb() { if (reportDataCb_ == nullptr) { @@ -260,43 +287,48 @@ sptr HdiConnection::GetReportDataCallback() return reportDataCallback_; } -void HdiConnection::UpdateSensorBasicInfo(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) +void HdiConnection::UpdateSensorBasicInfo(const SensorDescription &sensorDesc, int64_t samplingPeriodNs, + int64_t maxReportDelayNs) { std::lock_guard sensorInfoLock(g_sensorBasicInfoMutex); SensorBasicInfo sensorBasicInfo; sensorBasicInfo.SetSamplingPeriodNs(samplingPeriodNs); sensorBasicInfo.SetMaxReportDelayNs(maxReportDelayNs); - auto it = g_sensorBasicInfoMap.find(sensorId); + auto it = g_sensorBasicInfoMap.find(sensorDesc); if (it != g_sensorBasicInfoMap.end()) { - if (g_sensorBasicInfoMap[sensorId].GetSensorState()) { + if (g_sensorBasicInfoMap[sensorDesc].GetSensorState()) { sensorBasicInfo.SetSensorState(true); } } - g_sensorBasicInfoMap[sensorId] = sensorBasicInfo; + g_sensorBasicInfoMap[sensorDesc] = sensorBasicInfo; } -void HdiConnection::SetSensorBasicInfoState(int32_t sensorId, bool state) +void HdiConnection::SetSensorBasicInfoState(const SensorDescription &sensorDesc, bool state) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); + SEN_HILOGI("In, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); std::lock_guard sensorInfoLock(g_sensorBasicInfoMutex); - auto it = g_sensorBasicInfoMap.find(sensorId); + auto it = g_sensorBasicInfoMap.find(sensorDesc); if (it == g_sensorBasicInfoMap.end()) { SEN_HILOGW("Should set batch first"); return; } - g_sensorBasicInfoMap[sensorId].SetSensorState(state); - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + g_sensorBasicInfoMap[sensorDesc].SetSensorState(state); + SEN_HILOGI("Done, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); } -void HdiConnection::DeleteSensorBasicInfoState(int32_t sensorId) +void HdiConnection::DeleteSensorBasicInfoState(const SensorDescription &sensorDesc) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); + SEN_HILOGI("In, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); std::lock_guard sensorInfoLock(g_sensorBasicInfoMutex); - auto it = g_sensorBasicInfoMap.find(sensorId); + auto it = g_sensorBasicInfoMap.find(sensorDesc); if (it != g_sensorBasicInfoMap.end()) { - g_sensorBasicInfoMap.erase(sensorId); + g_sensorBasicInfoMap.erase(sensorDesc); } - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + SEN_HILOGI("Done,deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); } void HdiConnection::RegisterHdiDeathRecipient() @@ -342,6 +374,11 @@ void HdiConnection::Reconnect() SEN_HILOGE("Register callback fail"); return; } + ret = g_sensorInterface->RegSensorPlugCallBack(g_plugCallback); + if (ret != 0) { + SEN_HILOGE("Register plug callback fail"); + return; + } std::vector sensorList; ret = GetSensorList(sensorList); if (ret != 0) { @@ -350,28 +387,69 @@ void HdiConnection::Reconnect() } std::lock_guard sensorInfoLock(g_sensorBasicInfoMutex); for (const auto &sensorInfo: g_sensorBasicInfoMap) { - int32_t sensorTypeId = sensorInfo.first; SensorBasicInfo info = sensorInfo.second; if (info.GetSensorState() != true) { - SEN_HILOGE("sensorTypeId:%{public}d don't need enable sensor", sensorTypeId); + SEN_HILOGE("deviceId:%{public}d, sensortype:%{public}d, sensorId:%{public}d don't need enable sensor", + sensorInfo.first.deviceId, sensorInfo.first.sensorType, sensorInfo.first.sensorId); continue; } - DeviceSensorInfo deviceSensorInfo = { - .deviceId = 0, - .sensorType = sensorTypeId, - .sensorId = 0, - .location = 0 - }; - ret = g_sensorInterface->SetBatch(deviceSensorInfo, info.GetSamplingPeriodNs(), info.GetMaxReportDelayNs()); + ret = g_sensorInterface->SetBatch({sensorInfo.first.deviceId, sensorInfo.first.sensorType, + sensorInfo.first.sensorId, sensorInfo.first.location}, + info.GetSamplingPeriodNs(), info.GetMaxReportDelayNs()); if (ret != 0) { - SEN_HILOGE("sensorTypeId:%{public}d set batch fail, error:%{public}d", sensorTypeId, ret); + SEN_HILOGE("deviceId:%{public}d, sensortype:%{public}d, sensorId:%{public}d set batch fail, err:%{public}d", + sensorInfo.first.deviceId, sensorInfo.first.sensorType, sensorInfo.first.sensorId, ret); continue; } - ret = g_sensorInterface->Enable(deviceSensorInfo); + ret = g_sensorInterface->Enable({sensorInfo.first.deviceId, sensorInfo.first.sensorType, + sensorInfo.first.sensorId, sensorInfo.first.location}); if (ret != 0) { - SEN_HILOGE("Enable sensor fail, sensorTypeId:%{public}d, error:%{public}d", sensorTypeId, ret); + SEN_HILOGE("Enable fail, deviceId:%{public}d, sensortype:%{public}d, sensorId:%{public}d, err:%{public}d", + sensorInfo.first.deviceId, sensorInfo.first.sensorType, sensorInfo.first.sensorId, ret); + } + } +} + +int32_t HdiConnection::GetSensorListByDevice(int32_t deviceId, std::vector &singleDevSensors) +{ + CALL_LOG_ENTER; + CHKPR(g_sensorInterface, ERR_NO_INIT); + std::vector sensorInfos; + int32_t ret = g_sensorInterface->GetDeviceSensorInfo(deviceId, sensorInfos); + if (ret != 0) { +#ifdef HIVIEWDFX_HISYSEVENT_ENABLE + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "HDF_SERVICE_EXCEPTION", + HiSysEvent::EventType::FAULT, "PKG_NAME", "GetSensorListByDevice", "ERROR_CODE", ret); +#endif // HIVIEWDFX_HISYSEVENT_ENABLE + SEN_HILOGE("Get sensor list by device failed"); + return ret; + } + size_t count = sensorInfos.size(); + if (count > MAX_SENSOR_COUNT) { + SEN_HILOGD("SensorInfos size:%{public}zu", count); + count = MAX_SENSOR_COUNT; + } + for (size_t i = 0; i < count; i++) { + Sensor sensor; + sensor.SetDeviceId(sensorInfos[i].deviceSensorInfo.deviceId); + sensor.SetSensorId(sensorInfos[i].deviceSensorInfo.sensorId); + sensor.SetSensorTypeId(sensorInfos[i].deviceSensorInfo.sensorType); + sensor.SetLocation(sensorInfos[i].deviceSensorInfo.location); + sensor.SetFirmwareVersion(sensorInfos[i].firmwareVersion); + sensor.SetHardwareVersion(sensorInfos[i].hardwareVersion); + sensor.SetMaxRange(sensorInfos[i].maxRange); + sensor.SetSensorName(sensorInfos[i].sensorName); + sensor.SetVendorName(sensorInfos[i].vendorName); + sensor.SetResolution(sensorInfos[i].accuracy); + sensor.SetPower(sensorInfos[i].power); + sensor.SetMinSamplePeriodNs(sensorInfos[i].minDelay); + sensor.SetMaxSamplePeriodNs(sensorInfos[i].maxDelay); + if (sensorInfos[i].deviceSensorInfo.sensorType == SENSOR_TYPE_ID_HEADPOSTURE) { + sensor.SetFifoMaxEventCount(HEADPOSTURE_FIFO_COUNT); } + singleDevSensors.push_back(sensor); } + return ERR_OK; } } // namespace Sensors } // namespace OHOS diff --git a/services/hdi_connection/adapter/src/sensor_event_callback.cpp b/services/hdi_connection/adapter/src/sensor_event_callback.cpp index cc2c9a3cbc29eae0c611fa9596772edbda2f4291..3951ff4a69bccb5b521d64e06d9879c2d845f721 100644 --- a/services/hdi_connection/adapter/src/sensor_event_callback.cpp +++ b/services/hdi_connection/adapter/src/sensor_event_callback.cpp @@ -39,6 +39,19 @@ const std::set g_sensorTypeTrigger = { }; } // namespace +void CreatSensorData(SensorData &sensorData, const HdfSensorEvents &event) +{ + sensorData.sensorTypeId = event.deviceSensorInfo.sensorType; + sensorData.version = event.version; + sensorData.timestamp = event.timestamp; + sensorData.option = event.option; + sensorData.mode = event.mode; + sensorData.dataLen = event.dataLen; + sensorData.deviceId = event.deviceSensorInfo.deviceId; + sensorData.sensorId = event.deviceSensorInfo.sensorId; + sensorData.location = event.deviceSensorInfo.location; +} + int32_t SensorEventCallback::OnDataEvent(const HdfSensorEvents &event) { return ERR_OK; @@ -56,14 +69,8 @@ int32_t SensorEventCallback::OnDataEventAsync(const std::vector SEN_HILOGI("Data is empty"); return ERR_INVALID_VALUE; } - SensorData sensorData = { - .sensorTypeId = event.deviceSensorInfo.sensorType, - .version = event.version, - .timestamp = event.timestamp, - .option = event.option, - .mode = event.mode, - .dataLen = event.dataLen - }; + SensorData sensorData; + CreatSensorData(sensorData, event); if (g_sensorTypeTrigger.find(sensorData.sensorTypeId) != g_sensorTypeTrigger.end()) { sensorData.mode = SENSOR_ON_CHANGE; } diff --git a/services/hdi_connection/adapter/src/sensor_plug_callback.cpp b/services/hdi_connection/adapter/src/sensor_plug_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9e2ce2028e8437888b5690748c53ac8fef028938 --- /dev/null +++ b/services/hdi_connection/adapter/src/sensor_plug_callback.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "sensor_plug_callback.h" + +#include "hdi_connection.h" +#include "print_sensor_data.h" +#include "sensor_errors.h" + +#undef LOG_TAG +#define LOG_TAG "HdiConnection" + +namespace OHOS { +namespace Sensors { +using namespace OHOS::HiviewDFX; +namespace { +std::unique_ptr HdiConnection_ = std::make_unique(); +} // namespace + +int32_t SensorPlugCallback::OnSensorPlugEvent(const SensorPlugInfo &plugEvent) +{ + DevicePlugCallback reportPlugDataCb_ = HdiConnection_->GetSensorPlugCb(); + CHKPR(reportPlugDataCb_, ERR_NO_INIT); + reportPlugDataCb_(plugEvent); + return ERR_OK; +} +} // namespace Sensors +} // namespace OHOS \ No newline at end of file diff --git a/services/hdi_connection/hardware/include/hdi_service_impl.h b/services/hdi_connection/hardware/include/hdi_service_impl.h index bb0b3918755300d8ab039994f5997d55b7dda17d..406fdbac00b8288898895223d33c35ddd96e8a43 100644 --- a/services/hdi_connection/hardware/include/hdi_service_impl.h +++ b/services/hdi_connection/hardware/include/hdi_service_impl.h @@ -19,6 +19,7 @@ #include #include "sensor_agent_type.h" +#include "sensor.h" #include "singleton.h" namespace OHOS { @@ -28,10 +29,11 @@ public: HdiServiceImpl() = default; virtual ~HdiServiceImpl() {} int32_t GetSensorList(std::vector &sensorList); - int32_t EnableSensor(int32_t sensorId); - int32_t DisableSensor(int32_t sensorId); - int32_t SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval); - int32_t SetMode(int32_t sensorId, int32_t mode); + int32_t GetSensorListByDevice(int32_t deviceId, std::vector &singleDevSensors); + int32_t EnableSensor(const SensorDescription &sensorDesc); + int32_t DisableSensor(const SensorDescription &sensorDesc); + int32_t SetBatch(const SensorDescription &sensorDesc, int64_t samplingInterval, int64_t reportInterval); + int32_t SetMode(const SensorDescription &sensorDesc, int32_t mode); int32_t Register(RecordSensorCallback cb); int32_t Unregister(); diff --git a/services/hdi_connection/hardware/src/hdi_service_impl.cpp b/services/hdi_connection/hardware/src/hdi_service_impl.cpp index bf1c15e9f2605ab011c6b1308b94df6df63f55e1..e715a98c2162f19f7f9ecc287f4e621236c2a919 100644 --- a/services/hdi_connection/hardware/src/hdi_service_impl.cpp +++ b/services/hdi_connection/hardware/src/hdi_service_impl.cpp @@ -30,9 +30,12 @@ namespace { constexpr int64_t SAMPLING_INTERVAL_NS = 200000000; constexpr float TARGET_SUM = 9.8F * 9.8F; constexpr float MAX_RANGE = 9999.0F; +constexpr int32_t DEFAULT_DEVICE_ID = -1; +constexpr int32_t DEFAULT_SENSOR_ID = 0; +constexpr int32_t IS_LOCAL_DEVICE = 1; const std::string SENSOR_PRODUCE_THREAD_NAME = "OS_SenMock"; std::vector g_sensorInfos = { - {"sensor_test", "default", "1.0.0", "1.0.0", 1, 1, 9999.0, 0.000001, 23.0, 100000000, 1000000000}, + {"sensor_test", "default", "1.0.0", "1.0.0", 1, 0, 9999.0, 0.000001, 23.0, 100000000, 1000000000, -1, 1}, }; std::vector g_supportSensors = { SENSOR_TYPE_ID_ACCELEROMETER, @@ -49,27 +52,42 @@ float g_proximityData[1]; SensorEvent g_accEvent = { .sensorTypeId = SENSOR_TYPE_ID_ACCELEROMETER, .option = 3, - .dataLen = 12 + .dataLen = 12, + .deviceId = DEFAULT_DEVICE_ID, + .sensorId = DEFAULT_SENSOR_ID, + .location = IS_LOCAL_DEVICE }; SensorEvent g_colorEvent = { .sensorTypeId = SENSOR_TYPE_ID_COLOR, .option = 3, - .dataLen = 8 + .dataLen = 8, + .deviceId = DEFAULT_DEVICE_ID, + .sensorId = DEFAULT_SENSOR_ID, + .location = IS_LOCAL_DEVICE }; SensorEvent g_sarEvent = { .sensorTypeId = SENSOR_TYPE_ID_SAR, .option = 3, - .dataLen = 4 + .dataLen = 4, + .deviceId = DEFAULT_DEVICE_ID, + .sensorId = DEFAULT_SENSOR_ID, + .location = IS_LOCAL_DEVICE }; SensorEvent g_headPostureEvent = { .sensorTypeId = SENSOR_TYPE_ID_HEADPOSTURE, .option = 3, - .dataLen = 20 + .dataLen = 20, + .deviceId = DEFAULT_DEVICE_ID, + .sensorId = DEFAULT_SENSOR_ID, + .location = IS_LOCAL_DEVICE }; SensorEvent g_proximityEvent = { .sensorTypeId = SENSOR_TYPE_ID_PROXIMITY1, .option = 3, - .dataLen = 4 + .dataLen = 4, + .deviceId = DEFAULT_DEVICE_ID, + .sensorId = DEFAULT_SENSOR_ID, + .location = IS_LOCAL_DEVICE }; } // namespace std::vector HdiServiceImpl::enableSensors_; @@ -80,8 +98,8 @@ std::atomic_bool HdiServiceImpl::isStop_ = false; void HdiServiceImpl::GenerateEvent() { - for (const auto &sensorId : enableSensors_) { - switch (sensorId) { + for (const auto &sensorType : enableSensors_) { + switch (sensorType) { case SENSOR_TYPE_ID_ACCELEROMETER: GenerateAccelerometerEvent(); break; @@ -98,7 +116,7 @@ void HdiServiceImpl::GenerateEvent() GenerateProximityEvent(); break; default: - SEN_HILOGW("Unknown sensorId:%{public}d", sensorId); + SEN_HILOGW("Unknown sensorType:%{public}d", sensorType); break; } } @@ -188,6 +206,16 @@ int32_t HdiServiceImpl::GetSensorList(std::vector &sensorList) return ERR_OK; } +int32_t HdiServiceImpl::GetSensorListByDevice(int32_t deviceId, std::vector &singleDevSensors) +{ + CALL_LOG_ENTER; + singleDevSensors.assign(g_sensorInfos.begin(), g_sensorInfos.end()); + for (auto& sensor : singleDevSensors) { + sensor.deviceId = deviceId; + } + return ERR_OK; +} + void HdiServiceImpl::DataReportThread() { CALL_LOG_ENTER; @@ -200,8 +228,8 @@ void HdiServiceImpl::DataReportThread() SEN_HILOGW("RecordSensorCallback is null"); continue; } - for (const auto &sensorId : enableSensors_) { - switch (sensorId) { + for (const auto &sensorType : enableSensors_) { + switch (sensorType) { case SENSOR_TYPE_ID_ACCELEROMETER: it(&g_accEvent); break; @@ -218,7 +246,7 @@ void HdiServiceImpl::DataReportThread() it(&g_proximityEvent); break; default: - SEN_HILOGW("Unknown sensorId:%{public}d", sensorId); + SEN_HILOGW("Unknown sensorType:%{public}d", sensorType); break; } } @@ -231,18 +259,18 @@ void HdiServiceImpl::DataReportThread() return; } -int32_t HdiServiceImpl::EnableSensor(int32_t sensorId) +int32_t HdiServiceImpl::EnableSensor(const SensorDescription &sensorDesc) { CALL_LOG_ENTER; - if (std::find(g_supportSensors.begin(), g_supportSensors.end(), sensorId) == g_supportSensors.end()) { - SEN_HILOGE("Not support enable sensorId:%{public}d", sensorId); + if (std::find(g_supportSensors.begin(), g_supportSensors.end(), sensorDesc.sensorType) == g_supportSensors.end()) { + SEN_HILOGE("Not support enable sensorType:%{public}d", sensorDesc.sensorType); return ERR_NO_INIT; } - if (std::find(enableSensors_.begin(), enableSensors_.end(), sensorId) != enableSensors_.end()) { - SEN_HILOGI("sensorId:%{public}d has been enabled", sensorId); + if (std::find(enableSensors_.begin(), enableSensors_.end(), sensorDesc.sensorType) != enableSensors_.end()) { + SEN_HILOGI("sensorType:%{public}d has been enabled", sensorDesc.sensorType); return ERR_OK; } - enableSensors_.push_back(sensorId); + enableSensors_.push_back(sensorDesc.sensorType); if (!dataReportThread_.joinable() || isStop_) { if (dataReportThread_.joinable()) { dataReportThread_.join(); @@ -254,20 +282,21 @@ int32_t HdiServiceImpl::EnableSensor(int32_t sensorId) return ERR_OK; }; -int32_t HdiServiceImpl::DisableSensor(int32_t sensorId) +int32_t HdiServiceImpl::DisableSensor(const SensorDescription &sensorDesc) { CALL_LOG_ENTER; - if (std::find(g_supportSensors.begin(), g_supportSensors.end(), sensorId) == g_supportSensors.end()) { - SEN_HILOGE("Not support disable sensorId:%{public}d", sensorId); + if (std::find(g_supportSensors.begin(), g_supportSensors.end(), sensorDesc.sensorType) == g_supportSensors.end()) { + SEN_HILOGE("Not support disable deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return ERR_NO_INIT; } - if (std::find(enableSensors_.begin(), enableSensors_.end(), sensorId) == enableSensors_.end()) { - SEN_HILOGE("sensorId:%{public}d should be enable first", sensorId); + if (std::find(enableSensors_.begin(), enableSensors_.end(), sensorDesc.sensorType) == enableSensors_.end()) { + SEN_HILOGE("sensorType:%{public}d should be enable first", sensorDesc.sensorType); return ERR_NO_INIT; } std::vector::iterator iter; for (iter = enableSensors_.begin(); iter != enableSensors_.end();) { - if (*iter == sensorId) { + if (*iter == sensorDesc.sensorType) { iter = enableSensors_.erase(iter); break; } else { @@ -280,7 +309,7 @@ int32_t HdiServiceImpl::DisableSensor(int32_t sensorId) return ERR_OK; } -int32_t HdiServiceImpl::SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) +int32_t HdiServiceImpl::SetBatch(const SensorDescription &sensorDesc, int64_t samplingInterval, int64_t reportInterval) { CALL_LOG_ENTER; if (samplingInterval < 0 || reportInterval < 0) { @@ -292,7 +321,7 @@ int32_t HdiServiceImpl::SetBatch(int32_t sensorId, int64_t samplingInterval, int return ERR_OK; } -int32_t HdiServiceImpl::SetMode(int32_t sensorId, int32_t mode) +int32_t HdiServiceImpl::SetMode(const SensorDescription &sensorDesc, int32_t mode) { return ERR_OK; } diff --git a/services/hdi_connection/interface/include/i_sensor_hdi_connection.h b/services/hdi_connection/interface/include/i_sensor_hdi_connection.h index 5997a9b65500d4df04e5a3bf261b4448ece0e078..2a45ac6e91728a561710708e26dbb52c40dfd667 100644 --- a/services/hdi_connection/interface/include/i_sensor_hdi_connection.h +++ b/services/hdi_connection/interface/include/i_sensor_hdi_connection.h @@ -19,21 +19,28 @@ #include #include "report_data_callback.h" #include "sensor.h" +#include "sensor_agent_type.h" +#include "v3_0/sensor_types.h" namespace OHOS { namespace Sensors { +using OHOS::HDI::Sensor::V3_0::SensorPlugInfo; +using DevicePlugCallback = std::function; class ISensorHdiConnection { public: ISensorHdiConnection() = default; virtual ~ISensorHdiConnection() = default; virtual int32_t ConnectHdi() = 0; virtual int32_t GetSensorList(std::vector &sensorList) = 0; - virtual int32_t EnableSensor(int32_t sensorId) = 0; - virtual int32_t DisableSensor(int32_t sensorId) = 0; - virtual int32_t SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) = 0; - virtual int32_t SetMode(int32_t sensorId, int32_t mode) = 0; + virtual int32_t GetSensorListByDevice(int32_t deviceId, std::vector &singleDevSensors) = 0; + virtual int32_t EnableSensor(const SensorDescription &sensorDesc) = 0; + virtual int32_t DisableSensor(const SensorDescription &sensorDesc) = 0; + virtual int32_t SetBatch(const SensorDescription &sensorDesc, int64_t samplingInterval, int64_t reportInterval) = 0; + virtual int32_t SetMode(const SensorDescription &sensorDesc, int32_t mode) = 0; virtual int32_t RegisterDataReport(ReportDataCb cb, sptr reportDataCallback) = 0; virtual int32_t DestroyHdiConnection() = 0; + virtual int32_t RegSensorPlugCallback(DevicePlugCallback cb) = 0; + virtual DevicePlugCallback GetSensorPlugCb() = 0; static std::mutex dataMutex_; static std::condition_variable dataCondition_; static std::atomic dataReady_; diff --git a/services/hdi_connection/interface/include/sensor_hdi_connection.h b/services/hdi_connection/interface/include/sensor_hdi_connection.h index df45cfd38ac89c8018a24cdd065258c9b499f1ad..881208df354e456153b97f77c63703c706af78fa 100644 --- a/services/hdi_connection/interface/include/sensor_hdi_connection.h +++ b/services/hdi_connection/interface/include/sensor_hdi_connection.h @@ -29,12 +29,16 @@ public: virtual ~SensorHdiConnection() {} int32_t ConnectHdi() override; int32_t GetSensorList(std::vector &sensorList) override; - int32_t EnableSensor(int32_t sensorId) override; - int32_t DisableSensor(int32_t sensorId) override; - int32_t SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) override; - int32_t SetMode(int32_t sensorId, int32_t mode) override; + int32_t GetSensorListByDevice(int32_t deviceId, std::vector &singleDevSensors) override; + int32_t EnableSensor(const SensorDescription &sensorDesc) override; + int32_t DisableSensor(const SensorDescription &sensorDesc) override; + int32_t SetBatch(const SensorDescription &sensorDesc, int64_t samplingInterval, int64_t reportInterval) override; + int32_t SetMode(const SensorDescription &sensorDesc, int32_t mode) override; int32_t RegisterDataReport(ReportDataCb cb, sptr reportDataCallback) override; int32_t DestroyHdiConnection() override; + int32_t RegSensorPlugCallback(DevicePlugCallback cb) override; + DevicePlugCallback GetSensorPlugCb() override; + bool PlugEraseSensorData(SensorPlugInfo info); private: DISALLOW_COPY_AND_MOVE(SensorHdiConnection); @@ -47,7 +51,7 @@ private: int32_t ConnectHdiService(); int32_t ConnectCompatibleHdi(); bool FindAllInSensorSet(const std::unordered_set &sensors); - bool FindOneInMockSet(int32_t sensorId); + bool FindOneInMockSet(int32_t sensorType); Sensor GenerateColorSensor(); Sensor GenerateSarSensor(); Sensor GenerateHeadPostureSensor(); diff --git a/services/hdi_connection/interface/src/sensor_hdi_connection.cpp b/services/hdi_connection/interface/src/sensor_hdi_connection.cpp index 6dff811f59323f8d552ad69b1bd7842bd812d3a5..6d98e4666df7ef2f825e1ea4fc28f333f1b6f281 100644 --- a/services/hdi_connection/interface/src/sensor_hdi_connection.cpp +++ b/services/hdi_connection/interface/src/sensor_hdi_connection.cpp @@ -47,6 +47,10 @@ std::unordered_set g_supportMockSensors = { SENSOR_TYPE_ID_HEADPOSTURE, SENSOR_TYPE_ID_PROXIMITY1 }; +constexpr int32_t IS_LOCAL_DEVICE = 1; +constexpr int32_t DEFAULT_SENSORID = 0; +constexpr int32_t DEFAULT_LOCATION = 1; +static int32_t localDeviceId_ = -1; #endif // BUILD_VARIANT_ENG constexpr int32_t HDI_DISABLE_SENSOR_TIMEOUT = -23; } // namespace @@ -117,26 +121,28 @@ bool SensorHdiConnection::FindAllInSensorSet(const std::unordered_set & { int32_t count = 0; std::lock_guard sensorLock(sensorMutex_); - for (const auto &sensorId : sensors) { - if (sensorSet_.find(sensorId) == sensorSet_.end()) { - mockSet_.insert(sensorId); + for (const auto &sensorType : sensors) { + if (sensorSet_.find(sensorType) == sensorSet_.end()) { + mockSet_.insert(sensorType); count++; } } return count == 0 ? true : false; } -bool SensorHdiConnection::FindOneInMockSet(int32_t sensorId) +bool SensorHdiConnection::FindOneInMockSet(int32_t sensorType) { std::lock_guard sensorLock(sensorMutex_); - return mockSet_.find(sensorId) != mockSet_.end(); + return mockSet_.find(sensorType) != mockSet_.end(); } Sensor SensorHdiConnection::GenerateColorSensor() { Sensor sensorColor; - sensorColor.SetSensorId(SENSOR_TYPE_ID_COLOR); + sensorColor.SetSensorId(DEFAULT_SENSORID); sensorColor.SetSensorTypeId(SENSOR_TYPE_ID_COLOR); + sensorColor.SetDeviceId(localDeviceId_); + sensorColor.SetLocation(DEFAULT_LOCATION); sensorColor.SetFirmwareVersion(VERSION_NAME); sensorColor.SetHardwareVersion(VERSION_NAME); sensorColor.SetMaxRange(MAX_RANGE); @@ -152,8 +158,10 @@ Sensor SensorHdiConnection::GenerateColorSensor() Sensor SensorHdiConnection::GenerateSarSensor() { Sensor sensorSar; - sensorSar.SetSensorId(SENSOR_TYPE_ID_SAR); + sensorSar.SetSensorId(DEFAULT_SENSORID); sensorSar.SetSensorTypeId(SENSOR_TYPE_ID_SAR); + sensorSar.SetDeviceId(localDeviceId_); + sensorSar.SetLocation(DEFAULT_LOCATION); sensorSar.SetFirmwareVersion(VERSION_NAME); sensorSar.SetHardwareVersion(VERSION_NAME); sensorSar.SetMaxRange(MAX_RANGE); @@ -169,8 +177,10 @@ Sensor SensorHdiConnection::GenerateSarSensor() Sensor SensorHdiConnection::GenerateHeadPostureSensor() { Sensor sensorHeadPosture; - sensorHeadPosture.SetSensorId(SENSOR_TYPE_ID_HEADPOSTURE); + sensorHeadPosture.SetSensorId(DEFAULT_SENSORID); sensorHeadPosture.SetSensorTypeId(SENSOR_TYPE_ID_HEADPOSTURE); + sensorHeadPosture.SetDeviceId(localDeviceId_); + sensorHeadPosture.SetLocation(DEFAULT_LOCATION); sensorHeadPosture.SetFirmwareVersion(VERSION_NAME); sensorHeadPosture.SetHardwareVersion(VERSION_NAME); sensorHeadPosture.SetMaxRange(MAX_RANGE); @@ -186,8 +196,10 @@ Sensor SensorHdiConnection::GenerateHeadPostureSensor() Sensor SensorHdiConnection::GenerateProximitySensor() { Sensor sensorProximity; - sensorProximity.SetSensorId(SENSOR_TYPE_ID_PROXIMITY1); + sensorProximity.SetSensorId(DEFAULT_SENSORID); sensorProximity.SetSensorTypeId(SENSOR_TYPE_ID_PROXIMITY1); + sensorProximity.SetDeviceId(localDeviceId_); + sensorProximity.SetLocation(DEFAULT_LOCATION); sensorProximity.SetFirmwareVersion(VERSION_NAME); sensorProximity.SetHardwareVersion(VERSION_NAME); sensorProximity.SetMaxRange(MAX_RANGE); @@ -215,8 +227,13 @@ int32_t SensorHdiConnection::GetSensorList(std::vector &sensorList) if (!hdiConnectionStatus_) { return ERR_OK; } - for (const auto &sensorId : mockSet_) { - switch (sensorId) { + for (const auto& sensor : sensorList) { + if (sensor.GetLocation() == IS_LOCAL_DEVICE) { + localDeviceId_ = sensor.GetDeviceId(); + } + } + for (const auto &sensorType : mockSet_) { + switch (sensorType) { case SENSOR_TYPE_ID_COLOR: sensorList.push_back(GenerateColorSensor()); break; @@ -237,65 +254,71 @@ int32_t SensorHdiConnection::GetSensorList(std::vector &sensorList) return ERR_OK; } -int32_t SensorHdiConnection::EnableSensor(int32_t sensorId) +int32_t SensorHdiConnection::EnableSensor(const SensorDescription &sensorDesc) { #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "EnableSensor"); #endif // HIVIEWDFX_HITRACE_ENABLE int32_t ret = ENABLE_SENSOR_ERR; #ifdef BUILD_VARIANT_ENG - if (FindOneInMockSet(sensorId)) { + if (FindOneInMockSet(sensorDesc.sensorType)) { CHKPR(iSensorCompatibleHdiConnection_, ENABLE_SENSOR_ERR); - ret = iSensorCompatibleHdiConnection_->EnableSensor(sensorId); + ret = iSensorCompatibleHdiConnection_->EnableSensor(sensorDesc); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE if (ret != ERR_OK) { - SEN_HILOGE("Enable sensor failed in compatible, sensorId:%{public}d", sensorId); + SEN_HILOGE( + "Enable failed in compatible, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return ENABLE_SENSOR_ERR; } return ret; } #endif // BUILD_VARIANT_ENG CHKPR(iSensorHdiConnection_, ENABLE_SENSOR_ERR); - ret = iSensorHdiConnection_->EnableSensor(sensorId); + ret = iSensorHdiConnection_->EnableSensor(sensorDesc); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE if (ret != ERR_OK) { - SEN_HILOGI("Enable sensor failed, sensorId:%{public}d", sensorId); + SEN_HILOGI("Enable failed, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return ENABLE_SENSOR_ERR; } return ret; }; -int32_t SensorHdiConnection::DisableSensor(int32_t sensorId) +int32_t SensorHdiConnection::DisableSensor(const SensorDescription &sensorDesc) { #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "DisableSensor"); #endif // HIVIEWDFX_HITRACE_ENABLE int32_t ret = DISABLE_SENSOR_ERR; #ifdef BUILD_VARIANT_ENG - if (FindOneInMockSet(sensorId)) { + if (FindOneInMockSet(sensorDesc.sensorType)) { CHKPR(iSensorCompatibleHdiConnection_, DISABLE_SENSOR_ERR); - ret = iSensorCompatibleHdiConnection_->DisableSensor(sensorId); + ret = iSensorCompatibleHdiConnection_->DisableSensor(sensorDesc); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE if (ret != ERR_OK) { - SEN_HILOGE("Disable sensor failed in compatible, sensorId:%{public}d", sensorId); + SEN_HILOGE( + "Disable failed in compatible, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return DISABLE_SENSOR_ERR; } return ret; } #endif // BUILD_VARIANT_ENG CHKPR(iSensorHdiConnection_, DISABLE_SENSOR_ERR); - ret = iSensorHdiConnection_->DisableSensor(sensorId); + ret = iSensorHdiConnection_->DisableSensor(sensorDesc); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE if ((ret != ERR_OK) && (ret != HDI_DISABLE_SENSOR_TIMEOUT)) { - SEN_HILOGI("Disable sensor failed, sensorId:%{public}d", sensorId); + SEN_HILOGI("Disable sensor failed, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return DISABLE_SENSOR_ERR; } if (ret == HDI_DISABLE_SENSOR_TIMEOUT) { @@ -304,65 +327,71 @@ int32_t SensorHdiConnection::DisableSensor(int32_t sensorId) return ERR_OK; } -int32_t SensorHdiConnection::SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) +int32_t SensorHdiConnection::SetBatch(const SensorDescription &sensorDesc, int64_t samplingInterval, + int64_t reportInterval) { #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "SetBatch"); #endif // HIVIEWDFX_HITRACE_ENABLE int32_t ret = SET_SENSOR_CONFIG_ERR; #ifdef BUILD_VARIANT_ENG - if (FindOneInMockSet(sensorId)) { + if (FindOneInMockSet(sensorDesc.sensorType)) { CHKPR(iSensorCompatibleHdiConnection_, SET_SENSOR_CONFIG_ERR); - ret = iSensorCompatibleHdiConnection_->SetBatch(sensorId, samplingInterval, reportInterval); + ret = iSensorCompatibleHdiConnection_->SetBatch(sensorDesc, samplingInterval, reportInterval); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE if (ret != ERR_OK) { - SEN_HILOGI("Set batch failed in compatible, sensorId:%{public}d", sensorId); + SEN_HILOGI( + "Set batch failed in compatible, deviceId:%{public}d, sensortype:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return SET_SENSOR_CONFIG_ERR; } return ret; } #endif // BUILD_VARIANT_ENG CHKPR(iSensorHdiConnection_, SET_SENSOR_CONFIG_ERR); - ret = iSensorHdiConnection_->SetBatch(sensorId, samplingInterval, reportInterval); + ret = iSensorHdiConnection_->SetBatch(sensorDesc, samplingInterval, reportInterval); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE if (ret != ERR_OK) { - SEN_HILOGI("Set batch failed, sensorId:%{public}d", sensorId); + SEN_HILOGI("Set batch failed, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return SET_SENSOR_CONFIG_ERR; } return ret; } -int32_t SensorHdiConnection::SetMode(int32_t sensorId, int32_t mode) +int32_t SensorHdiConnection::SetMode(const SensorDescription &sensorDesc, int32_t mode) { #ifdef HIVIEWDFX_HITRACE_ENABLE StartTrace(HITRACE_TAG_SENSORS, "SetMode"); #endif // HIVIEWDFX_HITRACE_ENABLE int32_t ret = SET_SENSOR_MODE_ERR; #ifdef BUILD_VARIANT_ENG - if (FindOneInMockSet(sensorId)) { + if (FindOneInMockSet(sensorDesc.sensorType)) { CHKPR(iSensorCompatibleHdiConnection_, SET_SENSOR_MODE_ERR); - ret = iSensorCompatibleHdiConnection_->SetMode(sensorId, mode); + ret = iSensorCompatibleHdiConnection_->SetMode(sensorDesc, mode); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE if (ret != ERR_OK) { - SEN_HILOGI("Set mode failed, sensorId:%{public}d", sensorId); + SEN_HILOGI("Set mode failed, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return SET_SENSOR_MODE_ERR; } return ret; } #endif // BUILD_VARIANT_ENG CHKPR(iSensorHdiConnection_, SET_SENSOR_MODE_ERR); - ret = iSensorHdiConnection_->SetMode(sensorId, mode); + ret = iSensorHdiConnection_->SetMode(sensorDesc, mode); #ifdef HIVIEWDFX_HITRACE_ENABLE FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE if (ret != ERR_OK) { - SEN_HILOGI("Set mode failed, sensorId:%{public}d", sensorId); + SEN_HILOGI("Set mode failed, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return SET_SENSOR_MODE_ERR; } return ret; @@ -413,5 +442,109 @@ int32_t SensorHdiConnection::DestroyHdiConnection() #endif // BUILD_VARIANT_ENG return ret; } + +int32_t SensorHdiConnection::GetSensorListByDevice(int32_t deviceId, std::vector &singleDevSensors) +{ + CALL_LOG_ENTER; + CHKPR(iSensorHdiConnection_, GET_SENSOR_LIST_ERR); + std::lock_guard sensorLock(sensorMutex_); + if (iSensorHdiConnection_->GetSensorListByDevice(deviceId, singleDevSensors) != ERR_OK) { + SEN_HILOGW("Get sensor list by device failed"); + } + for (const auto& newSensor : singleDevSensors) { + bool found = false; + for (const auto& oldSensor : sensorList_) { + if (oldSensor.GetDeviceId() == newSensor.GetDeviceId() && + oldSensor.GetSensorId() == newSensor.GetSensorId() && + oldSensor.GetSensorTypeId() == newSensor.GetSensorTypeId()) { + found = true; + break; + } + } + if (!found) { + SEN_HILOGD("Sensor not found in sensorList_"); + sensorList_.push_back(newSensor); + } + } +#ifdef BUILD_VARIANT_ENG + if (singleDevSensors[0].GetLocation() == IS_LOCAL_DEVICE) { + if (!hdiConnectionStatus_) { + return ERR_OK; + } + localDeviceId_ = singleDevSensors[0].GetDeviceId(); + for (const auto &sensorType : mockSet_) { + switch (sensorType) { + case SENSOR_TYPE_ID_COLOR: + singleDevSensors.push_back(GenerateColorSensor()); + break; + case SENSOR_TYPE_ID_SAR: + singleDevSensors.push_back(GenerateSarSensor()); + break; + case SENSOR_TYPE_ID_HEADPOSTURE: + singleDevSensors.push_back(GenerateHeadPostureSensor()); + break; + case SENSOR_TYPE_ID_PROXIMITY1: + singleDevSensors.push_back(GenerateProximitySensor()); + break; + default: + break; + } + } + } +#endif // BUILD_VARIANT_ENG + return ERR_OK; +} + +int32_t SensorHdiConnection::RegSensorPlugCallback(DevicePlugCallback cb) +{ +#ifdef HIVIEWDFX_HITRACE_ENABLE + StartTrace(HITRACE_TAG_SENSORS, "RegSensorPlugCallback"); +#endif // HIVIEWDFX_HITRACE_ENABLE + CHKPR(iSensorHdiConnection_, REGIST_CALLBACK_ERR); + int32_t ret = iSensorHdiConnection_->RegSensorPlugCallback(cb); + if (ret != ERR_OK) { + SEN_HILOGE("Registe sensor plug callback failed"); + return REGIST_CALLBACK_ERR; + } +#ifdef BUILD_VARIANT_ENG + if (iSensorCompatibleHdiConnection_ != nullptr) { + ret = iSensorCompatibleHdiConnection_->RegSensorPlugCallback(cb); + if (ret != ERR_OK) { + SEN_HILOGE("Registe sensor plug callback failed in compatible"); + return REGIST_CALLBACK_ERR; + } + } +#endif // BUILD_VARIANT_ENG +#ifdef HIVIEWDFX_HITRACE_ENABLE + FinishTrace(HITRACE_TAG_SENSORS); +#endif // HIVIEWDFX_HITRACE_ENABLE + return ret; +} + +DevicePlugCallback SensorHdiConnection::GetSensorPlugCb() +{ + return NULL; +} + +bool SensorHdiConnection::PlugEraseSensorData(SensorPlugInfo info) +{ + CALL_LOG_ENTER; + std::lock_guard sensorLock(sensorMutex_); + if (sensorList_.empty()) { + SEN_HILOGE("sensorList_ cannot be empty"); + return false; + } + auto it = std::find_if(sensorList_.begin(), sensorList_.end(), [&](const Sensor& sensor) { + return sensor.GetDeviceId() == info.deviceSensorInfo.deviceId && + sensor.GetSensorTypeId() == info.deviceSensorInfo.sensorType && + sensor.GetSensorId() == info.deviceSensorInfo.sensorId; + }); + if (it != sensorList_.end()) { + sensorList_.erase(it); + return true; + } + SEN_HILOGD("sensorList_ cannot find the sensor"); + return true; +} } // namespace Sensors } // namespace OHOS diff --git a/services/include/client_info.h b/services/include/client_info.h index 01c4e5b5c51f23b0d026fc5e27d9d845b9521f0e..d93d2f95e6626af3e8cb8fa2688d7fb26ef60978 100644 --- a/services/include/client_info.h +++ b/services/include/client_info.h @@ -26,6 +26,7 @@ #include "iremote_object.h" #include "app_thread_info.h" +#include "sensor_agent_type.h" #include "sensor_basic_data_channel.h" #include "sensor_basic_info.h" #include "sensor_channel_info.h" @@ -37,52 +38,55 @@ class ClientInfo : public Singleton { public: ClientInfo() = default; virtual ~ClientInfo() = default; - bool GetSensorState(int32_t sensorId); - SensorBasicInfo GetBestSensorInfo(int32_t sensorId); - bool OnlyCurPidSensorEnabled(int32_t sensorId, int32_t pid); - std::vector> GetSensorChannel(int32_t sensorId); + bool GetSensorState(const SensorDescription &sensorDesc); + SensorBasicInfo GetBestSensorInfo(const SensorDescription &sensorDesc); + bool OnlyCurPidSensorEnabled(const SensorDescription &sensorDesc, int32_t pid); + std::vector> GetSensorChannel(const SensorDescription &sensorDesc); std::vector> GetSensorChannelByUid(int32_t uid); sptr GetSensorChannelByPid(int32_t pid); - bool UpdateSensorInfo(int32_t sensorId, int32_t pid, const SensorBasicInfo &sensorInfo); - void RemoveSubscriber(int32_t sensorId, uint32_t pid); + bool UpdateSensorInfo(const SensorDescription &sensorDesc, int32_t pid, const SensorBasicInfo &sensorInfo); + void RemoveSubscriber(const SensorDescription &sensorDesc, uint32_t pid); bool UpdateSensorChannel(int32_t pid, const sptr &channel); bool UpdateAppThreadInfo(int32_t pid, int32_t uid, AccessTokenID callerToken); - void ClearSensorInfo(int32_t sensorId); - void ClearCurPidSensorInfo(int32_t sensorId, int32_t pid); + void ClearSensorInfo(const SensorDescription &sensorDesc); + void ClearCurPidSensorInfo(const SensorDescription &sensorDesc, int32_t pid); bool DestroySensorChannel(int32_t pid); void DestroyAppThreadInfo(int32_t pid); - SensorBasicInfo GetCurPidSensorInfo(int32_t sensorId, int32_t pid); - uint64_t ComputeBestPeriodCount(int32_t sensorId, sptr &channel); - uint64_t ComputeBestFifoCount(int32_t sensorId, sptr &channel); - int32_t GetStoreEvent(int32_t sensorId, SensorData &data); + SensorBasicInfo GetCurPidSensorInfo(const SensorDescription &sensorDesc, int32_t pid); + uint64_t ComputeBestPeriodCount(const SensorDescription &sensorDesc, sptr &channel); + uint64_t ComputeBestFifoCount(const SensorDescription &sensorDesc, sptr &channel); + int32_t GetStoreEvent(const SensorDescription &sensorDesc, SensorData &data); void StoreEvent(const SensorData &data); void ClearEvent(); AppThreadInfo GetAppInfoByChannel(const sptr &channel); bool SaveClientPid(const sptr &sensorClient, int32_t pid); int32_t FindClientPid(const sptr &sensorClient); void DestroyClientPid(const sptr &sensorClient); - std::vector GetSensorIdByPid(int32_t pid); + std::vector GetSensorIdByPid(int32_t pid); void GetSensorChannelInfo(std::vector &channelInfo); - void UpdateCmd(int32_t sensorId, int32_t uid, int32_t cmdType); + void UpdateCmd(int32_t sensorType, int32_t uid, int32_t cmdType); void DestroyCmd(int32_t uid); - void UpdateDataQueue(int32_t sensorId, SensorData &data); - std::unordered_map> GetDumpQueue(); - void ClearDataQueue(int32_t sensorId); + void UpdateDataQueue(int32_t sensorType, SensorData &data); + std::unordered_map> GetDumpQueue(); int32_t GetUidByPid(int32_t pid); + void ClearDataQueue(const SensorDescription &sensorDesc); AccessTokenID GetTokenIdByPid(int32_t pid); int32_t AddActiveInfoCBPid(int32_t pid); int32_t DelActiveInfoCBPid(int32_t pid); std::vector GetActiveInfoCBPid(); bool CallingService(int32_t pid); int32_t GetPidByTokenId(AccessTokenID tokenId); - void UpdatePermState(int32_t pid, int32_t sensorId, bool state); + void UpdatePermState(int32_t pid, int32_t sensorType, bool state); void ChangeSensorPerm(AccessTokenID tokenId, const std::string &permName, bool state); void SetDeviceStatus(uint32_t deviceStatus); uint32_t GetDeviceStatus(); + void SaveSensorClient(const sptr &sensorClient); + void DestroySensorClient(const sptr &sensorClient); + void SendMsgToClient(SensorPlugData info); private: DISALLOW_COPY_AND_MOVE(ClientInfo); - std::vector GetCmdList(int32_t sensorId, int32_t uid); + std::vector GetCmdList(int32_t sensorType, int32_t uid); std::mutex clientMutex_; std::mutex channelMutex_; std::mutex eventMutex_; @@ -90,17 +94,19 @@ private: std::mutex clientPidMutex_; std::mutex cmdMutex_; std::mutex dataQueueMutex_; - std::unordered_map> clientMap_; + std::mutex sensorClientMutex_; + std::unordered_map> clientMap_; std::unordered_map> channelMap_; - std::unordered_map storedEvent_; + std::unordered_map storedEvent_; std::unordered_map appThreadInfoMap_; std::map, int32_t> clientPidMap_; std::unordered_map>> cmdMap_; - std::unordered_map> dumpQueue_; + std::unordered_map> dumpQueue_; std::mutex activeInfoCBPidMutex_; std::unordered_set activeInfoCBPidSet_; static std::unordered_map> userGrantPermMap_; std::atomic deviceStatus_; + std::vector> sensorClients_; }; } // namespace Sensors } // namespace OHOS diff --git a/services/include/flush_info_record.h b/services/include/flush_info_record.h index 003e676ee26d4fbda81f90f40d0ccb449e5fbc63..7ed3ba77ceb1ca26cfbf65c2a0d03edfefec89bc 100644 --- a/services/include/flush_info_record.h +++ b/services/include/flush_info_record.h @@ -40,13 +40,13 @@ public: flushInfo_.clear(); } std::unordered_map> GetFlushInfo(); - void ClearFlushInfoItem(int32_t sensorId); - ErrCode SetFlushInfo(int32_t sensorId, const sptr &channel, bool isFirstFlush); + void ClearFlushInfoItem(int32_t sensorType); + ErrCode SetFlushInfo(int32_t sensorType, const sptr &channel, bool isFirstFlush); bool IsFlushChannelValid(const std::vector> &currChannelList, const sptr &flushChannel); int32_t GetFlushChannelIndex(const std::vector &flushInfoList, const sptr &channel); - ErrCode FlushProcess(const int32_t sensorId, const uint32_t flag, const int32_t pid, const bool isEnableFlush); + ErrCode FlushProcess(const int32_t sensorType, const uint32_t flag, const int32_t pid, const bool isEnableFlush); private: DISALLOW_COPY_AND_MOVE(FlushInfoRecord); diff --git a/services/include/sensor_data_processer.h b/services/include/sensor_data_processer.h index 25731815338257c7fb7061b74293640de17efaaa..f15d3b6b4136cd7f1b355890343118012ebe0a55 100755 --- a/services/include/sensor_data_processer.h +++ b/services/include/sensor_data_processer.h @@ -24,32 +24,34 @@ namespace OHOS { namespace Sensors { class SensorDataProcesser : public RefBase { public: - explicit SensorDataProcesser(const std::unordered_map &sensorMap); + explicit SensorDataProcesser(const std::unordered_map &sensorMap); virtual ~SensorDataProcesser(); int32_t ProcessEvents(sptr dataCallback); int32_t SendEvents(sptr &channel, SensorData &data); static int DataThread(sptr dataProcesser, sptr dataCallback); int32_t CacheSensorEvent(const SensorData &data, sptr &channel); + void UpdataSensorMap(const std::unordered_map &sensorMap); private: DISALLOW_COPY_AND_MOVE(SensorDataProcesser); void ReportData(sptr &channel, SensorData &data); - bool ReportNotContinuousData(std::unordered_map &cacheBuf, + bool ReportNotContinuousData(std::unordered_map &cacheBuf, sptr &channel, SensorData &data); - void SendNoneFifoCacheData(std::unordered_map &cacheBuf, + void SendNoneFifoCacheData(std::unordered_map &cacheBuf, sptr &channel, SensorData &data, uint64_t periodCount); - void SendFifoCacheData(std::unordered_map &cacheBuf, + void SendFifoCacheData(std::unordered_map &cacheBuf, sptr &channel, SensorData &data, uint64_t periodCount, uint64_t fifoCount); - void SendRawData(std::unordered_map &cacheBuf, sptr channel, + void SendRawData(std::unordered_map &cacheBuf, sptr channel, std::vector events); void EventFilter(CircularEventBuf &eventsBuf); + void UpdataFifoDataChannel(sptr &channel, std::vector> &dataCount); ClientInfo &clientInfo_ = ClientInfo::GetInstance(); FlushInfoRecord &flushInfo_ = FlushInfoRecord::GetInstance(); std::mutex dataCountMutex_; - std::unordered_map>> dataCountMap_; + std::unordered_map>> dataCountMap_; std::mutex sensorMutex_; - std::unordered_map sensorMap_; + std::unordered_map sensorMap_; }; } // namespace Sensors } // namespace OHOS diff --git a/services/include/sensor_dump.h b/services/include/sensor_dump.h index 62e29e741f84232aac6d14f1819f467a7e710dff..eba9939158fff04ed7b6290b585d8963b1e60793 100644 --- a/services/include/sensor_dump.h +++ b/services/include/sensor_dump.h @@ -37,8 +37,8 @@ public: private: DISALLOW_COPY_AND_MOVE(SensorDump); void DumpCurrentTime(int32_t fd); - int32_t GetDataDimension(int32_t sensorId); - std::string GetDataBySensorId(int32_t sensorId, SensorData &sensorData); + int32_t GetDataDimension(int32_t sensorType); + std::string GetDataBySensorId(int32_t sensorType, SensorData &sensorData); static std::unordered_map sensorMap_; void RunSensorDump(int32_t fd, int32_t optionIndex, const std::vector &args, char **argv); std::vector sensors_; diff --git a/services/include/sensor_manager.h b/services/include/sensor_manager.h index ab8370e9540947ef95d2ab7096037b9f4e00de7a..6e1b4c2039b9b708c1075cdd37183196dec07ac8 100644 --- a/services/include/sensor_manager.h +++ b/services/include/sensor_manager.h @@ -31,18 +31,20 @@ using namespace Security::AccessToken; class SensorManager : public Singleton { public: #ifdef HDF_DRIVERS_INTERFACE_SENSOR - void InitSensorMap(const std::unordered_map &sensorMap, sptr dataProcesser, - sptr dataCallback); - bool SetBestSensorParams(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); - bool ResetBestSensorParams(int32_t sensorId); + void InitSensorMap(const std::unordered_map &sensorMap, + sptr dataProcesser, sptr dataCallback); + bool SetBestSensorParams(const SensorDescription &sensorDesc, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + bool ResetBestSensorParams(const SensorDescription &sensorDesc); void StartDataReportThread(); #else - void InitSensorMap(const std::unordered_map &sensorMap); + void InitSensorMap(const std::unordered_map &sensorMap); #endif // HDF_DRIVERS_INTERFACE_SENSOR - bool SaveSubscriber(int32_t sensorId, uint32_t pid, int64_t samplingPeriodNs, int64_t maxReportDelayNs); - SensorBasicInfo GetSensorInfo(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); - bool IsOtherClientUsingSensor(int32_t sensorId, int32_t clientPid); - ErrCode AfterDisableSensor(int32_t sensorId); + bool SaveSubscriber(const SensorDescription &sensorDesc, uint32_t pid, int64_t samplingPeriodNs, + int64_t maxReportDelayNs); + SensorBasicInfo GetSensorInfo(const SensorDescription &sensorDesc, int64_t samplingPeriodNs, + int64_t maxReportDelayNs); + bool IsOtherClientUsingSensor(const SensorDescription &sensorDesc, int32_t clientPid); + ErrCode AfterDisableSensor(const SensorDescription &sensorDesc); void GetPackageName(AccessTokenID tokenId, std::string &packageName, bool isAccessTokenServiceActive = false); private: @@ -53,7 +55,7 @@ private: sptr reportDataCallback_ = nullptr; #endif // HDF_DRIVERS_INTERFACE_SENSOR ClientInfo &clientInfo_ = ClientInfo::GetInstance(); - std::unordered_map sensorMap_; + std::unordered_map sensorMap_; std::mutex sensorMapMutex_; }; } // namespace Sensors diff --git a/services/include/sensor_power_policy.h b/services/include/sensor_power_policy.h index b1dba0d6ef1a462bcd05d57c61ce4e2e2801826c..50820cdfc5707a2416ef65db9b02cc8ebbc8ff56 100644 --- a/services/include/sensor_power_policy.h +++ b/services/include/sensor_power_policy.h @@ -17,6 +17,7 @@ #define SENSOR_POWER_POLICY_H #include "active_info.h" +#include "sensor_agent_type.h" #include "sensor_manager.h" #include "stream_session.h" #ifdef HDF_DRIVERS_INTERFACE_SENSOR @@ -35,14 +36,15 @@ public: void DeleteDeathPidSensorInfo(int32_t pid); private: - bool CheckFreezingSensor(int32_t sensorId); - bool Suspend(int32_t pid, const std::vector &sensorIdList, - std::unordered_map &SensorInfoMap); - bool Resume(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); - ErrCode RestoreSensorInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + bool CheckFreezingSensor(int32_t sensorType); + bool Suspend(int32_t pid, const std::vector &sensorDescList, + std::unordered_map &SensorInfoMap); + bool Resume(int32_t pid, const SensorDescription &sensorDesc, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + ErrCode RestoreSensorInfo(int32_t pid, const SensorDescription &sensorDesc, int64_t samplingPeriodNs, + int64_t maxReportDelayNs); std::vector GetSuspendPidList(); std::mutex pidSensorInfoMutex_; - std::unordered_map> pidSensorInfoMap_; + std::unordered_map> pidSensorInfoMap_; }; } // namespace Sensors } // namespace OHOS diff --git a/services/include/sensor_service.h b/services/include/sensor_service.h index 39286c8a47d6d9531e05ed6ff2a61c076ed4e67d..693e020ff73c4a54eac53588300870532b6a2c9c 100644 --- a/services/include/sensor_service.h +++ b/services/include/sensor_service.h @@ -43,9 +43,11 @@ public: void OnStart() override; void OnStop() override; int Dump(int fd, const std::vector &args) override; - ErrCode EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) override; - ErrCode DisableSensor(int32_t sensorId) override; + ErrCode EnableSensor(const SensorDescriptionIPC &sensorDesc, int64_t samplingPeriodNs, + int64_t maxReportDelayNs) override; + ErrCode DisableSensor(const SensorDescriptionIPC &sensorDesc) override; ErrCode GetSensorList(std::vector &sensorList) override; + ErrCode GetSensorListByDevice(int32_t deviceId, std::vector &sensorList) override; ErrCode TransferDataChannel(int32_t sendFd, const sptr &sensorClient) override; ErrCode DestroySensorChannel(const sptr &sensorClient) override; void ProcessDeathObserver(const wptr &object); @@ -58,13 +60,20 @@ public: ErrCode DisableActiveInfoCB() override; ErrCode ResetSensors() override; ErrCode SetDeviceStatus(uint32_t deviceStatus) override; + ErrCode TransferClientRemoteObject(const sptr &sensorClient) override; + ErrCode DestroyClientRemoteObject(const sptr &sensorClient) override; private: DISALLOW_COPY_AND_MOVE(SensorService); std::vector GetSensorList(); + std::vector GetSensorListByDevice(int32_t deviceId); void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; - ErrCode CheckAuthAndParameter(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + ErrCode CheckAuthAndParameter(const SensorDescription &sensorDesc, int64_t samplingPeriodNs, + int64_t maxReportDelayNs); + void ReportPlugEventCallback(const SensorPlugInfo sensorPlugInfo); + ErrCode SensorReportEvent(const SensorDescription &sensorDesc, int64_t samplingPeriodNs, int64_t maxReportDelayNs, + int32_t pid); class PermStateChangeCb : public Security::AccessToken::PermStateChangeCallbackCustomize { public: @@ -79,14 +88,14 @@ private: void RegisterClientDeathRecipient(sptr sensorClient, int32_t pid); void UnregisterClientDeathRecipient(sptr sensorClient); bool InitSensorPolicy(); - void ReportOnChangeData(int32_t sensorId); - void ReportSensorSysEvent(int32_t sensorId, bool enable, int32_t pid, int64_t samplingPeriodNs = 0, + void ReportOnChangeData(const SensorDescription &sensorDesc); + void ReportSensorSysEvent(int32_t sensorType, bool enable, int32_t pid, int64_t samplingPeriodNs = 0, int64_t maxReportDelayNs = 0); - ErrCode DisableSensor(int32_t sensorId, int32_t pid); - bool RegisterPermCallback(int32_t sensorId); + ErrCode DisableSensor(const SensorDescription &sensorDesc, int32_t pid); + bool RegisterPermCallback(int32_t sensorType); void UnregisterPermCallback(); - void ReportActiveInfo(int32_t sensorId, int32_t pid); - bool CheckSensorId(int32_t sensorId); + bool CheckSensorId(const SensorDescription &sensorDesc); + void ReportActiveInfo(const SensorDescription &sensorDesc, int32_t pid); bool IsSystemServiceCalling(); bool IsSystemCalling(); SensorServiceState state_; @@ -94,11 +103,12 @@ private: std::mutex sensorsMutex_; std::mutex sensorMapMutex_; std::vector sensors_; - std::unordered_map sensorMap_; + std::unordered_map sensorMap_; #ifdef HDF_DRIVERS_INTERFACE_SENSOR bool InitInterface(); bool InitDataCallback(); bool InitSensorList(); + bool InitPlugCallback(); SensorHdiConnection &sensorHdiConnection_ = SensorHdiConnection::GetInstance(); sptr sensorDataProcesser_ = nullptr; sptr reportDataCallback_ = nullptr; @@ -110,7 +120,7 @@ private: std::mutex clientDeathObserverMutex_; sptr clientDeathObserver_ = nullptr; std::shared_ptr permStateChangeCb_ = nullptr; - ErrCode SaveSubscriber(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + ErrCode SaveSubscriber(const SensorDescription &sensorDesc, int64_t samplingPeriodNs, int64_t maxReportDelayNs); std::atomic_bool isReportActiveInfo_ = false; static std::atomic_bool isAccessTokenServiceActive_; }; diff --git a/services/src/client_info.cpp b/services/src/client_info.cpp index 7746625e6d1103364dcc5bc5e995c3e3e738d351..9dc3e8fffe19b7a5c23ac27479484ffafa8d651c 100644 --- a/services/src/client_info.cpp +++ b/services/src/client_info.cpp @@ -13,9 +13,11 @@ * limitations under the License. */ +#include "i_sensor_client.h" #include "permission_util.h" #include "securec.h" #include "sensor_manager.h" +#include "sensor_client_proxy.h" #ifdef HDF_DRIVERS_INTERFACE_SENSOR #include "sensor_hdi_connection.h" #endif // HDF_DRIVERS_INTERFACE_SENSOR @@ -42,17 +44,18 @@ std::unordered_map> ClientInfo::userGrantPermMap_ { READ_HEALTH_DATA_PERMISSION, { SENSOR_TYPE_ID_HEART_RATE } } }; -bool ClientInfo::GetSensorState(int32_t sensorId) +bool ClientInfo::GetSensorState(const SensorDescription &sensorDesc) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); - if (sensorId == INVALID_SENSOR_ID) { - SEN_HILOGE("sensorId is invalid"); + SEN_HILOGI("In, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); + if (sensorDesc.sensorType == INVALID_SENSOR_ID) { + SEN_HILOGE("sensorType is invalid"); return false; } std::lock_guard clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); + auto it = clientMap_.find(sensorDesc); if (it == clientMap_.end()) { - SEN_HILOGE("Can't find sensorId:%{public}d", sensorId); + SEN_HILOGE("Can't find sensorType:%{public}d", sensorDesc.sensorType); return false; } for (const auto &pidIt : it->second) { @@ -60,26 +63,28 @@ bool ClientInfo::GetSensorState(int32_t sensorId) return true; } } - SEN_HILOGE("Can't find sensorInfo, sensorId:%{public}d", sensorId); + SEN_HILOGE("Can't find sensorInfo, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return false; } -SensorBasicInfo ClientInfo::GetBestSensorInfo(int32_t sensorId) +SensorBasicInfo ClientInfo::GetBestSensorInfo(const SensorDescription &sensorDesc) { int64_t minSamplingPeriodNs = LLONG_MAX; int64_t minReportDelayNs = LLONG_MAX; SensorBasicInfo sensorInfo; sensorInfo.SetSamplingPeriodNs(minSamplingPeriodNs); sensorInfo.SetMaxReportDelayNs(minReportDelayNs); - if (sensorId == INVALID_SENSOR_ID) { - SEN_HILOGE("sensorId is invalid"); + if (sensorDesc.sensorType == INVALID_SENSOR_ID) { + SEN_HILOGE("sensorType is invalid"); return sensorInfo; } std::lock_guard clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); + auto it = clientMap_.find(sensorDesc); if (it == clientMap_.end()) { - SEN_HILOGE("Can't find sensorId:%{public}d", sensorId); + SEN_HILOGE("Can't find deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d, location:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, sensorDesc.location); return sensorInfo; } for (const auto &pidIt : it->second) { @@ -93,17 +98,18 @@ SensorBasicInfo ClientInfo::GetBestSensorInfo(int32_t sensorId) return sensorInfo; } -bool ClientInfo::OnlyCurPidSensorEnabled(int32_t sensorId, int32_t pid) +bool ClientInfo::OnlyCurPidSensorEnabled(const SensorDescription &sensorDesc, int32_t pid) { - SEN_HILOGI("In, sensorId:%{public}d, pid:%{public}d", sensorId, pid); - if ((sensorId == INVALID_SENSOR_ID) || (pid <= INVALID_PID)) { - SEN_HILOGE("sensorId or pid is invalid"); + SEN_HILOGI("In, sensorType:%{public}d, pid:%{public}d", sensorDesc.sensorType, pid); + if ((sensorDesc.sensorType == INVALID_SENSOR_ID) || (pid <= INVALID_PID)) { + SEN_HILOGE("sensorType or pid is invalid"); return false; } std::lock_guard clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); + auto it = clientMap_.find(sensorDesc); if (it == clientMap_.end()) { - SEN_HILOGE("Can't find sensorId:%{public}d", sensorId); + SEN_HILOGE("Can't find deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return false; } bool ret = false; @@ -117,7 +123,7 @@ bool ClientInfo::OnlyCurPidSensorEnabled(int32_t sensorId, int32_t pid) } ret = true; } - SEN_HILOGI("Done, sensorId:%{public}d, pid:%{public}d", sensorId, pid); + SEN_HILOGI("Done, sensorType:%{public}d, pid:%{public}d", sensorDesc.sensorType, pid); return ret; } @@ -202,16 +208,18 @@ sptr ClientInfo::GetSensorChannelByPid(int32_t pid) return channelIt->second; } -std::vector> ClientInfo::GetSensorChannel(int32_t sensorId) +std::vector> ClientInfo::GetSensorChannel(const SensorDescription &sensorDesc) { - if (sensorId == INVALID_SENSOR_ID) { - SEN_HILOGE("sensorId is invalid"); + if (sensorDesc.sensorType == INVALID_SENSOR_ID) { + SEN_HILOGE("sensorType is invalid"); return {}; } std::lock_guard clientLock(clientMutex_); - auto clientIt = clientMap_.find(sensorId); + auto clientIt = clientMap_.find(sensorDesc); if (clientIt == clientMap_.end()) { - SEN_HILOGD("There is no channel belong to sensorId:%{public}d", sensorId); + SEN_HILOGD("There is no channel belong to sensor," + "deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return {}; } std::vector> sensorChannel; @@ -229,19 +237,19 @@ std::vector> ClientInfo::GetSensorChannel(int32_t s return sensorChannel; } -bool ClientInfo::UpdateSensorInfo(int32_t sensorId, int32_t pid, const SensorBasicInfo &sensorInfo) +bool ClientInfo::UpdateSensorInfo(const SensorDescription &sensorDesc, int32_t pid, const SensorBasicInfo &sensorInfo) { - SEN_HILOGI("In, sensorId:%{public}d, pid:%{public}d", sensorId, pid); - if ((sensorId == INVALID_SENSOR_ID) || (pid <= INVALID_PID) || (!sensorInfo.GetSensorState())) { + SEN_HILOGI("In, sensorType:%{public}d, pid:%{public}d", sensorDesc.sensorType, pid); + if ((sensorDesc.sensorType == INVALID_SENSOR_ID) || (pid <= INVALID_PID) || (!sensorInfo.GetSensorState())) { SEN_HILOGE("Params are invalid"); return false; } std::lock_guard clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); + auto it = clientMap_.find(sensorDesc); if (it == clientMap_.end()) { std::unordered_map pidMap; auto pidRet = pidMap.insert(std::make_pair(pid, sensorInfo)); - auto clientRet = clientMap_.insert(std::make_pair(sensorId, pidMap)); + auto clientRet = clientMap_.insert(std::make_pair(sensorDesc, pidMap)); return pidRet.second && clientRet.second; } auto pidIt = it->second.find(pid); @@ -250,24 +258,24 @@ bool ClientInfo::UpdateSensorInfo(int32_t sensorId, int32_t pid, const SensorBas return ret.second; } it->second[pid] = sensorInfo; - SEN_HILOGI("Done, sensorId:%{public}d, pid:%{public}d", sensorId, pid); + SEN_HILOGI("Done, sensorType:%{public}d, pid:%{public}d", sensorDesc.sensorType, pid); return true; } -void ClientInfo::RemoveSubscriber(int32_t sensorId, uint32_t pid) +void ClientInfo::RemoveSubscriber(const SensorDescription &sensorDesc, uint32_t pid) { - SEN_HILOGI("In, sensorId:%{public}d, pid:%{public}u", sensorId, pid); + SEN_HILOGI("In, sensorTypeId:%{public}d, pid:%{public}u", sensorDesc.sensorType, pid); std::lock_guard clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); + auto it = clientMap_.find(sensorDesc); if (it == clientMap_.end()) { - SEN_HILOGW("sensorId not exist"); + SEN_HILOGW("sensorDesc not exist"); return; } auto pidIt = it->second.find(pid); if (pidIt != it->second.end()) { it->second.erase(pidIt); } - SEN_HILOGI("Done, sensorId:%{public}d, pid:%{public}d", sensorId, pid); + SEN_HILOGI("Done, sensorType:%{public}d, pid:%{public}u", sensorDesc.sensorType, pid); } bool ClientInfo::UpdateSensorChannel(int32_t pid, const sptr &channel) @@ -294,34 +302,35 @@ bool ClientInfo::UpdateSensorChannel(int32_t pid, const sptr clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); + auto it = clientMap_.find(sensorDesc); if (it == clientMap_.end()) { - SEN_HILOGD("sensorId not exist, no need to clear it"); + SEN_HILOGD("sensorDesc not exist, no need to clear it"); return; } clientMap_.erase(it); - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + SEN_HILOGI("Done, sensorType:%{public}d", sensorDesc.sensorType); } -void ClientInfo::ClearCurPidSensorInfo(int32_t sensorId, int32_t pid) +void ClientInfo::ClearCurPidSensorInfo(const SensorDescription &sensorDesc, int32_t pid) { - SEN_HILOGI("In, sensorId:%{public}d, pid:%{public}d", sensorId, pid); - if ((sensorId == INVALID_SENSOR_ID) || (pid <= INVALID_PID)) { - SEN_HILOGE("sensorId or pid is invalid"); + SEN_HILOGI("In, sensorType:%{public}d, pid:%{public}d", sensorDesc.sensorType, pid); + if ((sensorDesc.sensorType == INVALID_SENSOR_ID) || (pid <= INVALID_PID)) { + SEN_HILOGE("sensorType or pid is invalid"); return; } std::lock_guard clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); + auto it = clientMap_.find(sensorDesc); if (it == clientMap_.end()) { - SEN_HILOGD("sensorId not exist, no need to clear it"); + SEN_HILOGD("sensorDesc not exist, no need to clear it"); return; } auto pidIt = it->second.find(pid); @@ -333,7 +342,7 @@ void ClientInfo::ClearCurPidSensorInfo(int32_t sensorId, int32_t pid) if (it->second.size() == MIN_MAP_SIZE) { it = clientMap_.erase(it); } - SEN_HILOGI("Done, sensorId:%{public}d, pid:%{public}d", sensorId, pid); + SEN_HILOGI("Done, sensorType:%{public}d, pid:%{public}d", sensorDesc.sensorType, pid); } bool ClientInfo::DestroySensorChannel(int32_t pid) @@ -368,21 +377,22 @@ bool ClientInfo::DestroySensorChannel(int32_t pid) return true; } -SensorBasicInfo ClientInfo::GetCurPidSensorInfo(int32_t sensorId, int32_t pid) +SensorBasicInfo ClientInfo::GetCurPidSensorInfo(const SensorDescription &sensorDesc, int32_t pid) { int64_t minSamplingPeriodNs = LLONG_MAX; int64_t minReportDelayNs = LLONG_MAX; SensorBasicInfo sensorInfo; sensorInfo.SetSamplingPeriodNs(minSamplingPeriodNs); sensorInfo.SetMaxReportDelayNs(minReportDelayNs); - if ((sensorId == INVALID_SENSOR_ID) || (pid <= INVALID_PID)) { - SEN_HILOGE("sensorId or channel is invalid"); + if ((sensorDesc.sensorType == INVALID_SENSOR_ID) || (pid <= INVALID_PID)) { + SEN_HILOGE("sensorType or channel is invalid"); return sensorInfo; } std::lock_guard clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); + auto it = clientMap_.find(sensorDesc); if (it == clientMap_.end()) { - SEN_HILOGE("Can't find sensorId:%{public}d", sensorId); + SEN_HILOGE("Can't find deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return sensorInfo; } auto pidIt = it->second.find(pid); @@ -395,10 +405,10 @@ SensorBasicInfo ClientInfo::GetCurPidSensorInfo(int32_t sensorId, int32_t pid) return sensorInfo; } -uint64_t ClientInfo::ComputeBestPeriodCount(int32_t sensorId, sptr &channel) +uint64_t ClientInfo::ComputeBestPeriodCount(const SensorDescription &sensorDesc, sptr &channel) { - if (sensorId == INVALID_SENSOR_ID || channel == nullptr) { - SEN_HILOGE("sensorId is invalid or channel cannot be null"); + if (sensorDesc.sensorType == INVALID_SENSOR_ID || channel == nullptr) { + SEN_HILOGE("sensorType is invalid or channel cannot be null"); return 0UL; } int32_t pid = INVALID_PID; @@ -410,8 +420,8 @@ uint64_t ClientInfo::ComputeBestPeriodCount(int32_t sensorId, sptr &channel) +uint64_t ClientInfo::ComputeBestFifoCount(const SensorDescription &sensorDesc, sptr &channel) { - if (channel == nullptr || sensorId == INVALID_SENSOR_ID) { - SEN_HILOGE("sensorId is invalid or channel cannot be null"); + if (channel == nullptr || sensorDesc.sensorType == INVALID_SENSOR_ID) { + SEN_HILOGE("sensorType is invalid or channel cannot be null"); return 0UL; } int32_t pid = INVALID_PID; @@ -435,8 +445,8 @@ uint64_t ClientInfo::ComputeBestFifoCount(int32_t sensorId, sptr lock(eventMutex_); - auto storedEvent = storedEvent_.find(sensorId); + auto storedEvent = storedEvent_.find(sensorDesc); if (storedEvent != storedEvent_.end()) { errno_t ret = memcpy_s(&data, sizeof(data), &storedEvent->second, sizeof(storedEvent->second)); if (ret != EOK) { - SEN_HILOGE("memcpy_s failed, sensorId:%{public}d", sensorId); + SEN_HILOGE("memcpy_s failed, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return ret; } return ERR_OK; } - SEN_HILOGE("Can't get store event, sensorId:%{public}d", sensorId); + SEN_HILOGE("Can't get store event, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return NO_STORE_EVENT; } @@ -485,7 +497,8 @@ void ClientInfo::StoreEvent(const SensorData &data) return; } for (size_t i = 0; i < sensors.size(); i++) { - if (sensors[i].GetSensorId() == storedEvent.sensorTypeId) { + if (sensors[i].GetSensorId() == storedEvent.sensorTypeId && sensors[i].GetDeviceId() == storedEvent.deviceId + && sensors[i].GetSensorId() == storedEvent.sensorId) { foundSensor = true; break; } @@ -493,7 +506,8 @@ void ClientInfo::StoreEvent(const SensorData &data) if (foundSensor) { std::lock_guard lock(eventMutex_); - storedEvent_[storedEvent.sensorTypeId] = storedEvent; + storedEvent_[{storedEvent.deviceId, storedEvent.sensorTypeId, storedEvent.sensorId, + storedEvent.location}] = storedEvent; } } @@ -543,18 +557,18 @@ void ClientInfo::ClearEvent() storedEvent_.clear(); } -std::vector ClientInfo::GetSensorIdByPid(int32_t pid) +std::vector ClientInfo::GetSensorIdByPid(int32_t pid) { CALL_LOG_ENTER; - std::vector sensorIdVec; + std::vector sensorDescVec; std::lock_guard clientLock(clientMutex_); for (const auto &itClientMap : clientMap_) { auto it = itClientMap.second.find(pid); if (it != itClientMap.second.end()) { - sensorIdVec.push_back(itClientMap.first); + sensorDescVec.push_back(itClientMap.first); } } - return sensorIdVec; + return sensorDescVec; } AppThreadInfo ClientInfo::GetAppInfoByChannel(const sptr &channel) @@ -598,7 +612,9 @@ void ClientInfo::GetSensorChannelInfo(std::vector &channelInf } SensorChannelInfo channel; channel.SetUid(uid); - channel.SetSensorId(sensorIt.first); + channel.SetDeviceId(sensorIt.first.deviceId); + channel.SetSensorType(sensorIt.first.sensorType); + channel.SetSensorId(sensorIt.first.sensorId); std::string packageName; SensorManager::GetInstance().GetPackageName(GetTokenIdByPid(pid), packageName); channel.SetPackageName(packageName); @@ -607,7 +623,7 @@ void ClientInfo::GetSensorChannelInfo(std::vector &channelInf channel.SetSamplingPeriodNs(samplingPeriodNs); uint32_t fifoCount = (samplingPeriodNs == 0) ? 0 : (uint32_t)(maxReportDelayNs / samplingPeriodNs); channel.SetFifoCount(fifoCount); - channel.SetCmdType(GetCmdList(sensorIt.first, uid)); + channel.SetCmdType(GetCmdList(sensorIt.first.sensorType, uid)); channelInfo.push_back(channel); } } @@ -633,16 +649,16 @@ AccessTokenID ClientInfo::GetTokenIdByPid(int32_t pid) return appThreadInfoIt->second.callerToken; } -void ClientInfo::UpdateCmd(int32_t sensorId, int32_t uid, int32_t cmdType) +void ClientInfo::UpdateCmd(int32_t sensorType, int32_t uid, int32_t cmdType) { std::lock_guard cmdLock(cmdMutex_); - auto cmdIt = cmdMap_.find(sensorId); + auto cmdIt = cmdMap_.find(sensorType); if (cmdIt == cmdMap_.end()) { std::unordered_map> cmds; std::vector tmp; tmp.push_back(cmdType); cmds.insert(std::make_pair(uid, tmp)); - cmdMap_.insert(std::make_pair(sensorId, cmds)); + cmdMap_.insert(std::make_pair(sensorType, cmds)); return; } auto tmpIt = cmdIt->second.find(uid); @@ -663,10 +679,10 @@ void ClientInfo::DestroyCmd(int32_t uid) cmdMap_.erase(uid); } -std::vector ClientInfo::GetCmdList(int32_t sensorId, int32_t uid) +std::vector ClientInfo::GetCmdList(int32_t sensorType, int32_t uid) { std::lock_guard cmdLock(cmdMutex_); - auto cmdIt = cmdMap_.find(sensorId); + auto cmdIt = cmdMap_.find(sensorType); if (cmdIt == cmdMap_.end()) { return {}; } @@ -677,17 +693,18 @@ std::vector ClientInfo::GetCmdList(int32_t sensorId, int32_t uid) return uidIt->second; } -void ClientInfo::UpdateDataQueue(int32_t sensorId, SensorData &data) +void ClientInfo::UpdateDataQueue(int32_t sensorType, SensorData &data) { - if (sensorId == SENSOR_TYPE_ID_HEART_RATE) { + if (sensorType == SENSOR_TYPE_ID_HEART_RATE) { return; } std::lock_guard queueLock(dataQueueMutex_); - auto it = dumpQueue_.find(sensorId); + auto it = dumpQueue_.find({data.deviceId, data.sensorTypeId, data.sensorId, data.location}); if (it == dumpQueue_.end()) { std::queue q; q.push(data); - dumpQueue_.insert(std::make_pair(sensorId, q)); + dumpQueue_.insert(std::pair>( + {data.deviceId, data.sensorTypeId, data.sensorId, data.location}, q)); return; } it->second.push(data); @@ -696,15 +713,15 @@ void ClientInfo::UpdateDataQueue(int32_t sensorId, SensorData &data) } } -std::unordered_map> ClientInfo::GetDumpQueue() +std::unordered_map> ClientInfo::GetDumpQueue() { return dumpQueue_; } -void ClientInfo::ClearDataQueue(int32_t sensorId) +void ClientInfo::ClearDataQueue(const SensorDescription &sensorDesc) { std::lock_guard queueLock(dataQueueMutex_); - auto it = dumpQueue_.find(sensorId); + auto it = dumpQueue_.find(sensorDesc); if (it != dumpQueue_.end()) { dumpQueue_.erase(it); } @@ -774,17 +791,19 @@ int32_t ClientInfo::GetPidByTokenId(AccessTokenID tokenId) return pid; } -void ClientInfo::UpdatePermState(int32_t pid, int32_t sensorId, bool state) +void ClientInfo::UpdatePermState(int32_t pid, int32_t sensorType, bool state) { std::lock_guard clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); - if (it == clientMap_.end()) { - SEN_HILOGE("Cannot find sensorId:%{public}d", sensorId); - return; - } - auto clientInfo = it->second.find(pid); - if (clientInfo != it->second.end()) { - clientInfo->second.SetPermState(state); + for (auto it = clientMap_.begin(); it != clientMap_.end();) { + if (it->first.sensorType != sensorType) { + it++; + continue; + } + auto clientInfo = it->second.find(pid); + if (clientInfo != it->second.end()) { + clientInfo->second.SetPermState(state); + } + it++; } } @@ -800,8 +819,8 @@ void ClientInfo::ChangeSensorPerm(AccessTokenID tokenId, const std::string &perm SEN_HILOGE("Invalid permission name:%{public}s", permName.c_str()); return; } - for (int32_t sensorId : it->second) { - UpdatePermState(pid, sensorId, state); + for (int32_t sensorType : it->second) { + UpdatePermState(pid, sensorType, state); } } @@ -814,5 +833,35 @@ uint32_t ClientInfo::GetDeviceStatus() { return deviceStatus_; } + +void ClientInfo::SaveSensorClient(const sptr &sensorClient) +{ + CALL_LOG_ENTER; + CHKPV(sensorClient); + std::lock_guard lock(sensorClientMutex_); + sensorClients_.push_back(sensorClient); +} + +void ClientInfo::DestroySensorClient(const sptr &sensorClient) +{ + CALL_LOG_ENTER; + CHKPV(sensorClient); + std::lock_guard lock(sensorClientMutex_); + auto it = std::find(sensorClients_.begin(), sensorClients_.end(), sensorClient); + if (it != sensorClients_.end()) { + sensorClients_.erase(it); + } +} + +void ClientInfo::SendMsgToClient(SensorPlugData info) +{ + CALL_LOG_ENTER; + for (const auto &client : sensorClients_) { + sptr clientProxy = iface_cast(client); + if (clientProxy != nullptr) { + clientProxy->ProcessPlugEvent(info); + } + } +} } // namespace Sensors } // namespace OHOS diff --git a/services/src/flush_info_record.cpp b/services/src/flush_info_record.cpp index 799a8f232ac243a383548d5f9279dc2592331ab3..f8a44a314502005ed5ce75d563124b37912565af 100644 --- a/services/src/flush_info_record.cpp +++ b/services/src/flush_info_record.cpp @@ -32,29 +32,30 @@ std::unordered_map> FlushInfoRecord::GetFlushInf return flushInfo_; } -void FlushInfoRecord::ClearFlushInfoItem(int32_t sensorId) +void FlushInfoRecord::ClearFlushInfoItem(int32_t sensorType) { std::lock_guard flushLock(flushInfoMutex_); - auto it = flushInfo_.find(sensorId); + auto it = flushInfo_.find(sensorType); if (it != flushInfo_.end()) { it->second.erase(it->second.begin()); } } -ErrCode FlushInfoRecord::SetFlushInfo(int32_t sensorId, const sptr &channel, bool isFirstFlush) +ErrCode FlushInfoRecord::SetFlushInfo(int32_t sensorType, const sptr &channel, + bool isFirstFlush) { - SEN_HILOGD("sensorId:%{public}u", sensorId); + SEN_HILOGD("sensorType:%{public}u", sensorType); CHKPR(channel, INVALID_POINTER); FlushInfo flush(channel, isFirstFlush); std::lock_guard flushLock(flushInfoMutex_); /* If the sensorId can be found, it indicates that other processes have flushed on this sensor, so need to insert this flush command to the end of the vector */ - auto it = flushInfo_.find(sensorId); + auto it = flushInfo_.find(sensorType); if (it != flushInfo_.end()) { it->second.push_back(flush); } else { std::vector vec { flush }; - flushInfo_.insert(std::make_pair(sensorId, vec)); + flushInfo_.insert(std::make_pair(sensorType, vec)); } return ERR_OK; } @@ -82,12 +83,12 @@ int32_t FlushInfoRecord::GetFlushChannelIndex(const std::vector &flus return CHANNEL_NO_FLUSH; } -ErrCode FlushInfoRecord::FlushProcess(const int32_t sensorId, const uint32_t flag, const int32_t pid, +ErrCode FlushInfoRecord::FlushProcess(const int32_t sensorType, const uint32_t flag, const int32_t pid, const bool isEnableFlush) { sptr channel = clientInfo_.GetSensorChannelByPid(pid); CHKPR(channel, ERROR); - int32_t ret = SetFlushInfo(sensorId, channel, false); + int32_t ret = SetFlushInfo(sensorType, channel, false); if (ret != ERR_OK) { SEN_HILOGE("Set flush info failed"); return ret; diff --git a/services/src/sensor_data_processer.cpp b/services/src/sensor_data_processer.cpp index 34e69cc38fa4c8ee5e05a2566a51b71e9fc17150..f4e1fbae73755b956db771d43fc71723748b7af6 100644 --- a/services/src/sensor_data_processer.cpp +++ b/services/src/sensor_data_processer.cpp @@ -36,7 +36,7 @@ namespace { const std::string SENSOR_REPORT_THREAD_NAME = "OS_SenProducer"; } // namespace -SensorDataProcesser::SensorDataProcesser(const std::unordered_map &sensorMap) +SensorDataProcesser::SensorDataProcesser(const std::unordered_map &sensorMap) { sensorMap_.insert(sensorMap.begin(), sensorMap.end()); SEN_HILOGD("sensorMap_.size:%{public}d", int32_t { sensorMap_.size() }); @@ -48,21 +48,29 @@ SensorDataProcesser::~SensorDataProcesser() sensorMap_.clear(); } -void SensorDataProcesser::SendNoneFifoCacheData(std::unordered_map &cacheBuf, +void SensorDataProcesser::UpdataSensorMap(const std::unordered_map &sensorMap) +{ + sensorMap_.clear(); + sensorMap_.insert(sensorMap.begin(), sensorMap.end()); + SEN_HILOGD("sensorMap_.size:%{public}d", int32_t { sensorMap_.size() }); +} + +void SensorDataProcesser::SendNoneFifoCacheData(std::unordered_map &cacheBuf, sptr &channel, SensorData &data, uint64_t periodCount) { std::vector sendEvents; std::lock_guard dataCountLock(dataCountMutex_); sendEvents.push_back(data); - auto dataCountIt = dataCountMap_.find(data.sensorTypeId); + auto dataCountIt = dataCountMap_.find({data.deviceId, data.sensorTypeId, data.sensorId, data.location}); if (dataCountIt == dataCountMap_.end()) { std::vector> channelFifoList; sptr fifoCacheData = new (std::nothrow) FifoCacheData(); CHKPV(fifoCacheData); fifoCacheData->SetChannel(channel); channelFifoList.push_back(fifoCacheData); - dataCountMap_.insert(std::make_pair(data.sensorTypeId, channelFifoList)); + dataCountMap_.insert(std::pair>>( + {data.deviceId, data.sensorTypeId, data.sensorId, data.location}, channelFifoList)); SendRawData(cacheBuf, channel, sendEvents); return; } @@ -99,12 +107,12 @@ void SensorDataProcesser::SendNoneFifoCacheData(std::unordered_map &cacheBuf, +void SensorDataProcesser::SendFifoCacheData(std::unordered_map &cacheBuf, sptr &channel, SensorData &data, uint64_t periodCount, uint64_t fifoCount) { std::lock_guard dataCountLock(dataCountMutex_); - auto dataCountIt = dataCountMap_.find(data.sensorTypeId); + auto dataCountIt = dataCountMap_.find({data.deviceId, data.sensorTypeId, data.sensorId, data.location}); // there is no channelFifoList if (dataCountIt == dataCountMap_.end()) { std::vector> channelFifoList; @@ -112,7 +120,8 @@ void SensorDataProcesser::SendFifoCacheData(std::unordered_mapSetChannel(channel); channelFifoList.push_back(fifoCacheData); - dataCountMap_.insert(std::make_pair(data.sensorTypeId, channelFifoList)); + dataCountMap_.insert(std::pair>>( + {data.deviceId, data.sensorTypeId, data.sensorId, data.location}, channelFifoList)); return; } // find channel in channelFifoList @@ -149,30 +158,38 @@ void SensorDataProcesser::SendFifoCacheData(std::unordered_map fifoCacheData = new (std::nothrow) FifoCacheData(); - CHKPV(fifoCacheData); - fifoCacheData->SetChannel(channel); - dataCountIt->second.push_back(fifoCacheData); + UpdataFifoDataChannel(channel, dataCountIt->second); } } +void SensorDataProcesser::UpdataFifoDataChannel(sptr &channel, + std::vector> &dataCount) +{ + sptr fifoCacheData = new (std::nothrow) FifoCacheData(); + CHKPV(fifoCacheData); + fifoCacheData->SetChannel(channel); + dataCount.push_back(fifoCacheData); +} + void SensorDataProcesser::ReportData(sptr &channel, SensorData &data) { CHKPV(channel); - int32_t sensorId = data.sensorTypeId; - if (sensorId == SENSOR_TYPE_ID_HALL_EXT) { + int32_t sensorTypeId = data.sensorTypeId; + if (sensorTypeId == SENSOR_TYPE_ID_HALL_EXT) { PrintSensorData::GetInstance().PrintSensorDataLog("ReportData", data); } - auto &cacheBuf = const_cast &>(channel->GetDataCacheBuf()); + auto &cacheBuf = const_cast &>(channel->GetDataCacheBuf()); if (ReportNotContinuousData(cacheBuf, channel, data)) { return; } - uint64_t periodCount = clientInfo_.ComputeBestPeriodCount(sensorId, channel); + uint64_t periodCount = clientInfo_.ComputeBestPeriodCount({data.deviceId, data.sensorTypeId, data.sensorId, + data.location}, channel); if (periodCount == 0UL) { SEN_HILOGE("periodCount is zero"); return; } - auto fifoCount = clientInfo_.ComputeBestFifoCount(sensorId, channel); + auto fifoCount = clientInfo_.ComputeBestFifoCount({data.deviceId, data.sensorTypeId, data.sensorId, + data.location}, channel); if (fifoCount <= 1) { SendNoneFifoCacheData(cacheBuf, channel, data, periodCount); return; @@ -180,14 +197,14 @@ void SensorDataProcesser::ReportData(sptr &channel, Sens SendFifoCacheData(cacheBuf, channel, data, periodCount, fifoCount); } -bool SensorDataProcesser::ReportNotContinuousData(std::unordered_map &cacheBuf, +bool SensorDataProcesser::ReportNotContinuousData(std::unordered_map &cacheBuf, sptr &channel, SensorData &data) { - int32_t sensorId = data.sensorTypeId; + int32_t sensorTypeId = data.sensorTypeId; std::lock_guard sensorLock(sensorMutex_); - auto sensor = sensorMap_.find(sensorId); + auto sensor = sensorMap_.find({data.deviceId, data.sensorTypeId, data.sensorId, data.location}); if (sensor == sensorMap_.end()) { - SEN_HILOGE("Data's sensorId is not supported"); + SEN_HILOGE("Data's SensorDesc is not supported"); return false; } sensor->second.SetFlags(data.mode); @@ -195,7 +212,7 @@ bool SensorDataProcesser::ReportNotContinuousData(std::unordered_mapsecond.GetFlags()) == SENSOR_ONE_SHOT)) { std::vector sendEvents; sendEvents.push_back(data); - if (sensorId == SENSOR_TYPE_ID_HALL_EXT) { + if (sensorTypeId == SENSOR_TYPE_ID_HALL_EXT) { PrintSensorData::GetInstance().PrintSensorDataLog("ReportNotContinuousData", data); } SendRawData(cacheBuf, channel, sendEvents); @@ -204,7 +221,7 @@ bool SensorDataProcesser::ReportNotContinuousData(std::unordered_map &cacheBuf, +void SensorDataProcesser::SendRawData(std::unordered_map &cacheBuf, sptr channel, std::vector events) { CHKPV(channel); @@ -214,10 +231,10 @@ void SensorDataProcesser::SendRawData(std::unordered_map &c size_t eventSize = events.size(); auto ret = channel->SendData(events.data(), eventSize * sizeof(SensorData)); if (ret != ERR_OK) { - SEN_HILOGE("Send data failed, ret:%{public}d, sensorId:%{public}d, timestamp:%{public}" PRId64, + SEN_HILOGE("Send data failed, ret:%{public}d, sensorTypeId:%{public}d, timestamp:%{public}" PRId64, ret, events[eventSize - 1].sensorTypeId, events[eventSize - 1].timestamp); - int32_t sensorId = events[eventSize - 1].sensorTypeId; - cacheBuf[sensorId] = events[eventSize - 1]; + cacheBuf[{events[eventSize - 1].deviceId, events[eventSize - 1].sensorTypeId, + events[eventSize - 1].sensorId, events[eventSize - 1].location}] = events[eventSize - 1]; } } @@ -225,34 +242,33 @@ int32_t SensorDataProcesser::CacheSensorEvent(const SensorData &data, sptr &>(channel->GetDataCacheBuf()); - int32_t sensorId = data.sensorTypeId; - if (sensorId == SENSOR_TYPE_ID_HALL_EXT) { + auto &cacheBuf = const_cast &>(channel->GetDataCacheBuf()); + if (data.sensorTypeId == SENSOR_TYPE_ID_HALL_EXT) { PrintSensorData::GetInstance().PrintSensorDataLog("CacheSensorEvent", data); } - auto cacheEvent = cacheBuf.find(sensorId); + auto cacheEvent = cacheBuf.find({data.deviceId, data.sensorTypeId, data.sensorId, data.location}); if (cacheEvent != cacheBuf.end()) { // Try to send the last failed value, if it still fails, replace the previous cache directly const SensorData &cacheData = cacheEvent->second; ret = channel->SendData(&cacheData, sizeof(SensorData)); if (ret != ERR_OK) { - SEN_HILOGE("retry send cache data failed, ret:%{public}d, sensorId:%{public}d, timestamp:%{public}" PRId64, + SEN_HILOGE("retry send cacheData failed, ret:%{public}d, sensorType:%{public}d, timestamp:%{public}" PRId64, ret, cacheData.sensorTypeId, cacheData.timestamp); } ret = channel->SendData(&data, sizeof(SensorData)); if (ret != ERR_OK) { - SEN_HILOGE("retry send data failed, ret:%{public}d, sensorId:%{public}d, timestamp:%{public}" PRId64, + SEN_HILOGE("retry send data failed, ret:%{public}d, sensorType:%{public}d, timestamp:%{public}" PRId64, ret, data.sensorTypeId, data.timestamp); - cacheBuf[sensorId] = data; + cacheBuf[{data.deviceId, data.sensorTypeId, data.sensorId, data.location}] = data; } else { cacheBuf.erase(cacheEvent); } } else { ret = channel->SendData(&data, sizeof(SensorData)); if (ret != ERR_OK) { - SEN_HILOGE("directly retry failed, ret:%{public}d, sensorId:%{public}d, timestamp:%{public}" PRId64, + SEN_HILOGE("directly retry failed, ret:%{public}d, sensorType:%{public}d, timestamp:%{public}" PRId64, ret, data.sensorTypeId, data.timestamp); - cacheBuf[sensorId] = data; + cacheBuf[{data.deviceId, data.sensorTypeId, data.sensorId, data.location}] = data; } } return ret; @@ -260,11 +276,12 @@ int32_t SensorDataProcesser::CacheSensorEvent(const SensorData &data, sptr> channelList = clientInfo_.GetSensorChannel(sensorId); + std::vector> channelList = clientInfo_.GetSensorChannel({ + eventsBuf.circularBuf[eventsBuf.readPos].deviceId, eventsBuf.circularBuf[eventsBuf.readPos].sensorTypeId, + eventsBuf.circularBuf[eventsBuf.readPos].sensorId, eventsBuf.circularBuf[eventsBuf.readPos].location}); for (auto &channel : channelList) { if (channel == nullptr) { SEN_HILOGE("channel is null"); diff --git a/services/src/sensor_dump.cpp b/services/src/sensor_dump.cpp index bc6f670fee414730cf4d31e0355eac77ac0778e8..ed978d2a9c8ba74e41c9a954bea00312cd036613 100644 --- a/services/src/sensor_dump.cpp +++ b/services/src/sensor_dump.cpp @@ -198,16 +198,18 @@ bool SensorDump::DumpSensorList(int32_t fd, const std::vector &sensors) DumpCurrentTime(fd); dprintf(fd, "Total sensor:%d, Sensor list:\n", int32_t { sensors.size() }); for (const auto &sensor : sensors) { + auto deviceId = sensor.GetDeviceId(); + auto sensorTypeId = sensor.GetSensorTypeId(); auto sensorId = sensor.GetSensorId(); - if (sensorMap_.find(sensorId) == sensorMap_.end()) { + if (sensorMap_.find(sensorTypeId) == sensorMap_.end()) { continue; } dprintf(fd, - "sensorId:%8u | sensorType:%s | sensorName:%s | vendorName:%s | maxRange:%f" + "deviceId:%d | sensorType:%s |sensorId:%8u | sensorName:%s | vendorName:%s | maxRange:%f" "| fifoMaxEventCount:%d | minSamplePeriodNs:%" PRId64 " | maxSamplePeriodNs:%" PRId64 "\n", - sensorId, sensorMap_[sensorId].c_str(), sensor.GetSensorName().c_str(), sensor.GetVendorName().c_str(), - sensor.GetMaxRange(), sensor.GetFifoMaxEventCount(), sensor.GetMinSamplePeriodNs(), - sensor.GetMaxSamplePeriodNs()); + deviceId, sensorMap_[sensorTypeId].c_str(), sensorId, sensor.GetSensorName().c_str(), + sensor.GetVendorName().c_str(), sensor.GetMaxRange(), sensor.GetFifoMaxEventCount(), + sensor.GetMinSamplePeriodNs(), sensor.GetMaxSamplePeriodNs()); } return true; } @@ -219,14 +221,16 @@ bool SensorDump::DumpSensorChannel(int32_t fd, ClientInfo &clientInfo) std::vector channelInfo; clientInfo.GetSensorChannelInfo(channelInfo); for (const auto &channel : channelInfo) { + auto deviceId = channel.GetDeviceId(); + auto sensorType = channel.GetSensorType(); auto sensorId = channel.GetSensorId(); if (sensorMap_.find(sensorId) == sensorMap_.end()) { continue; } dprintf(fd, - "uid:%d | packageName:%s | sensorId:%8u | sensorType:%s | samplingPeriodNs:%" PRId64 "" + "uid:%d | packageName:%s | deviceId:%d | sensorType:%s |sensorId:%8u | samplingPeriodNs:%" PRId64 "" "| fifoCount:%u\n", - channel.GetUid(), channel.GetPackageName().c_str(), sensorId, sensorMap_[sensorId].c_str(), + channel.GetUid(), channel.GetPackageName().c_str(), deviceId, sensorMap_[sensorType].c_str(), sensorId, channel.GetSamplingPeriodNs(), channel.GetFifoCount()); } return true; @@ -237,13 +241,16 @@ bool SensorDump::DumpOpeningSensor(int32_t fd, const std::vector &sensor DumpCurrentTime(fd); dprintf(fd, "Opening sensors:\n"); for (const auto &sensor : sensors) { - int32_t sensorId = sensor.GetSensorId(); - if (sensorMap_.find(sensorId) == sensorMap_.end()) { + auto deviceId = sensor.GetDeviceId(); + auto sensorTypeId = sensor.GetSensorTypeId(); + auto sensorId = sensor.GetSensorId(); + if (sensorMap_.find(sensorTypeId) == sensorMap_.end()) { continue; } - if (clientInfo.GetSensorState(sensorId)) { - dprintf(fd, "sensorId: %8u | sensorType: %s | channelSize: %lu\n", - sensorId, sensorMap_[sensorId].c_str(), clientInfo.GetSensorChannel(sensorId).size()); + if (clientInfo.GetSensorState({sensor.GetDeviceId(), sensorTypeId, sensor.GetSensorId()})) { + dprintf(fd, "deviceId:%d | sensorType:%s |sensorId:%8u | channelSize: %lu\n", + deviceId, sensorMap_[sensorTypeId].c_str(), sensorId, clientInfo.GetSensorChannel({ + sensor.GetDeviceId(), sensorTypeId, sensor.GetSensorId(), sensor.GetLocation()}).size()); } } return true; @@ -256,11 +263,11 @@ bool SensorDump::DumpSensorData(int32_t fd, ClientInfo &clientInfo) auto dataMap = clientInfo.GetDumpQueue(); int32_t j = 0; for (auto &sensorData : dataMap) { - int32_t sensorId = sensorData.first; - if (sensorMap_.find(sensorId) == sensorMap_.end()) { + if (sensorMap_.find(sensorData.first.sensorType) == sensorMap_.end()) { continue; } - dprintf(fd, "sensorId: %8u | sensorType: %s:\n", sensorId, sensorMap_[sensorId].c_str()); + dprintf(fd, "deviceId:%d | sensorType:%s |sensorId:%8u :\n", sensorData.first.deviceId, + sensorMap_[sensorData.first.sensorType].c_str(), sensorData.first.sensorId); for (uint32_t i = 0; i < MAX_DUMP_DATA_SIZE && (!sensorData.second.empty()); i++) { auto data = sensorData.second.front(); sensorData.second.pop(); @@ -270,7 +277,7 @@ bool SensorDump::DumpSensorData(int32_t fd, ClientInfo &clientInfo) CHKPF(timeinfo); dprintf(fd, " %2d (ts=%.9f, time=%02d:%02d:%02d.%03d) | data:%s", ++j, data.timestamp / 1e9, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, int32_t { (time.tv_nsec / MS_NS) }, - GetDataBySensorId(sensorId, data).c_str()); + GetDataBySensorId(sensorData.first.sensorType, data).c_str()); } } return true; @@ -287,9 +294,9 @@ void SensorDump::DumpCurrentTime(int32_t fd) int32_t { (curTime.tv_nsec / MS_NS) }); } -int32_t SensorDump::GetDataDimension(int32_t sensorId) +int32_t SensorDump::GetDataDimension(int32_t sensorType) { - switch (sensorId) { + switch (sensorType) { case SENSOR_TYPE_ID_BAROMETER: case SENSOR_TYPE_ID_HALL: case SENSOR_TYPE_ID_HALL_EXT: @@ -317,16 +324,16 @@ int32_t SensorDump::GetDataDimension(int32_t sensorId) case SENSOR_TYPE_ID_POSTURE: return SEVEN_DIMENSION; default: - SEN_HILOGW("Unknown sensorId:%{public}d, size:%{public}d", sensorId, COMMON_DIMENSION); + SEN_HILOGW("Unknown sensorType:%{public}d, size:%{public}d", sensorType, COMMON_DIMENSION); return COMMON_DIMENSION; } } -std::string SensorDump::GetDataBySensorId(int32_t sensorId, SensorData &sensorData) +std::string SensorDump::GetDataBySensorId(int32_t sensorType, SensorData &sensorData) { - SEN_HILOGD("sensorId:%{public}u", sensorId); + SEN_HILOGD("sensorType:%{public}u", sensorType); std::string str; - int32_t dataLen = GetDataDimension(sensorId); + int32_t dataLen = GetDataDimension(sensorType); if (sensorData.dataLen < sizeof(float)) { SEN_HILOGE("SensorData dataLen less than float size"); return str; diff --git a/services/src/sensor_manager.cpp b/services/src/sensor_manager.cpp index e79c215e1e81eabd8d6695d2b4227befa6c41aea..3a4b5966a5e18c49ce76b49e0ac2648490029ae4 100644 --- a/services/src/sensor_manager.cpp +++ b/services/src/sensor_manager.cpp @@ -32,7 +32,7 @@ constexpr float PROXIMITY_FAR = 5.0; } // namespace #ifdef HDF_DRIVERS_INTERFACE_SENSOR -void SensorManager::InitSensorMap(const std::unordered_map &sensorMap, +void SensorManager::InitSensorMap(const std::unordered_map &sensorMap, sptr dataProcesser, sptr dataCallback) { std::lock_guard sensorLock(sensorMapMutex_); @@ -42,14 +42,15 @@ void SensorManager::InitSensorMap(const std::unordered_map &sen SEN_HILOGD("Begin sensorMap_.size:%{public}zu", sensorMap_.size()); } -bool SensorManager::SetBestSensorParams(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) +bool SensorManager::SetBestSensorParams(const SensorDescription &sensorDesc, int64_t samplingPeriodNs, + int64_t maxReportDelayNs) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); - if (sensorId == INVALID_SENSOR_ID) { - SEN_HILOGE("sensorId is invalid"); + SEN_HILOGI("In, sensorType:%{public}d", sensorDesc.sensorType); + if (sensorDesc.sensorType == INVALID_SENSOR_ID) { + SEN_HILOGE("sensorType is invalid"); return false; } - SensorBasicInfo sensorInfo = clientInfo_.GetBestSensorInfo(sensorId); + SensorBasicInfo sensorInfo = clientInfo_.GetBestSensorInfo(sensorDesc); int64_t bestSamplingPeriodNs = sensorInfo.GetSamplingPeriodNs(); int64_t bestReportDelayNs = sensorInfo.GetMaxReportDelayNs(); if ((samplingPeriodNs > bestSamplingPeriodNs) && (maxReportDelayNs > bestReportDelayNs)) { @@ -59,30 +60,31 @@ bool SensorManager::SetBestSensorParams(int32_t sensorId, int64_t samplingPeriod bestSamplingPeriodNs = (samplingPeriodNs < bestSamplingPeriodNs) ? samplingPeriodNs : bestSamplingPeriodNs; bestReportDelayNs = (maxReportDelayNs < bestReportDelayNs) ? maxReportDelayNs : bestReportDelayNs; SEN_HILOGD("bestSamplingPeriodNs : %{public}" PRId64, bestSamplingPeriodNs); - auto ret = sensorHdiConnection_.SetBatch(sensorId, bestSamplingPeriodNs, bestReportDelayNs); + auto ret = sensorHdiConnection_.SetBatch(sensorDesc, bestSamplingPeriodNs, bestReportDelayNs); if (ret != ERR_OK) { SEN_HILOGE("SetBatch is failed"); return false; } - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + SEN_HILOGI("Done, sensorType:%{public}d", sensorDesc.sensorType); return true; } -bool SensorManager::ResetBestSensorParams(int32_t sensorId) +bool SensorManager::ResetBestSensorParams(const SensorDescription &sensorDesc) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); - if (sensorId == INVALID_SENSOR_ID) { - SEN_HILOGE("sensorId is invalid"); + SEN_HILOGI("In, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); + if (sensorDesc.sensorType == INVALID_SENSOR_ID) { + SEN_HILOGE("sensorType is invalid"); return false; } - SensorBasicInfo sensorInfo = clientInfo_.GetBestSensorInfo(sensorId); - auto ret = sensorHdiConnection_.SetBatch(sensorId, + SensorBasicInfo sensorInfo = clientInfo_.GetBestSensorInfo(sensorDesc); + auto ret = sensorHdiConnection_.SetBatch(sensorDesc, sensorInfo.GetSamplingPeriodNs(), sensorInfo.GetMaxReportDelayNs()); if (ret != ERR_OK) { SEN_HILOGE("SetBatch is failed"); return false; } - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + SEN_HILOGI("Done, sensorType:%{public}d", sensorDesc.sensorType); return true; } @@ -96,7 +98,7 @@ void SensorManager::StartDataReportThread() } } #else -void SensorManager::InitSensorMap(const std::unordered_map &sensorMap) +void SensorManager::InitSensorMap(const std::unordered_map &sensorMap) { std::lock_guard sensorLock(sensorMapMutex_); sensorMap_ = sensorMap; @@ -104,30 +106,31 @@ void SensorManager::InitSensorMap(const std::unordered_map &sen } #endif // HDF_DRIVERS_INTERFACE_SENSOR -bool SensorManager::SaveSubscriber(int32_t sensorId, uint32_t pid, int64_t samplingPeriodNs, +bool SensorManager::SaveSubscriber(const SensorDescription &sensorDesc, uint32_t pid, int64_t samplingPeriodNs, int64_t maxReportDelayNs) { - SEN_HILOGI("In, sensorId:%{public}d, pid:%{public}u", sensorId, pid); - SensorBasicInfo sensorInfo = GetSensorInfo(sensorId, samplingPeriodNs, maxReportDelayNs); - if (!clientInfo_.UpdateSensorInfo(sensorId, pid, sensorInfo)) { + SEN_HILOGI("In, sensorType:%{public}d, pid:%{public}u", sensorDesc.sensorType, pid); + SensorBasicInfo sensorInfo = GetSensorInfo(sensorDesc, samplingPeriodNs, maxReportDelayNs); + if (!clientInfo_.UpdateSensorInfo(sensorDesc, pid, sensorInfo)) { SEN_HILOGE("UpdateSensorInfo is failed"); return false; } - SEN_HILOGI("Done, sensorId:%{public}d, pid:%{public}u", sensorId, pid); + SEN_HILOGI("Done, sensorType:%{public}d, pid:%{public}u", sensorDesc.sensorType, pid); return true; } -SensorBasicInfo SensorManager::GetSensorInfo(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) +SensorBasicInfo SensorManager::GetSensorInfo(const SensorDescription &sensorDesc, int64_t samplingPeriodNs, + int64_t maxReportDelayNs) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); + SEN_HILOGI("In, sensorType:%{public}d", sensorDesc.sensorType); SensorBasicInfo sensorInfo; std::lock_guard sensorMapLock(sensorMapMutex_); - auto it = sensorMap_.find(sensorId); + auto it = sensorMap_.find(sensorDesc); if (it == sensorMap_.end()) { sensorInfo.SetSamplingPeriodNs(samplingPeriodNs); sensorInfo.SetMaxReportDelayNs(maxReportDelayNs); sensorInfo.SetSensorState(true); - SEN_HILOGE("sensorId is invalid"); + SEN_HILOGE("sensorDesc is invalid"); return sensorInfo; } int64_t curSamplingPeriodNs = @@ -142,42 +145,43 @@ SensorBasicInfo SensorManager::GetSensorInfo(int32_t sensorId, int64_t samplingP sensorInfo.SetSamplingPeriodNs(curSamplingPeriodNs); sensorInfo.SetMaxReportDelayNs(curReportDelayNs); sensorInfo.SetSensorState(true); - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + SEN_HILOGI("Done, sensorType:%{public}d", sensorDesc.sensorType); return sensorInfo; } -bool SensorManager::IsOtherClientUsingSensor(int32_t sensorId, int32_t clientPid) +bool SensorManager::IsOtherClientUsingSensor(const SensorDescription &sensorDesc, int32_t clientPid) { - SEN_HILOGI("In, sensorId:%{public}d, clientPid:%{public}d", sensorId, clientPid); - if (clientInfo_.OnlyCurPidSensorEnabled(sensorId, clientPid)) { + SEN_HILOGI("In, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d, clientPid:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, clientPid); + if (clientInfo_.OnlyCurPidSensorEnabled(sensorDesc, clientPid)) { SEN_HILOGD("Only current client using this sensor"); return false; } - clientInfo_.ClearCurPidSensorInfo(sensorId, clientPid); + clientInfo_.ClearCurPidSensorInfo(sensorDesc, clientPid); #ifdef HDF_DRIVERS_INTERFACE_SENSOR - if (!ResetBestSensorParams(sensorId)) { + if (!ResetBestSensorParams(sensorDesc)) { SEN_HILOGW("ResetBestSensorParams is failed"); } #endif // HDF_DRIVERS_INTERFACE_SENSOR SEN_HILOGD("Other client is using this sensor"); - SEN_HILOGI("Done, sensorId:%{public}d, clientPid:%{public}d", sensorId, clientPid); + SEN_HILOGI("Done, sensorType:%{public}d, clientPid:%{public}d", sensorDesc.sensorType, clientPid); return true; } -ErrCode SensorManager::AfterDisableSensor(int32_t sensorId) +ErrCode SensorManager::AfterDisableSensor(const SensorDescription &sensorDesc) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); - clientInfo_.ClearSensorInfo(sensorId); - if (sensorId == PROXIMITY_SENSOR_ID) { + SEN_HILOGI("In, sensorType:%{public}d", sensorDesc.sensorType); + clientInfo_.ClearSensorInfo(sensorDesc); + if (sensorDesc.sensorType == PROXIMITY_SENSOR_ID) { SensorData sensorData; - auto ret = clientInfo_.GetStoreEvent(sensorId, sensorData); + auto ret = clientInfo_.GetStoreEvent(sensorDesc, sensorData); if (ret == ERR_OK) { SEN_HILOGD("Change the default state is far"); sensorData.data[0] = PROXIMITY_FAR; clientInfo_.StoreEvent(sensorData); } } - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + SEN_HILOGI("Done, sensorType:%{public}d", sensorDesc.sensorType); return ERR_OK; } diff --git a/services/src/sensor_power_policy.cpp b/services/src/sensor_power_policy.cpp index e5c817484a6fbdaab421f1a750f1647c7a589ed5..c46b0cce7b0c4bd2b91e8247babaaf2f39070282 100644 --- a/services/src/sensor_power_policy.cpp +++ b/services/src/sensor_power_policy.cpp @@ -35,32 +35,32 @@ SensorHdiConnection &sensorHdiConnection_ = SensorHdiConnection::GetInstance(); #endif // HDF_DRIVERS_INTERFACE_SENSOR } // namespace -bool SensorPowerPolicy::CheckFreezingSensor(int32_t sensorId) +bool SensorPowerPolicy::CheckFreezingSensor(int32_t sensorType) { - return ((sensorId == SENSOR_TYPE_ID_PEDOMETER_DETECTION) || (sensorId == SENSOR_TYPE_ID_PEDOMETER)); + return ((sensorType == SENSOR_TYPE_ID_PEDOMETER_DETECTION) || (sensorType == SENSOR_TYPE_ID_PEDOMETER)); } ErrCode SensorPowerPolicy::SuspendSensors(int32_t pid) { CALL_LOG_ENTER; - std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); - if (sensorIdList.empty()) { + std::vector sensorDescList = clientInfo_.GetSensorIdByPid(pid); + if (sensorDescList.empty()) { SEN_HILOGD("Suspend sensors failed, sensorIdList is empty, pid:%{public}d", pid); return SUSPEND_ERR; } std::lock_guard pidSensorInfoLock(pidSensorInfoMutex_); auto pidSensorInfoIt = pidSensorInfoMap_.find(pid); if (pidSensorInfoIt != pidSensorInfoMap_.end()) { - std::unordered_map sensorInfoMap = pidSensorInfoIt->second; - if (!Suspend(pid, sensorIdList, sensorInfoMap)) { + std::unordered_map sensorInfoMap = pidSensorInfoIt->second; + if (!Suspend(pid, sensorDescList, sensorInfoMap)) { SEN_HILOGE("Suspend part sensors, but some failed, pid:%{public}d", pid); return SUSPEND_ERR; } SEN_HILOGI("Suspend sensors success, pid:%{public}d", pid); return ERR_OK; } - std::unordered_map sensorInfoMap; - auto isAllSuspend = Suspend(pid, sensorIdList, sensorInfoMap); + std::unordered_map sensorInfoMap; + auto isAllSuspend = Suspend(pid, sensorDescList, sensorInfoMap); pidSensorInfoMap_.insert(std::make_pair(pid, sensorInfoMap)); if (!isAllSuspend) { SEN_HILOGE("Suspend all sensors, but some failed, pid:%{public}d", pid); @@ -70,31 +70,32 @@ ErrCode SensorPowerPolicy::SuspendSensors(int32_t pid) return ERR_OK; } -bool SensorPowerPolicy::Suspend(int32_t pid, const std::vector &sensorIdList, - std::unordered_map &sensorInfoMap) +bool SensorPowerPolicy::Suspend(int32_t pid, const std::vector &sensorDescList, + std::unordered_map &sensorInfoMap) { CALL_LOG_ENTER; bool isAllSuspend = true; - for (const auto &sensorId : sensorIdList) { - if (CheckFreezingSensor(sensorId)) { + for (const auto &sensorDesc : sensorDescList) { + if (CheckFreezingSensor(sensorDesc.sensorType)) { SEN_HILOGD("Current sensor is pedometer detection or pedometer, can not suspend"); continue; } - auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); - if (sensorManager_.IsOtherClientUsingSensor(sensorId, pid)) { - SEN_HILOGD("Other client is using this sensor now, cannot suspend, sensorId:%{public}d", sensorId); - sensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); + auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorDesc, pid); + if (sensorManager_.IsOtherClientUsingSensor(sensorDesc, pid)) { + SEN_HILOGD("Other client is using this sensor now, cannot suspend, sensorType:%{public}d", + sensorDesc.sensorType); + sensorInfoMap.insert(std::make_pair(sensorDesc, sensorInfo)); continue; } #ifdef HDF_DRIVERS_INTERFACE_SENSOR - auto ret = sensorHdiConnection_.DisableSensor(sensorId); + auto ret = sensorHdiConnection_.DisableSensor(sensorDesc); if (ret != ERR_OK) { isAllSuspend = false; - SEN_HILOGE("Hdi disable sensor failed, sensorId:%{public}d, ret:%{public}d", sensorId, ret); + SEN_HILOGE("Hdi disable sensor failed, sensorType:%{public}d, ret:%{public}d", sensorDesc.sensorType, ret); } #endif // HDF_DRIVERS_INTERFACE_SENSOR - sensorInfoMap.insert(std::make_pair(sensorId, sensorInfo)); - sensorManager_.AfterDisableSensor(sensorId); + sensorInfoMap.insert(std::make_pair(sensorDesc, sensorInfo)); + sensorManager_.AfterDisableSensor(sensorDesc); } return isAllSuspend; } @@ -109,13 +110,12 @@ ErrCode SensorPowerPolicy::ResumeSensors(int32_t pid) return RESUME_ERR; } bool isAllResume = true; - std::unordered_map sensorInfoMap = pidSensorInfoIt->second; + std::unordered_map sensorInfoMap = pidSensorInfoIt->second; for (auto sensorIt = sensorInfoMap.begin(); sensorIt != sensorInfoMap.end();) { - int32_t sensorId = sensorIt->first; int64_t samplingPeriodNs = sensorIt->second.GetSamplingPeriodNs(); int64_t maxReportDelayNs = sensorIt->second.GetMaxReportDelayNs(); - if (!Resume(pid, sensorId, samplingPeriodNs, maxReportDelayNs)) { - SEN_HILOGE("Resume sensor failed, sensorId:%{public}d", sensorId); + if (!Resume(pid, sensorIt->first, samplingPeriodNs, maxReportDelayNs)) { + SEN_HILOGE("Resume sensor failed, sensorType:%{public}d", sensorIt->first.sensorType); isAllResume = false; ++sensorIt; } else { @@ -131,53 +131,53 @@ ErrCode SensorPowerPolicy::ResumeSensors(int32_t pid) return ERR_OK; } -bool SensorPowerPolicy::Resume(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, +bool SensorPowerPolicy::Resume(int32_t pid, const SensorDescription &sensorDesc, int64_t samplingPeriodNs, int64_t maxReportDelayNs) { CALL_LOG_ENTER; - if ((sensorId == INVALID_SENSOR_ID) || (samplingPeriodNs <= 0) || + if ((sensorDesc.sensorType == INVALID_SENSOR_ID) || (samplingPeriodNs <= 0) || ((samplingPeriodNs != 0L) && (maxReportDelayNs / samplingPeriodNs > MAX_EVENT_COUNT))) { - SEN_HILOGE("sensorId is invalid or maxReportDelayNs exceed the maximum value"); + SEN_HILOGE("sensorType is invalid or maxReportDelayNs exceed the maximum value"); return false; } - if (clientInfo_.GetSensorState(sensorId)) { - SEN_HILOGD("Sensor is enable, sensorId:%{public}d", sensorId); - auto ret = RestoreSensorInfo(pid, sensorId, samplingPeriodNs, maxReportDelayNs); + if (clientInfo_.GetSensorState(sensorDesc)) { + SEN_HILOGD("Sensor is enable, sensorType:%{public}d", sensorDesc.sensorType); + auto ret = RestoreSensorInfo(pid, sensorDesc, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { SEN_HILOGE("Restore sensor info failed, ret:%{public}d", ret); return false; } return true; } - auto ret = RestoreSensorInfo(pid, sensorId, samplingPeriodNs, maxReportDelayNs); + auto ret = RestoreSensorInfo(pid, sensorDesc, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { SEN_HILOGE("Restore sensor info failed, ret:%{public}d", ret); return false; } #ifdef HDF_DRIVERS_INTERFACE_SENSOR - ret = sensorHdiConnection_.EnableSensor(sensorId); + ret = sensorHdiConnection_.EnableSensor(sensorDesc); if (ret != ERR_OK) { - SEN_HILOGE("Hdi enable sensor failed, sensorId:%{public}d, ret:%{public}d", sensorId, ret); - clientInfo_.RemoveSubscriber(sensorId, pid); + SEN_HILOGE("Hdi enable sensor failed, sensorType:%{public}d, ret:%{public}d", sensorDesc.sensorType, ret); + clientInfo_.RemoveSubscriber(sensorDesc, pid); return false; } #endif // HDF_DRIVERS_INTERFACE_SENSOR return true; } -ErrCode SensorPowerPolicy::RestoreSensorInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, +ErrCode SensorPowerPolicy::RestoreSensorInfo(int32_t pid, const SensorDescription &sensorDesc, int64_t samplingPeriodNs, int64_t maxReportDelayNs) { CALL_LOG_ENTER; - if (!sensorManager_.SaveSubscriber(sensorId, pid, samplingPeriodNs, maxReportDelayNs)) { + if (!sensorManager_.SaveSubscriber(sensorDesc, pid, samplingPeriodNs, maxReportDelayNs)) { SEN_HILOGE("SaveSubscriber failed"); return UPDATE_SENSOR_INFO_ERR; } #ifdef HDF_DRIVERS_INTERFACE_SENSOR sensorManager_.StartDataReportThread(); - if (!sensorManager_.SetBestSensorParams(sensorId, samplingPeriodNs, maxReportDelayNs)) { + if (!sensorManager_.SetBestSensorParams(sensorDesc, samplingPeriodNs, maxReportDelayNs)) { SEN_HILOGE("SetBestSensorParams failed"); - clientInfo_.RemoveSubscriber(sensorId, pid); + clientInfo_.RemoveSubscriber(sensorDesc, pid); return SET_SENSOR_CONFIG_ERR; } #endif // HDF_DRIVERS_INTERFACE_SENSOR @@ -218,11 +218,11 @@ std::vector SensorPowerPolicy::GetActiveInfoList(int32_t pid) { CALL_LOG_ENTER; std::vector activeInfoList; - std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); - for (const auto &sensorId : sensorIdList) { - auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); - ActiveInfo activeInfo(pid, sensorId, sensorInfo.GetSamplingPeriodNs(), - sensorInfo.GetMaxReportDelayNs()); + std::vector sensorDescList = clientInfo_.GetSensorIdByPid(pid); + for (const auto &sensorDesc : sensorDescList) { + auto sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorDesc, pid); + ActiveInfo activeInfo(pid, sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorInfo.GetSamplingPeriodNs(), sensorInfo.GetMaxReportDelayNs()); activeInfoList.push_back(activeInfo); } if (activeInfoList.size() > 0) { diff --git a/services/src/sensor_service.cpp b/services/src/sensor_service.cpp index a098d60978ed31a907385d84d8f0084e69d31081..6b4771521a83fd7268301106762c3d5056011770 100644 --- a/services/src/sensor_service.cpp +++ b/services/src/sensor_service.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #ifdef HIVIEWDFX_HISYSEVENT_ENABLE @@ -46,6 +47,7 @@ auto g_sensorService = SensorDelayedSpSingleton::GetInstance(); const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(g_sensorService.GetRefPtr()); constexpr int32_t INVALID_PID = -1; constexpr int64_t MAX_EVENT_COUNT = 1000; +constexpr int32_t SENSOR_ONLINE = 1; std::atomic_bool g_isRegister = false; } // namespace @@ -131,6 +133,9 @@ void SensorService::OnStart() if (!InitSensorList()) { SEN_HILOGE("Init sensor list error"); } + if (!InitPlugCallback()) { + SEN_HILOGE("Init plug callback error"); + } sensorDataProcesser_ = new (std::nothrow) SensorDataProcesser(sensorMap_); CHKPV(sensorDataProcesser_); #endif // HDF_DRIVERS_INTERFACE_SENSOR @@ -170,6 +175,17 @@ bool SensorService::InitInterface() return true; } +bool SensorService::InitPlugCallback() +{ + auto ret = sensorHdiConnection_.RegSensorPlugCallback( + std::bind(&SensorService::ReportPlugEventCallback, this, std::placeholders::_1)); + if (ret != ERR_OK) { + SEN_HILOGE("RegSensorPlugCallback failed"); + return false; + } + return true; +} + bool SensorService::InitDataCallback() { reportDataCallback_ = new (std::nothrow) ReportDataCallback(); @@ -194,7 +210,8 @@ bool SensorService::InitSensorList() { std::lock_guard sensorMapLock(sensorMapMutex_); for (const auto &it : sensors_) { - if (!(sensorMap_.insert(std::make_pair(it.GetSensorId(), it)).second)) { + if (!(sensorMap_.insert(std::pair({ + it.GetDeviceId(), it.GetSensorTypeId(), it.GetSensorId(), it.GetLocation()}, it)).second)) { SEN_HILOGW("sensorMap_ insert failed"); } } @@ -229,7 +246,7 @@ void SensorService::OnStop() #endif // MEMMGR_ENABLE } -void SensorService::ReportSensorSysEvent(int32_t sensorId, bool enable, int32_t pid, int64_t samplingPeriodNs, +void SensorService::ReportSensorSysEvent(int32_t sensorType, bool enable, int32_t pid, int64_t samplingPeriodNs, int64_t maxReportDelayNs) { std::string packageName(""); @@ -242,27 +259,27 @@ void SensorService::ReportSensorSysEvent(int32_t sensorId, bool enable, int32_t if (enable) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::SENSOR, "ENABLE_SENSOR", HiSysEvent::EventType::STATISTIC, - "LEVEL", logLevel, "PKG_NAME", packageName, "TYPE", sensorId, "UID", uid, "PID", pid); + "LEVEL", logLevel, "PKG_NAME", packageName, "TYPE", sensorType, "UID", uid, "PID", pid); #endif // HIVIEWDFX_HISYSEVENT_ENABLE - SEN_HILOGI("PackageName:%{public}s open the sensor, sensorId:%{public}d, pid:%{public}d, " + SEN_HILOGI("PackageName:%{public}s open the sensor, sensorType:%{public}d, pid:%{public}d, " "samplingPeriodNs:%{public}" PRId64 ", samplingPeriodNs:%{public}" PRId64, packageName.c_str(), - sensorId, pid, samplingPeriodNs, maxReportDelayNs); + sensorType, pid, samplingPeriodNs, maxReportDelayNs); } else { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::SENSOR, "DISABLE_SENSOR", HiSysEvent::EventType::STATISTIC, - "LEVEL", logLevel, "TYPE", sensorId, "PKG_NAME", packageName, "UID", uid, "PID", pid); + "LEVEL", logLevel, "TYPE", sensorType, "PKG_NAME", packageName, "UID", uid, "PID", pid); #endif // HIVIEWDFX_HISYSEVENT_ENABLE - SEN_HILOGI("PackageName:%{public}s close the sensor, sensorId:%{public}d, pid:%{public}d", - packageName.c_str(), sensorId, pid); + SEN_HILOGI("PackageName:%{public}s close the sensor, sensorType:%{public}d, pid:%{public}d", + packageName.c_str(), sensorType, pid); } } -void SensorService::ReportOnChangeData(int32_t sensorId) +void SensorService::ReportOnChangeData(const SensorDescription &sensorDesc) { std::lock_guard sensorMapLock(sensorMapMutex_); - auto it = sensorMap_.find(sensorId); + auto it = sensorMap_.find(sensorDesc); if (it == sensorMap_.end()) { - SEN_HILOGE("sensorId is invalid"); + SEN_HILOGE("sensorDesc is invalid"); return; } if ((SENSOR_ON_CHANGE & it->second.GetFlags()) != SENSOR_ON_CHANGE) { @@ -270,7 +287,7 @@ void SensorService::ReportOnChangeData(int32_t sensorId) return; } SensorData sensorData; - auto ret = clientInfo_.GetStoreEvent(sensorId, sensorData); + auto ret = clientInfo_.GetStoreEvent(sensorDesc, sensorData); if (ret != ERR_OK) { SEN_HILOGE("There is no data to be reported"); return; @@ -284,33 +301,38 @@ void SensorService::ReportOnChangeData(int32_t sensorId) } } -ErrCode SensorService::SaveSubscriber(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) +ErrCode SensorService::SaveSubscriber(const SensorDescription &sensorDesc, int64_t samplingPeriodNs, + int64_t maxReportDelayNs) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); - if (!sensorManager_.SaveSubscriber(sensorId, GetCallingPid(), samplingPeriodNs, maxReportDelayNs)) { + SEN_HILOGI("In, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); + if (!sensorManager_.SaveSubscriber(sensorDesc, GetCallingPid(), samplingPeriodNs, maxReportDelayNs)) { SEN_HILOGE("SaveSubscriber failed"); return UPDATE_SENSOR_INFO_ERR; } #ifdef HDF_DRIVERS_INTERFACE_SENSOR sensorManager_.StartDataReportThread(); - SensorBasicInfo sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, GetCallingPid()); - if (!sensorManager_.SetBestSensorParams(sensorId, + SensorBasicInfo sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorDesc, GetCallingPid()); + if (!sensorManager_.SetBestSensorParams(sensorDesc, sensorInfo.GetSamplingPeriodNs(), sensorInfo.GetMaxReportDelayNs())) { SEN_HILOGE("SetBestSensorParams failed"); - clientInfo_.RemoveSubscriber(sensorId, GetCallingPid()); + clientInfo_.RemoveSubscriber(sensorDesc, GetCallingPid()); return SET_SENSOR_CONFIG_ERR; } #endif // HDF_DRIVERS_INTERFACE_SENSOR - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + SEN_HILOGI("Done, deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); return ERR_OK; } -bool SensorService::CheckSensorId(int32_t sensorId) +bool SensorService::CheckSensorId(const SensorDescription &sensorDesc) { std::lock_guard sensorMapLock(sensorMapMutex_); - auto it = sensorMap_.find(sensorId); + auto it = sensorMap_.find(sensorDesc); if (it == sensorMap_.end()) { - SEN_HILOGE("Invalid sensorId, sensorId:%{public}d", sensorId); + SEN_HILOGE("Invalid sensorDesc," + "deviceId:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d, location:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, sensorDesc.location); return false; } return true; @@ -336,134 +358,153 @@ bool SensorService::IsSystemCalling() return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID()); } -ErrCode SensorService::CheckAuthAndParameter(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) +ErrCode SensorService::CheckAuthAndParameter(const SensorDescription &sensorDesc, int64_t samplingPeriodNs, + int64_t maxReportDelayNs) { - if ((sensorId == SENSOR_TYPE_ID_COLOR || sensorId == SENSOR_TYPE_ID_SAR || - sensorId > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE) && - !IsSystemCalling()) { + if (((sensorDesc.sensorType == SENSOR_TYPE_ID_COLOR) || (sensorDesc.sensorType == SENSOR_TYPE_ID_SAR) || + (sensorDesc.sensorType > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE)) && !IsSystemCalling()) { SEN_HILOGE("Permission check failed. A non-system application uses the system API"); return NON_SYSTEM_API; } PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); - int32_t ret = permissionUtil.CheckSensorPermission(GetCallingTokenID(), sensorId); + int32_t ret = permissionUtil.CheckSensorPermission(GetCallingTokenID(), sensorDesc.sensorType); if (ret != PERMISSION_GRANTED) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::SENSOR, "VERIFY_ACCESS_TOKEN_FAIL", HiSysEvent::EventType::SECURITY, "PKG_NAME", "SensorEnableInner", "ERROR_CODE", ret); #endif // HIVIEWDFX_HISYSEVENT_ENABLE - SEN_HILOGE("sensorId:%{public}d grant failed, ret:%{public}d", sensorId, ret); + SEN_HILOGE("sensorType:%{public}d grant failed, ret:%{public}d", sensorDesc.sensorType, ret); return PERMISSION_DENIED; } - if ((!CheckSensorId(sensorId)) || (maxReportDelayNs != 0L && samplingPeriodNs != 0L && + if ((!CheckSensorId(sensorDesc)) || (maxReportDelayNs != 0L && samplingPeriodNs != 0L && ((maxReportDelayNs / samplingPeriodNs) > MAX_EVENT_COUNT))) { - SEN_HILOGE("sensorId is invalid or maxReportDelayNs exceeded the maximum value"); + SEN_HILOGE("sensorDesc is invalid or maxReportDelayNs exceeded the maximum value"); return ERR_NO_INIT; } return ERR_OK; } -ErrCode SensorService::EnableSensor(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) +ErrCode SensorService::EnableSensor(const SensorDescriptionIPC &SensorDescriptionIPC, int64_t samplingPeriodNs, + int64_t maxReportDelayNs) { CALL_LOG_ENTER; - ErrCode checkResult = CheckAuthAndParameter(sensorId, samplingPeriodNs, maxReportDelayNs); + SensorDescription sensorDesc { + .deviceId = SensorDescriptionIPC.deviceId, + .sensorType = SensorDescriptionIPC.sensorType, + .sensorId = SensorDescriptionIPC.sensorId, + .location = SensorDescriptionIPC.location + }; + ErrCode checkResult = CheckAuthAndParameter(sensorDesc, samplingPeriodNs, maxReportDelayNs); if (checkResult != ERR_OK) { return checkResult; } int32_t pid = GetCallingPid(); std::lock_guard serviceLock(serviceLock_); - if (clientInfo_.GetSensorState(sensorId)) { - SEN_HILOGW("Sensor has been enabled already"); - auto ret = SaveSubscriber(sensorId, samplingPeriodNs, maxReportDelayNs); - if (ret != ERR_OK) { - SEN_HILOGE("SaveSubscriber failed"); - return ret; - } - ReportSensorSysEvent(sensorId, true, pid, samplingPeriodNs, maxReportDelayNs); - if (ret != ERR_OK) { - SEN_HILOGE("ret:%{public}d", ret); - } - ReportOnChangeData(sensorId); - if (isReportActiveInfo_) { - ReportActiveInfo(sensorId, pid); - } - PrintSensorData::GetInstance().ResetHdiCounter(sensorId); - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); - return ERR_OK; + if (clientInfo_.GetSensorState(sensorDesc)) { + return SensorReportEvent(sensorDesc, samplingPeriodNs, maxReportDelayNs, pid); } - auto ret = SaveSubscriber(sensorId, samplingPeriodNs, maxReportDelayNs); + auto ret = SaveSubscriber(sensorDesc, samplingPeriodNs, maxReportDelayNs); if (ret != ERR_OK) { SEN_HILOGE("SaveSubscriber failed"); - clientInfo_.RemoveSubscriber(sensorId, GetCallingPid()); + clientInfo_.RemoveSubscriber(sensorDesc, GetCallingPid()); return ret; } #ifdef HDF_DRIVERS_INTERFACE_SENSOR - ret = sensorHdiConnection_.EnableSensor(sensorId); + ret = sensorHdiConnection_.EnableSensor(sensorDesc); if (ret != ERR_OK) { SEN_HILOGE("EnableSensor failed"); - clientInfo_.RemoveSubscriber(sensorId, GetCallingPid()); + clientInfo_.RemoveSubscriber(sensorDesc, GetCallingPid()); return ENABLE_SENSOR_ERR; } #endif // HDF_DRIVERS_INTERFACE_SENSOR - if ((!g_isRegister) && (RegisterPermCallback(sensorId))) { + if ((!g_isRegister) && (RegisterPermCallback(sensorDesc.sensorType))) { g_isRegister = true; } - ReportSensorSysEvent(sensorId, true, pid, samplingPeriodNs, maxReportDelayNs); + ReportSensorSysEvent(sensorDesc.sensorType, true, pid, samplingPeriodNs, maxReportDelayNs); if (isReportActiveInfo_) { - ReportActiveInfo(sensorId, pid); + ReportActiveInfo(sensorDesc, pid); } - PrintSensorData::GetInstance().ResetHdiCounter(sensorId); + PrintSensorData::GetInstance().ResetHdiCounter(sensorDesc.sensorType); return ret; } -ErrCode SensorService::DisableSensor(int32_t sensorId, int32_t pid) +ErrCode SensorService::SensorReportEvent(const SensorDescription &sensorDesc, int64_t samplingPeriodNs, + int64_t maxReportDelayNs, int32_t pid) +{ + SEN_HILOGW("Sensor has been enabled already"); + auto ret = SaveSubscriber(sensorDesc, samplingPeriodNs, maxReportDelayNs); + if (ret != ERR_OK) { + SEN_HILOGE("SaveSubscriber failed"); + return ret; + } + ReportSensorSysEvent(sensorDesc.sensorType, true, pid, samplingPeriodNs, maxReportDelayNs); + if (ret != ERR_OK) { + SEN_HILOGE("ret:%{public}d", ret); + } + ReportOnChangeData(sensorDesc); + if (isReportActiveInfo_) { + ReportActiveInfo(sensorDesc, pid); + } + PrintSensorData::GetInstance().ResetHdiCounter(sensorDesc.sensorType); + SEN_HILOGI("Done, sensorTypeId:%{public}d", sensorDesc.sensorType); + return ERR_OK; +} + +ErrCode SensorService::DisableSensor(const SensorDescription &sensorDesc, int32_t pid) { CALL_LOG_ENTER; - if (!CheckSensorId(sensorId)) { - SEN_HILOGE("sensorId is invalid"); + if (!CheckSensorId(sensorDesc)) { + SEN_HILOGE("sensorDesc is invalid"); return ERR_NO_INIT; } if (pid < 0) { SEN_HILOGE("pid is invalid, pid:%{public}d", pid); return CLIENT_PID_INVALID_ERR; } - ReportSensorSysEvent(sensorId, false, pid); + ReportSensorSysEvent(sensorDesc.sensorType, false, pid); std::lock_guard serviceLock(serviceLock_); - if (sensorManager_.IsOtherClientUsingSensor(sensorId, pid)) { + if (sensorManager_.IsOtherClientUsingSensor(sensorDesc, pid)) { SEN_HILOGW("Other client is using this sensor now, can't disable"); return ERR_OK; } #ifdef HDF_DRIVERS_INTERFACE_SENSOR - if (sensorHdiConnection_.DisableSensor(sensorId) != ERR_OK) { + if (sensorHdiConnection_.DisableSensor(sensorDesc) != ERR_OK) { SEN_HILOGE("DisableSensor is failed"); return DISABLE_SENSOR_ERR; } #endif // HDF_DRIVERS_INTERFACE_SENSOR int32_t uid = clientInfo_.GetUidByPid(pid); clientInfo_.DestroyCmd(uid); - clientInfo_.ClearDataQueue(sensorId); - return sensorManager_.AfterDisableSensor(sensorId); + clientInfo_.ClearDataQueue(sensorDesc); + return sensorManager_.AfterDisableSensor(sensorDesc); } -ErrCode SensorService::DisableSensor(int32_t sensorId) +ErrCode SensorService::DisableSensor(const SensorDescriptionIPC &SensorDescriptionIPC) { CALL_LOG_ENTER; - if ((sensorId == SENSOR_TYPE_ID_COLOR || sensorId == SENSOR_TYPE_ID_SAR || - sensorId > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE) && + SensorDescription sensorDesc { + .deviceId = SensorDescriptionIPC.deviceId, + .sensorType = SensorDescriptionIPC.sensorType, + .sensorId = SensorDescriptionIPC.sensorId, + .location = SensorDescriptionIPC.location + }; + if ((sensorDesc.sensorType == SENSOR_TYPE_ID_COLOR || sensorDesc.sensorType == SENSOR_TYPE_ID_SAR || + sensorDesc.sensorType > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE) && !IsSystemCalling()) { SEN_HILOGE("Permission check failed. A non-system application uses the system API"); return NON_SYSTEM_API; } PermissionUtil &permissionUtil = PermissionUtil::GetInstance(); - int32_t ret = permissionUtil.CheckSensorPermission(GetCallingTokenID(), sensorId); + int32_t ret = permissionUtil.CheckSensorPermission(GetCallingTokenID(), sensorDesc.sensorType); if (ret != PERMISSION_GRANTED) { #ifdef HIVIEWDFX_HISYSEVENT_ENABLE HiSysEventWrite(HiSysEvent::Domain::SENSOR, "VERIFY_ACCESS_TOKEN_FAIL", HiSysEvent::EventType::SECURITY, "PKG_NAME", "SensorDisableInner", "ERROR_CODE", ret); #endif // HIVIEWDFX_HISYSEVENT_ENABLE - SEN_HILOGE("sensorId:%{public}d grant failed, ret:%{public}d", sensorId, ret); + SEN_HILOGE("sensorType:%{public}d grant failed, ret:%{public}d", sensorDesc.sensorType, ret); return PERMISSION_DENIED; } - return DisableSensor(sensorId, GetCallingPid()); + return DisableSensor(sensorDesc, GetCallingPid()); } ErrCode SensorService::GetSensorList(std::vector &sensorList) @@ -480,6 +521,69 @@ ErrCode SensorService::GetSensorList(std::vector &sensorList) return ERR_OK; } +ErrCode SensorService::GetSensorListByDevice(int32_t deviceId, std::vector &singleDevSensors) +{ + CALL_LOG_ENTER; + for (const auto& sensor : sensors_) { + if (sensor.GetDeviceId() == deviceId) { + SEN_HILOGD("Sensor found: GetDeviceId: %{public}d, deviceId: %{public}d", sensor.GetDeviceId(), deviceId); + singleDevSensors.push_back(sensor); + } + } + if (singleDevSensors.empty()) { + std::vector sensors = GetSensorListByDevice(deviceId); + int32_t sensorCount = static_cast(sensors.size()); + for (int32_t i = 0; i < sensorCount; ++i) { + singleDevSensors.push_back(sensors[i]); + } + } + return ERR_OK; +} + +std::vector SensorService::GetSensorListByDevice(int32_t deviceId) +{ + CALL_LOG_ENTER; + std::lock_guard sensorLock(sensorsMutex_); +#ifdef HDF_DRIVERS_INTERFACE_SENSOR + std::vector singleDevSensors; + int32_t ret = sensorHdiConnection_.GetSensorListByDevice(deviceId, singleDevSensors); + if (ret != 0) { + SEN_HILOGE("GetSensorListByDevice is failed"); + return sensors_; + } + for (const auto& newSensor : singleDevSensors) { + bool found = false; + for (auto& oldSensor : sensors_) { + if (oldSensor.GetSensorId() == newSensor.GetSensorId() && + oldSensor.GetDeviceId() == newSensor.GetDeviceId() && + oldSensor.GetSensorTypeId() == newSensor.GetSensorTypeId()) { + SEN_HILOGD("Sensor found in sensorList_"); + found = true; + break; + } + } + if (!found) { + SEN_HILOGD("Sensor not found in sensorList_"); + found = true; + sensors_.push_back(newSensor); + } + } +#endif // HDF_DRIVERS_INTERFACE_SENSOR + + std::lock_guard sensorMapLock(sensorMapMutex_); + for (const auto &it : sensors_) { + auto iter = sensorMap_.find({it.GetDeviceId(), it.GetSensorTypeId(), it.GetSensorId(), it.GetLocation()}); + if (iter != sensorMap_.end()) { + iter->second = it; + } else { + sensorMap_.insert(std::pair( + {it.GetDeviceId(), it.GetSensorTypeId(), it.GetSensorId(), it.GetLocation()}, it)); + sensorDataProcesser_->UpdataSensorMap(sensorMap_); + } + } + return singleDevSensors; +} + std::vector SensorService::GetSensorList() { std::lock_guard sensorLock(sensorsMutex_); @@ -492,7 +596,8 @@ std::vector SensorService::GetSensorList() #endif // HDF_DRIVERS_INTERFACE_SENSOR for (const auto &it : sensors_) { std::lock_guard sensorMapLock(sensorMapMutex_); - sensorMap_.insert(std::make_pair(it.GetSensorId(), it)); + sensorMap_.insert(std::pair({ + it.GetDeviceId(), it.GetSensorTypeId(), it.GetSensorId(), it.GetLocation()}, it)); } return sensors_; } @@ -560,7 +665,7 @@ void SensorService::ProcessDeathObserver(const wptr &object) } POWER_POLICY.DeleteDeathPidSensorInfo(pid); SEN_HILOGI("pid is %{public}d", pid); - std::vector activeSensors = clientInfo_.GetSensorIdByPid(pid); + std::vector activeSensors = clientInfo_.GetSensorIdByPid(pid); for (size_t i = 0; i < activeSensors.size(); ++i) { int32_t ret = DisableSensor(activeSensors[i], pid); if (ret != ERR_OK) { @@ -764,7 +869,7 @@ ErrCode SensorService::ResetSensors() return POWER_POLICY.ResetSensors(); } -void SensorService::ReportActiveInfo(int32_t sensorId, int32_t pid) +void SensorService::ReportActiveInfo(const SensorDescription &sensorDesc, int32_t pid) { CALL_LOG_ENTER; std::vector sessionList; @@ -775,17 +880,17 @@ void SensorService::ReportActiveInfo(int32_t sensorId, int32_t pid) sessionList.push_back(sess); } } - SensorBasicInfo sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorId, pid); - ActiveInfo activeInfo(pid, sensorId, sensorInfo.GetSamplingPeriodNs(), - sensorInfo.GetMaxReportDelayNs()); + SensorBasicInfo sensorInfo = clientInfo_.GetCurPidSensorInfo(sensorDesc, pid); + ActiveInfo activeInfo(pid, sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorInfo.GetSamplingPeriodNs(), sensorInfo.GetMaxReportDelayNs()); POWER_POLICY.ReportActiveInfo(activeInfo, sessionList); } -bool SensorService::RegisterPermCallback(int32_t sensorId) +bool SensorService::RegisterPermCallback(int32_t sensorType) { CALL_LOG_ENTER; - if ((sensorId != SENSOR_TYPE_ID_PEDOMETER) && (sensorId != SENSOR_TYPE_ID_PEDOMETER_DETECTION) && - (sensorId != SENSOR_TYPE_ID_HEART_RATE)) { + if ((sensorType != SENSOR_TYPE_ID_PEDOMETER) && (sensorType != SENSOR_TYPE_ID_PEDOMETER_DETECTION) && + (sensorType != SENSOR_TYPE_ID_HEART_RATE)) { SEN_HILOGD("No need listen for the sensor permission changes"); return false; } @@ -832,5 +937,64 @@ ErrCode SensorService::SetDeviceStatus(uint32_t deviceStatus) clientInfo_.SetDeviceStatus(deviceStatus); return ERR_OK; } + +ErrCode SensorService::TransferClientRemoteObject(const sptr &sensorClient) +{ + CALL_LOG_ENTER; + clientInfo_.SaveSensorClient(sensorClient); + return ERR_OK; +} + +ErrCode SensorService::DestroyClientRemoteObject(const sptr &sensorClient) +{ + CALL_LOG_ENTER; + clientInfo_.DestroySensorClient(sensorClient); + return ERR_OK; +} + +void SensorService::ReportPlugEventCallback(const SensorPlugInfo info) +{ + CALL_LOG_ENTER; + if (info.status == SENSOR_ONLINE) { + auto it = sensorMap_.find({info.deviceSensorInfo.deviceId, info.deviceSensorInfo.sensorType, + info.deviceSensorInfo.sensorId, info.deviceSensorInfo.location}); + if (it == sensorMap_.end()) { + GetSensorListByDevice(info.deviceSensorInfo.deviceId); + } + } else { + if (sensorHdiConnection_.PlugEraseSensorData(info)) { + SEN_HILOGW("sensorHdiConnection Cache update failure"); + } + std::lock_guard sensorMapLock(sensorMapMutex_); + auto it = std::find_if(sensors_.begin(), sensors_.end(), [&](const Sensor& sensor) { + return sensor.GetDeviceId() == info.deviceSensorInfo.deviceId && + sensor.GetSensorTypeId() == info.deviceSensorInfo.sensorType && + sensor.GetSensorId() == info.deviceSensorInfo.sensorId; + }); + if (it != sensors_.end()) { + sensors_.erase(it); + } + auto iter = sensorMap_.find({info.deviceSensorInfo.deviceId, info.deviceSensorInfo.sensorType, + info.deviceSensorInfo.sensorId, info.deviceSensorInfo.location}); + if (iter != sensorMap_.end()) { + sensorMap_.erase(iter); + } + } + struct timeval curTime; + curTime.tv_sec = 0; + curTime.tv_usec = 0; + gettimeofday(&curTime, NULL); + const SensorPlugData sensorPlugData = { + .deviceId = info.deviceSensorInfo.deviceId, + .sensorTypeId = info.deviceSensorInfo.sensorType, + .sensorId = info.deviceSensorInfo.sensorId, + .location = info.deviceSensorInfo.location, + .deviceName = info.deviceName, + .status = info.status, + .reserved = info.reserved, + .timestamp = static_cast(curTime.tv_sec * 1000 + curTime.tv_usec / 1000) //1000:milliSecond + }; + clientInfo_.SendMsgToClient(sensorPlugData); +} } // namespace Sensors } // namespace OHOS diff --git a/test/fuzztest/interfaces/BUILD.gn b/test/fuzztest/interfaces/BUILD.gn index 9012ffc2e03b9d90efffd889f3afa94499f9164c..054343a75a436f4b02ce298d122987d433d99522 100644 --- a/test/fuzztest/interfaces/BUILD.gn +++ b/test/fuzztest/interfaces/BUILD.gn @@ -22,6 +22,7 @@ group("fuzztest") { "register_fuzzer:fuzztest", "resumesensors_fuzzer:fuzztest", "sensoragent_fuzzer:fuzztest", + "sensoragentenhanced_fuzzer:fuzztest", "setdevicestatus_fuzzer:fuzztest", "suspendsensors_fuzzer:fuzztest", "unregister_fuzzer:fuzztest", diff --git a/test/fuzztest/interfaces/getactivesensorinfos_fuzzer/BUILD.gn b/test/fuzztest/interfaces/getactivesensorinfos_fuzzer/BUILD.gn index 209be307bd491b61bc2cfdf758d204edc3e29346..aaae2dd008855adf613fe7548b5b9adecf012a62 100644 --- a/test/fuzztest/interfaces/getactivesensorinfos_fuzzer/BUILD.gn +++ b/test/fuzztest/interfaces/getactivesensorinfos_fuzzer/BUILD.gn @@ -45,6 +45,7 @@ ohos_fuzztest("GetActiveSensorInfosFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", ] } diff --git a/test/fuzztest/interfaces/register_fuzzer/BUILD.gn b/test/fuzztest/interfaces/register_fuzzer/BUILD.gn index 4365a14141985c5d54e48467d973dc0f0435a72f..1bff0bde86e74ec95f65344ec7fe595cc9950f8c 100644 --- a/test/fuzztest/interfaces/register_fuzzer/BUILD.gn +++ b/test/fuzztest/interfaces/register_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("RegisterFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", ] } diff --git a/test/fuzztest/interfaces/resumesensors_fuzzer/BUILD.gn b/test/fuzztest/interfaces/resumesensors_fuzzer/BUILD.gn index 8ab0ebed1d24780c49fcfa635475d2efdf09a393..d509f67a45c559158654b77a67c1e0566bf72726 100644 --- a/test/fuzztest/interfaces/resumesensors_fuzzer/BUILD.gn +++ b/test/fuzztest/interfaces/resumesensors_fuzzer/BUILD.gn @@ -45,6 +45,7 @@ ohos_fuzztest("ResumeSensorsFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", ] } diff --git a/test/fuzztest/interfaces/sensoragent_fuzzer/BUILD.gn b/test/fuzztest/interfaces/sensoragent_fuzzer/BUILD.gn index 104dc41633685588998dd9753d14fa63c0a6ddff..e056db82661cc3c423c93858ceac842051c8d6d5 100644 --- a/test/fuzztest/interfaces/sensoragent_fuzzer/BUILD.gn +++ b/test/fuzztest/interfaces/sensoragent_fuzzer/BUILD.gn @@ -45,6 +45,7 @@ ohos_fuzztest("SensorAgentFuzzTest") { "access_token:libnativetoken", "access_token:libtoken_setproc", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "selinux_adapter:librestorecon", "cJSON:cjson_static", diff --git a/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/BUILD.gn b/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2722a964ae7d874705cf3fecd49111475cf896a3 --- /dev/null +++ b/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../sensor.gni") + +ohos_fuzztest("SensorAgentEnhancedFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = + "$SUBSYSTEM_DIR/test/fuzztest/interfaces/sensoragentenhanced_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/test/fuzztest/interfaces/sensoragentenhanced_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "sensoragentenhanced_fuzzer.cpp" ] + + deps = [ "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", + "hilog:libhilog", + ] +} + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":SensorAgentEnhancedFuzzTest", + ] +} diff --git a/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/corpus/init b/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..e010f5889b59a772ce45fc45b17e8a578984479c --- /dev/null +++ b/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/project.xml b/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..2eb360c27f1b159e1b043e38846f10fcf37fa37c --- /dev/null +++ b/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/sensoragentenhanced_fuzzer.cpp b/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/sensoragentenhanced_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..874156dc5c955f396ea5bb3e1848837e6f09e91a --- /dev/null +++ b/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/sensoragentenhanced_fuzzer.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sensoragentenhanced_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "token_setproc.h" +#include "nativetoken_kit.h" +#include "securec.h" + +#include "sensor_agent.h" +#include "sensor_agent_type.h" +#include "sensor_errors.h" + +namespace OHOS { +namespace Sensors { +using namespace OHOS::HiviewDFX; +using namespace OHOS::Security::AccessToken; +using OHOS::Security::AccessToken::AccessTokenID; +namespace { +constexpr int64_t SAMPLING_INTERVAL = 200000000; +constexpr int64_t REPORT_INTERVAL = 200000000; +constexpr size_t DATA_MIN_SIZE = sizeof(int32_t) + sizeof(SensorIdentifier) + sizeof(SensorUser); +constexpr int32_t SLEEP_TIME = 1000; +} // namespace + +template +size_t GetObject(T &object, const uint8_t *data, size_t size) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +void SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + CHKPV(perms); + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "SensorAgentEnhancedFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +void SensorDataCallbackImpl(SensorEvent *event) +{ + if (event == nullptr) { + return; + } +} + +void SensorAgentEnhancedFuzzTest(const uint8_t *data, size_t size) +{ + if (data == nullptr || size < DATA_MIN_SIZE) { + return; + } + SetUpTestCase(); + size_t startPos = 0; + int32_t deviceId = 0; + GetObject(deviceId, data + startPos, size - startPos); + + SensorIdentifier sensorIdentifier; + GetObject(sensorIdentifier, data + startPos, size - startPos); + + SensorUser user; + user.callback = SensorDataCallbackImpl; + + SensorInfo *sensorInfo = nullptr; + int32_t count = 0; + GetDeviceSensors(deviceId, &sensorInfo, &count); + + SubscribeSensorEnhanced(sensorIdentifier, &user); + SetBatchEnhanced(sensorIdentifier, &user, SAMPLING_INTERVAL, REPORT_INTERVAL); + ActivateSensorEnhanced(sensorIdentifier, &user); + + std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME)); + + DeactivateSensorEnhanced(sensorIdentifier, &user); + UnsubscribeSensorEnhanced(sensorIdentifier, &user); + + SubscribeSensorPlug(&user); + UnsubscribeSensorPlug(&user); +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::Sensors::SensorAgentEnhancedFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/sensoragentenhanced_fuzzer.h b/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/sensoragentenhanced_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..7fd2dc6055ee74f92f0d46726da30dd355e720bd --- /dev/null +++ b/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/sensoragentenhanced_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SENSOR_AGENT_ENHANCED_FUZZER_H +#define SENSOR_AGENT_ENHANCED_FUZZER_H + +#define FUZZ_PROJECT_NAME "sensoragentenhanced_fuzzer" + +#endif + diff --git a/test/fuzztest/interfaces/setdevicestatus_fuzzer/BUILD.gn b/test/fuzztest/interfaces/setdevicestatus_fuzzer/BUILD.gn index 1b330732bf88ddb0cf21356443806694ad04bbf4..54324326486fd8ec9bf87c5c408f2e45f79d1d11 100644 --- a/test/fuzztest/interfaces/setdevicestatus_fuzzer/BUILD.gn +++ b/test/fuzztest/interfaces/setdevicestatus_fuzzer/BUILD.gn @@ -45,6 +45,7 @@ ohos_fuzztest("SetDeviceStatusFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", ] } diff --git a/test/fuzztest/interfaces/suspendsensors_fuzzer/BUILD.gn b/test/fuzztest/interfaces/suspendsensors_fuzzer/BUILD.gn index 7da3d06fce80789fc6d549679151a2b79d1ca670..ac818842c9818addf2a08e97781c0b8c6403d40b 100644 --- a/test/fuzztest/interfaces/suspendsensors_fuzzer/BUILD.gn +++ b/test/fuzztest/interfaces/suspendsensors_fuzzer/BUILD.gn @@ -45,6 +45,7 @@ ohos_fuzztest("SuspendSensorsFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", ] } diff --git a/test/fuzztest/interfaces/unregister_fuzzer/BUILD.gn b/test/fuzztest/interfaces/unregister_fuzzer/BUILD.gn index 35c128bd21a33fbeb9059125bf27bb59c942bb0a..5ce2fe2f363ef69124d72ce82a4ef21950102bad 100644 --- a/test/fuzztest/interfaces/unregister_fuzzer/BUILD.gn +++ b/test/fuzztest/interfaces/unregister_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("UnregisterFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", ] } diff --git a/test/fuzztest/services/BUILD.gn b/test/fuzztest/services/BUILD.gn index e541b0ae5a68a7ded80d41f20a9cbe5e1737271f..55c38be0c6f4a427087be848dd14e2f9b321687a 100644 --- a/test/fuzztest/services/BUILD.gn +++ b/test/fuzztest/services/BUILD.gn @@ -23,6 +23,7 @@ group("fuzztest") { "enableactiveinfocbstub_fuzzer:fuzztest", "getactiveinfoliststub_fuzzer:fuzztest", "getallsensorsstub_fuzzer:fuzztest", + "getsensorlistbydevicestub_fuzzer:fuzztest", "resetsensorsstub_fuzzer:fuzztest", "resumesensorsstub_fuzzer:fuzztest", "sensordisablestub_fuzzer:fuzztest", @@ -30,6 +31,7 @@ group("fuzztest") { "sensoronremoterequest_fuzzer:fuzztest", "service/createsocketchannel_fuzzer:fuzztest", "service/getactiveinfolist_fuzzer:fuzztest", + "service/getsensorlistbydevice_fuzzer:fuzztest", "service/registerclientdeathrecipient_fuzzer:fuzztest", "service/registerpermcallback_fuzzer:fuzztest", "service/reportactiveinfo_fuzzer:fuzztest", @@ -37,5 +39,6 @@ group("fuzztest") { "service/reportsensorsysevent_fuzzer:fuzztest", "service/setdevicestatusservice_fuzzer:fuzztest", "suspendsensorsstub_fuzzer:fuzztest", + "transferclientremoteobjectstub_fuzzer:fuzztest", ] } diff --git a/test/fuzztest/services/createdatachannelstub_fuzzer/BUILD.gn b/test/fuzztest/services/createdatachannelstub_fuzzer/BUILD.gn index 12ef126406c22100d941a9583d087219141f9a31..ba1dda738bc0c882be87562ff7ae6bca994af112 100644 --- a/test/fuzztest/services/createdatachannelstub_fuzzer/BUILD.gn +++ b/test/fuzztest/services/createdatachannelstub_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("CreateDataChannelStubFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/disableactiveinfocbstub_fuzzer/BUILD.gn b/test/fuzztest/services/disableactiveinfocbstub_fuzzer/BUILD.gn index 8add4d57e9c8c45a2ad1dc237b5aab899947291b..dd764d1f5c834bcac2de72725daf6e379e6cf344 100644 --- a/test/fuzztest/services/disableactiveinfocbstub_fuzzer/BUILD.gn +++ b/test/fuzztest/services/disableactiveinfocbstub_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("DisableActiveInfoCBStubFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/enableactiveinfocbstub_fuzzer/BUILD.gn b/test/fuzztest/services/enableactiveinfocbstub_fuzzer/BUILD.gn index 0c2bd42edfa26c05bde8ff99998042ff9470e5da..87ec6ccf5ac68f0922714dcef87834419cdb8f86 100644 --- a/test/fuzztest/services/enableactiveinfocbstub_fuzzer/BUILD.gn +++ b/test/fuzztest/services/enableactiveinfocbstub_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("EnableActiveInfoCBStubFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/getactiveinfoliststub_fuzzer/BUILD.gn b/test/fuzztest/services/getactiveinfoliststub_fuzzer/BUILD.gn index da44777e270c8d58fcec6ad90d49d35fd81a0f18..1803c61a29e2ce2653171a45e085c7319bb3d171 100644 --- a/test/fuzztest/services/getactiveinfoliststub_fuzzer/BUILD.gn +++ b/test/fuzztest/services/getactiveinfoliststub_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("GetActiveInfoListStubFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/getallsensorsstub_fuzzer/BUILD.gn b/test/fuzztest/services/getallsensorsstub_fuzzer/BUILD.gn index c90b3a708a7d80f6626789864cf9b7c53e5a4fe2..170affea6776c93446ed618c76ed327c98cb69c5 100644 --- a/test/fuzztest/services/getallsensorsstub_fuzzer/BUILD.gn +++ b/test/fuzztest/services/getallsensorsstub_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("GetAllSensorsStubFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/BUILD.gn b/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8d0cbaaf14f6c5f5e16cf54c519ecebe696198cb --- /dev/null +++ b/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../sensor.gni") + +ohos_fuzztest("GetSensorListByDeviceStubFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = + "$SUBSYSTEM_DIR/test/fuzztest/services/getsensorlistbydevicestub_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/services/hdi_connection/interface/include", + "$SUBSYSTEM_DIR/services/hdi_connection/adapter/include", + "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include", + "$SUBSYSTEM_DIR/services/include", + "$SUBSYSTEM_DIR/test/fuzztest/services/getsensorlistbydevicestub_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "getsensorlistbydevicestub_fuzzer.cpp" ] + + defines = sensor_default_defines + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/frameworks/native:sensor_service_stub", + "$SUBSYSTEM_DIR/services:libsensor_service_static", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken_shared", + "access_token:libtokensetproc_shared", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "drivers_interface_sensor:libsensor_proxy_3.0", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":GetSensorListByDeviceStubFuzzTest", + ] +} diff --git a/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/corpus/init b/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..65af8ee8d11bf23407ea34d4de49f7cbb6a2b791 --- /dev/null +++ b/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/getsensorlistbydevicestub_fuzzer.cpp b/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/getsensorlistbydevicestub_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..77b68836be0ffbc4974da85b52a4d557f5857d7b --- /dev/null +++ b/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/getsensorlistbydevicestub_fuzzer.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "getsensorlistbydevicestub_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "sensor.h" +#include "sensor_service.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 4; +auto g_service = SensorDelayedSpSingleton::GetInstance(); +const std::u16string SENSOR_INTERFACE_TOKEN = u"ISensorService"; +} // namespace + +void SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "GetSensorListByDeviceStubFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool OnRemoteRequestFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + MessageParcel datas; + datas.WriteInterfaceToken(SENSOR_INTERFACE_TOKEN); + int32_t deviceId = 0; + if (size < sizeof(deviceId)) { + return false; + } + errno_t ret = memcpy_s(&deviceId, sizeof(deviceId), data, sizeof(deviceId)); + if (ret != EOK) { + return false; + } + datas.WriteInt32(deviceId); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + g_service->OnRemoteRequest(static_cast(ISensorServiceIpcCode::COMMAND_GET_SENSOR_LIST_BY_DEVICE), + datas, reply, option); + return true; +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::Sensors::U32_AT_SIZE) { + return 0; + } + + OHOS::Sensors::OnRemoteRequestFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/getsensorlistbydevicestub_fuzzer.h b/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/getsensorlistbydevicestub_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..1e0ef02461f74a722a8742fb5adbcbda01396270 --- /dev/null +++ b/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/getsensorlistbydevicestub_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GET_SENSOR_LIST_BY_DEVICE_STUB_FUZZER_H +#define GET_SENSOR_LIST_BY_DEVICE_STUB_FUZZER_H + +#define FUZZ_PROJECT_NAME "getsensorlistbydevicestub_fuzzer" + +#endif // GET_SENSOR_LIST_BY_DEVICE_STUB_FUZZER_H + diff --git a/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/project.xml b/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..2eb360c27f1b159e1b043e38846f10fcf37fa37c --- /dev/null +++ b/test/fuzztest/services/getsensorlistbydevicestub_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/resetsensorsstub_fuzzer/BUILD.gn b/test/fuzztest/services/resetsensorsstub_fuzzer/BUILD.gn index 91e0e642c195f40e087fc390ec40727e01f325ce..4a4e6204e944666a3bfce124d2c3170fd1698ad3 100644 --- a/test/fuzztest/services/resetsensorsstub_fuzzer/BUILD.gn +++ b/test/fuzztest/services/resetsensorsstub_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("ResetSensorsStubFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/resumesensorsstub_fuzzer/BUILD.gn b/test/fuzztest/services/resumesensorsstub_fuzzer/BUILD.gn index fb32eb606ebedd2dab15075f38812eda52fd271c..89a1f9105e182b20c0cb9ae2484d0dc7a3b9b794 100644 --- a/test/fuzztest/services/resumesensorsstub_fuzzer/BUILD.gn +++ b/test/fuzztest/services/resumesensorsstub_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("ResumeSensorsStubFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/sensordisablestub_fuzzer/BUILD.gn b/test/fuzztest/services/sensordisablestub_fuzzer/BUILD.gn index 1d91b758b9060c096c9e667e00752c4bd285db22..22cc93e4ba2407e2466fcfc6916f5c8e461cad2c 100644 --- a/test/fuzztest/services/sensordisablestub_fuzzer/BUILD.gn +++ b/test/fuzztest/services/sensordisablestub_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("SensorDisableStubFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/sensordisablestub_fuzzer/sensordisablestub_fuzzer.cpp b/test/fuzztest/services/sensordisablestub_fuzzer/sensordisablestub_fuzzer.cpp index e3aee833be21110ab7fd5b03f11a72581ec3e5d8..b0175ad58a1f2dbd07e80969a8dc7bf5f8d33e19 100644 --- a/test/fuzztest/services/sensordisablestub_fuzzer/sensordisablestub_fuzzer.cpp +++ b/test/fuzztest/services/sensordisablestub_fuzzer/sensordisablestub_fuzzer.cpp @@ -81,10 +81,16 @@ bool OnRemoteRequestFuzzTest(const uint8_t *data, size_t size) if (g_service == nullptr) { return false; } - g_service->DisableSensor(SENSOR_TYPE_ID_ACCELEROMETER); + int32_t deviceId = 0; + GetObject(deviceId, data, size); int32_t sensorId = 0; GetObject(sensorId, data, size); - g_service->DisableSensor(sensorId); + int32_t location = 0; + GetObject(location, data, size); + g_service->DisableSensor({deviceId, SENSOR_TYPE_ID_ACCELEROMETER, sensorId, location}); + int32_t sensorType = 0; + GetObject(sensorType, data, size); + g_service->DisableSensor({deviceId, sensorType, sensorId, location}); return true; } } // namespace Sensors diff --git a/test/fuzztest/services/sensorenablestub_fuzzer/BUILD.gn b/test/fuzztest/services/sensorenablestub_fuzzer/BUILD.gn index 2480cf832b0852386d432f587e4d7b3a4ed9003c..4dcb036d1183e3f0bbb25d22f0c3e29f599dcecb 100644 --- a/test/fuzztest/services/sensorenablestub_fuzzer/BUILD.gn +++ b/test/fuzztest/services/sensorenablestub_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("SensorEnableStubFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/sensorenablestub_fuzzer/sensorenablestub_fuzzer.cpp b/test/fuzztest/services/sensorenablestub_fuzzer/sensorenablestub_fuzzer.cpp index 58da44efb21d07ca28005e92ceced0e9d6406c56..c49539c2a5e9889cd9a42aa4568c0286e6c7683e 100644 --- a/test/fuzztest/services/sensorenablestub_fuzzer/sensorenablestub_fuzzer.cpp +++ b/test/fuzztest/services/sensorenablestub_fuzzer/sensorenablestub_fuzzer.cpp @@ -83,16 +83,24 @@ bool OnRemoteRequestFuzzTest(const uint8_t *data, size_t size) if (g_service == nullptr) { return false; } - g_service->EnableSensor(SENSOR_TYPE_ID_ACCELEROMETER, g_samplingPeriod, g_maxReportDelay); - g_service->ResetSensors(); size_t startPos = 0; + int32_t deviceId = 0; + startPos += GetObject(deviceId, data + startPos, size - startPos); int32_t sensorId = 0; startPos += GetObject(sensorId, data + startPos, size - startPos); + int32_t location = 0; + startPos += GetObject(location, data + startPos, size - startPos); + g_service->EnableSensor({deviceId, SENSOR_TYPE_ID_ACCELEROMETER, sensorId, location}, + g_samplingPeriod, g_maxReportDelay); + g_service->ResetSensors(); + + int32_t sensorType = 0; + startPos += GetObject(sensorType, data + startPos, size - startPos); int64_t samplingPeriod = 0; startPos += GetObject(samplingPeriod, data + startPos, size - startPos); int64_t maxReportDelay = 0; GetObject(maxReportDelay, data + startPos, size - startPos); - g_service->EnableSensor(sensorId, samplingPeriod, maxReportDelay); + g_service->EnableSensor({deviceId, sensorType, sensorId, location}, samplingPeriod, maxReportDelay); return true; } } // namespace Sensors diff --git a/test/fuzztest/services/sensoronremoterequest_fuzzer/BUILD.gn b/test/fuzztest/services/sensoronremoterequest_fuzzer/BUILD.gn index e7a593a15ba71c235ba0e91f7bb5dca034fce9ec..16ae18902f128eec133f464963638c86d6115330 100644 --- a/test/fuzztest/services/sensoronremoterequest_fuzzer/BUILD.gn +++ b/test/fuzztest/services/sensoronremoterequest_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("SensorOnRemoteRequestFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/service/createsocketchannel_fuzzer/BUILD.gn b/test/fuzztest/services/service/createsocketchannel_fuzzer/BUILD.gn index b5068f0d9a42b74d8fd60bccb4f32394487ab056..185af1011d88f841fcf7313e391a09400e9a0fc6 100644 --- a/test/fuzztest/services/service/createsocketchannel_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/createsocketchannel_fuzzer/BUILD.gn @@ -61,6 +61,7 @@ ohos_fuzztest("CreateSocketChannelFuzzTest") { "access_token:libtoken_setproc", "cJSON:cjson_static", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/service/getactiveinfolist_fuzzer/BUILD.gn b/test/fuzztest/services/service/getactiveinfolist_fuzzer/BUILD.gn index 5c545944be650ee52ffaf6306ee74ee0e1a786b4..e5414610c6036881c45614b2c2930e7aabbd02ae 100644 --- a/test/fuzztest/services/service/getactiveinfolist_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/getactiveinfolist_fuzzer/BUILD.gn @@ -61,6 +61,7 @@ ohos_fuzztest("GetActiveInfoListFuzzTest") { "access_token:libtoken_setproc", "cJSON:cjson_static", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/BUILD.gn b/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e1bda17589b35dd1c42a296f1ef2481ea7baa553 --- /dev/null +++ b/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../../sensor.gni") + +ohos_fuzztest("GetSensorListByDeviceFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/services/service/getsensorlistbydevice_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/services/hdi_connection/interface/include", + "$SUBSYSTEM_DIR/services/hdi_connection/adapter/include", + "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include", + "$SUBSYSTEM_DIR/services/include", + "$SUBSYSTEM_DIR/test/fuzztest/services/service/getsensorlistbydevice_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-Dprivate=public", + "-Dprotected=public", + ] + + sources = [ "getsensorlistbydevice_fuzzer.cpp" ] + + defines = sensor_default_defines + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/frameworks/native:sensor_service_stub", + "$SUBSYSTEM_DIR/services:libsensor_service_static", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "drivers_interface_sensor:libsensor_proxy_3.0", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":GetSensorListByDeviceFuzzTest", + ] +} diff --git a/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/corpus/init b/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..65af8ee8d11bf23407ea34d4de49f7cbb6a2b791 --- /dev/null +++ b/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/getsensorlistbydevice_fuzzer.cpp b/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/getsensorlistbydevice_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bdfa8a20429974f581bd9c8f812beaba38cea123 --- /dev/null +++ b/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/getsensorlistbydevice_fuzzer.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "getsensorlistbydevice_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "sensor.h" +#include "sensor_service.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 4; +auto g_service = SensorDelayedSpSingleton::GetInstance(); +} // namespace + +template +size_t GetObject(T &object, const uint8_t *data, size_t size) +{ + size_t objectSize = sizeof(object); + if (objectSize > size) { + return 0; + } + errno_t ret = memcpy_s(&object, objectSize, data, objectSize); + if (ret != EOK) { + return 0; + } + return objectSize; +} + +void SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "CreateDataChannelStubFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool GetSensorListByDeviceFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + int32_t deviceId = 0; + size_t consumed = GetObject(deviceId, data, size); + if (consumed == 0) { + return false; + } + g_service->GetSensorListByDevice(deviceId); + return true; +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::Sensors::U32_AT_SIZE) { + return 0; + } + + OHOS::Sensors::GetSensorListByDeviceFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/getsensorlistbydevice_fuzzer.h b/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/getsensorlistbydevice_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..8bbaae9c3b23f49579aa8b1ead18d4ae70baf444 --- /dev/null +++ b/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/getsensorlistbydevice_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef RET_SENSOR_LIST_BY_DEVICE_FUZZER_H +#define RET_SENSOR_LIST_BY_DEVICE_FUZZER_H + +#define FUZZ_PROJECT_NAME "getsensorlistbydevice_fuzzer" + +#endif // RET_SENSOR_LIST_BY_DEVICE_FUZZER_H + diff --git a/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/project.xml b/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..2eb360c27f1b159e1b043e38846f10fcf37fa37c --- /dev/null +++ b/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/BUILD.gn b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/BUILD.gn index 2899d0101e576334124f077ba4ee9817e3f4a80d..65ce4de3eb7981293e36bae5d437290306c49368 100644 --- a/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/BUILD.gn @@ -60,6 +60,7 @@ ohos_fuzztest("RegisterClientDeathRecipientFuzzTest") { "access_token:libtoken_setproc", "cJSON:cjson_static", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/service/registerpermcallback_fuzzer/BUILD.gn b/test/fuzztest/services/service/registerpermcallback_fuzzer/BUILD.gn index ea0ebb871abd90598577a60e530619bbac35867f..f3440875c14e9c8b9382347589307dbd6807f735 100644 --- a/test/fuzztest/services/service/registerpermcallback_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/registerpermcallback_fuzzer/BUILD.gn @@ -60,6 +60,7 @@ ohos_fuzztest("RegisterPermCallbackFuzzTest") { "access_token:libtoken_setproc", "cJSON:cjson_static", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/service/reportactiveinfo_fuzzer/BUILD.gn b/test/fuzztest/services/service/reportactiveinfo_fuzzer/BUILD.gn index 41239564270a5002df51ec397e0be96d160e24f6..f73b02ad3ca54686270c461f1f6aca18f0a78a66 100644 --- a/test/fuzztest/services/service/reportactiveinfo_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/reportactiveinfo_fuzzer/BUILD.gn @@ -61,6 +61,7 @@ ohos_fuzztest("ReportActiveInfoFuzzTest") { "access_token:libtoken_setproc", "cJSON:cjson_static", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/service/reportactiveinfo_fuzzer/reportactiveinfo_fuzzer.cpp b/test/fuzztest/services/service/reportactiveinfo_fuzzer/reportactiveinfo_fuzzer.cpp index f597b240baae7de5478f11f662c2a024e708d7ee..48f8cf0c9ad66727b8995d47f56d054d7b2091cd 100644 --- a/test/fuzztest/services/service/reportactiveinfo_fuzzer/reportactiveinfo_fuzzer.cpp +++ b/test/fuzztest/services/service/reportactiveinfo_fuzzer/reportactiveinfo_fuzzer.cpp @@ -78,11 +78,14 @@ bool ReportActiveInfoFuzzTest(const uint8_t *data, size_t size) { SetUpTestCase(); size_t startPos = 0; - int32_t sensorId = 0; - startPos += GetObject(sensorId, data + startPos, size - startPos); + SensorDescription sensorDesc; + startPos += GetObject(sensorDesc.deviceId, data + startPos, size - startPos); + startPos += GetObject(sensorDesc.sensorType, data + startPos, size - startPos); + startPos += GetObject(sensorDesc.sensorId, data + startPos, size - startPos); + startPos += GetObject(sensorDesc.location, data + startPos, size - startPos); int32_t pid = 0; startPos += GetObject(pid, data + startPos, size - startPos); - g_service->ReportActiveInfo(sensorId, pid); + g_service->ReportActiveInfo(sensorDesc, pid); return true; } } // namespace Sensors diff --git a/test/fuzztest/services/service/reportonchangedata_fuzzer/BUILD.gn b/test/fuzztest/services/service/reportonchangedata_fuzzer/BUILD.gn index 7361ca2ddee7c16dc4b04a707e0c65dc470eb23c..e49c4f5afd6b84bf61e4f847cc75775fd822e250 100644 --- a/test/fuzztest/services/service/reportonchangedata_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/reportonchangedata_fuzzer/BUILD.gn @@ -61,6 +61,7 @@ ohos_fuzztest("ReportOnChangeDataFuzzTest") { "access_token:libtoken_setproc", "cJSON:cjson_static", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/service/reportonchangedata_fuzzer/reportonchangedata_fuzzer.cpp b/test/fuzztest/services/service/reportonchangedata_fuzzer/reportonchangedata_fuzzer.cpp index 556f94dcb0627a7f5ce7b70c4ff1baf0963d2be8..08bec1d3bb3a0f9a5ed91ea9b0af2660902aef90 100644 --- a/test/fuzztest/services/service/reportonchangedata_fuzzer/reportonchangedata_fuzzer.cpp +++ b/test/fuzztest/services/service/reportonchangedata_fuzzer/reportonchangedata_fuzzer.cpp @@ -78,9 +78,15 @@ bool ReportOnChangeDataFuzzTest(const uint8_t *data, size_t size) { SetUpTestCase(); g_service->OnStart(); + int32_t deviceId = 0; + GetObject(deviceId, data, size); + int32_t sensorType = 0; + GetObject(sensorType, data, size); int32_t sensorId = 0; GetObject(sensorId, data, size); - g_service->ReportOnChangeData(sensorId); + int32_t location = 0; + GetObject(location, data, size); + g_service->ReportOnChangeData({deviceId, sensorType, sensorId, location}); return true; } } // namespace Sensors diff --git a/test/fuzztest/services/service/reportsensorsysevent_fuzzer/BUILD.gn b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/BUILD.gn index 922d606f0e3d58a3c63a64b6efd07e85be7b9fc1..d26d91ec5e35b3e4c8adedf80beb058332ee988c 100644 --- a/test/fuzztest/services/service/reportsensorsysevent_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/BUILD.gn @@ -60,6 +60,7 @@ ohos_fuzztest("ReportSensorSysEventFuzzTest") { "access_token:libtoken_setproc", "cJSON:cjson_static", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/service/setdevicestatusservice_fuzzer/BUILD.gn b/test/fuzztest/services/service/setdevicestatusservice_fuzzer/BUILD.gn index bd040a6647f8766ec3792f609d1613f3013fbd77..690a4b2d9b139c7df7d4d953d08b498d7855aacc 100644 --- a/test/fuzztest/services/service/setdevicestatusservice_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/setdevicestatusservice_fuzzer/BUILD.gn @@ -60,6 +60,7 @@ ohos_fuzztest("SetDeviceStatusServiceFuzzTest") { "access_token:libtoken_setproc", "cJSON:cjson_static", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/suspendsensorsstub_fuzzer/BUILD.gn b/test/fuzztest/services/suspendsensorsstub_fuzzer/BUILD.gn index eb7123d83c6b3fc34c8c42fc9b257eda40e94cff..bf49c68594dc760a2d214a172aef426545e3336b 100644 --- a/test/fuzztest/services/suspendsensorsstub_fuzzer/BUILD.gn +++ b/test/fuzztest/services/suspendsensorsstub_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("SuspendSensorsStubFuzzTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "drivers_interface_sensor:libsensor_proxy_3.0", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/BUILD.gn b/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2c7a5eb50eaf521be0e736ed69990b94a8de7729 --- /dev/null +++ b/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("./../../../../sensor.gni") + +ohos_fuzztest("TransferClientRemoteObjectStubFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = + "$SUBSYSTEM_DIR/test/fuzztest/services/transferclientremoteobjectstub_fuzzer" + + include_dirs = [ + "$SUBSYSTEM_DIR/frameworks/native/include", + "$SUBSYSTEM_DIR/interfaces/inner_api", + "$SUBSYSTEM_DIR/services/hdi_connection/interface/include", + "$SUBSYSTEM_DIR/services/hdi_connection/adapter/include", + "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include", + "$SUBSYSTEM_DIR/services/include", + "$SUBSYSTEM_DIR/test/fuzztest/services/transferclientremoteobjectstub_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "transferclientremoteobjectstub_fuzzer.cpp" ] + + defines = sensor_default_defines + + deps = [ + "$SUBSYSTEM_DIR/frameworks/native:sensor_interface_native", + "$SUBSYSTEM_DIR/frameworks/native:sensor_service_stub", + "$SUBSYSTEM_DIR/services:libsensor_service_static", + "$SUBSYSTEM_DIR/utils/common:libsensor_utils", + "$SUBSYSTEM_DIR/utils/ipc:libsensor_ipc", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken_shared", + "access_token:libtokensetproc_shared", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "drivers_interface_sensor:libsensor_proxy_3.0", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":TransferClientRemoteObjectStubFuzzTest", + ] +} diff --git a/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/corpus/init b/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..65af8ee8d11bf23407ea34d4de49f7cbb6a2b791 --- /dev/null +++ b/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/project.xml b/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..2eb360c27f1b159e1b043e38846f10fcf37fa37c --- /dev/null +++ b/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/transferclientremoteobjectstub_fuzzer.cpp b/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/transferclientremoteobjectstub_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a680a43ebaa8540b5481c6d4260d17d36c5dbace --- /dev/null +++ b/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/transferclientremoteobjectstub_fuzzer.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "transferclientremoteobjectstub_fuzzer.h" + +#include +#include + +#include "accesstoken_kit.h" +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "securec.h" +#include "token_setproc.h" + +#include "sensor.h" +#include "sensor_service.h" + +namespace OHOS { +namespace Sensors { +using namespace Security::AccessToken; +using Security::AccessToken::AccessTokenID; +namespace { +constexpr size_t U32_AT_SIZE = 4; +auto g_service = SensorDelayedSpSingleton::GetInstance(); +const std::u16string SENSOR_INTERFACE_TOKEN = u"ISensorService"; +} // namespace + +void SetUpTestCase() +{ + const char **perms = new (std::nothrow) const char *[2]; + if (perms == nullptr) { + return; + } + perms[0] = "ohos.permission.ACCELEROMETER"; + perms[1] = "ohos.permission.MANAGE_SENSOR"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "TransferClientRemoteObjectStubFuzzTest", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +bool OnRemoteRequestFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + MessageParcel datas; + datas.WriteInterfaceToken(SENSOR_INTERFACE_TOKEN); + sptr sensorClient = nullptr; + datas.WriteRemoteObject(sensorClient); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + g_service->OnRemoteRequest(static_cast(ISensorServiceIpcCode::COMMAND_TRANSFER_CLIENT_REMOTE_OBJECT), + datas, reply, option); + return true; +} +} // namespace Sensors +} // namespace OHOS + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::Sensors::U32_AT_SIZE) { + return 0; + } + + OHOS::Sensors::OnRemoteRequestFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/transferclientremoteobjectstub_fuzzer.h b/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/transferclientremoteobjectstub_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..6dc60c57f218abaec1d10927cdfef4f93153cc85 --- /dev/null +++ b/test/fuzztest/services/transferclientremoteobjectstub_fuzzer/transferclientremoteobjectstub_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TRANSFER_CLIENT_REMOTE_OBJECT_STUB_FUZZER_H +#define TRANSFER_CLIENT_REMOTE_OBJECT_STUB_FUZZER_H + +#define FUZZ_PROJECT_NAME "transferclientremoteobjectstub_fuzzer" + +#endif // TRANSFER_CLIENT_REMOTE_OBJECT_STUB_FUZZER_H + diff --git a/test/unittest/interfaces/inner_api/sensor_agent_test.cpp b/test/unittest/interfaces/inner_api/sensor_agent_test.cpp index 1c6c640dff4c89dbcfe0ef900ef7a9d0d0db777d..5f587ede38f9db908727747532f75e80060bd56c 100644 --- a/test/unittest/interfaces/inner_api/sensor_agent_test.cpp +++ b/test/unittest/interfaces/inner_api/sensor_agent_test.cpp @@ -39,6 +39,7 @@ namespace { constexpr int32_t SENSOR_ID { 1 }; constexpr int32_t INVALID_VALUE { -1 }; constexpr int32_t DEVICE_STATUS { 0 }; +static int32_t g_localDeviceId = -1; PermissionStateFull g_infoManagerTestState = { .grantFlags = {1}, @@ -140,6 +141,14 @@ void SensorDataCallbackImpl2(SensorEvent *event) accelData->x, accelData->y, accelData->z, event[0].option); } +void SensorDataCallbackImpl3(SensorStatusEvent *statusEvent) +{ + if (statusEvent == nullptr) { + SEN_HILOGE("statusEvent is null"); + return; + } +} + HWTEST_F(SensorAgentTest, GetAllSensorsTest_001, TestSize.Level1) { SEN_HILOGI("GetAllSensorsTest_001 in"); @@ -403,6 +412,9 @@ HWTEST_F(SensorAgentTest, SensorListTest_001, TestSize.Level1) int32_t ret = GetAllSensors(&sensorInfo, &count); ASSERT_EQ(ret, OHOS::Sensors::SUCCESS); for (int32_t i = 0; i < count; ++i) { + if (sensorInfo[i].location == 1) { + g_localDeviceId = sensorInfo[i].deviceId; + } SEN_HILOGD("sensorName:%{public}s, sensorId:%{public}d, minSamplePeriod:%{public}" PRId64 " ns, maxSamplePeriod:%{public}" PRId64 " ns", sensorInfo[i].sensorName, sensorInfo[i].sensorId, sensorInfo[i].minSamplePeriod, sensorInfo[i].maxSamplePeriod); @@ -486,5 +498,163 @@ HWTEST_F(SensorAgentTest, SensorNativeApiTest_005, TestSize.Level1) int32_t ret = SetMode(SENSOR_ID, &user, SENSOR_DEFAULT_MODE); ASSERT_NE(ret, OHOS::Sensors::SUCCESS); } + +HWTEST_F(SensorAgentTest, GetDeviceSensorsTest_001, TestSize.Level1) +{ + SEN_HILOGI("GetDeviceSensorsTest_001 in"); + SensorInfo *sensorInfos { nullptr }; + int32_t count { 0 }; + int32_t deviceId = g_localDeviceId; + int32_t ret = GetDeviceSensors(deviceId, &sensorInfos, &count); + ASSERT_EQ(ret, OHOS::ERR_OK); + ASSERT_EQ(count, 0); +} + +HWTEST_F(SensorAgentTest, GetDeviceSensorsTest_002, TestSize.Level1) +{ + SEN_HILOGI("GetDeviceSensorsTest_002 in"); + SensorInfo *sensorInfos { nullptr }; + int32_t deviceId = g_localDeviceId; + int32_t ret = GetDeviceSensors(deviceId, &sensorInfos, nullptr); + ASSERT_NE(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, SubscribeSensorEnhancedTest_001, TestSize.Level1) +{ + SEN_HILOGI("SubscribeSensorEnhancedTest_001 in"); + SensorIdentifier sensorIdentifier; + int32_t ret = SubscribeSensorEnhanced(sensorIdentifier, nullptr); + ASSERT_NE(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, SubscribeSensorEnhancedTest_002, TestSize.Level1) +{ + SEN_HILOGI("SubscribeSensorEnhancedTest_002 in"); + SensorIdentifier sensorIdentifier { + .deviceId = g_localDeviceId, + .sensorType = 1, + .sensorId = 0, + .location = 1, + }; + SensorUser user; + user.callback = SensorDataCallbackImpl; + int32_t ret = SubscribeSensorEnhanced(sensorIdentifier, &user); + ASSERT_EQ(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, UnsubscribeSensorEnhancedTest_001, TestSize.Level1) +{ + SEN_HILOGI("UnsubscribeSensorEnhancedTest_001 in"); + SensorIdentifier sensorIdentifier { + .deviceId = g_localDeviceId, + .sensorType = 1, + .sensorId = 0, + .location = 1, + }; + SensorUser user; + user.callback = SensorDataCallbackImpl; + int32_t ret = SubscribeSensorEnhanced(sensorIdentifier, &user); + ASSERT_EQ(ret, OHOS::ERR_OK); + ret = SetBatchEnhanced(sensorIdentifier, &user, 100000000, 100000000); + ASSERT_EQ(ret, OHOS::ERR_OK); + ret = ActivateSensorEnhanced(sensorIdentifier, &user); + ASSERT_EQ(ret, OHOS::ERR_OK); + ret = DeactivateSensorEnhanced(sensorIdentifier, &user); + ASSERT_EQ(ret, OHOS::ERR_OK); + ret = UnsubscribeSensorEnhanced(sensorIdentifier, &user); + ASSERT_EQ(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, UnsubscribeSensorEnhancedTest_002, TestSize.Level1) +{ + SEN_HILOGI("UnsubscribeSensorEnhancedTest_002 in"); + SensorIdentifier sensorIdentifier; + int32_t ret = UnsubscribeSensorEnhanced(sensorIdentifier, nullptr); + ASSERT_NE(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, SetBatchEnhancedTest_001, TestSize.Level1) +{ + SEN_HILOGI("SetBatchEnhancedTest_001 in"); + SensorIdentifier sensorIdentifier; + int32_t ret = SetBatchEnhanced(sensorIdentifier, nullptr, 100, 100); + ASSERT_NE(ret, OHOS::ERR_OK); +} + + +HWTEST_F(SensorAgentTest, ActivateSensorEnhancedTest_001, TestSize.Level1) +{ + SEN_HILOGI("ActivateSensorEnhancedTest_001 in"); + SensorIdentifier sensorIdentifier; + int32_t ret = ActivateSensorEnhanced(sensorIdentifier, nullptr); + ASSERT_NE(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, DeactivateSensorEnhancedTest_001, TestSize.Level1) +{ + SEN_HILOGI("DeactivateSensorEnhancedTest_001 in"); + SensorIdentifier sensorIdentifier; + int32_t ret = DeactivateSensorEnhanced(sensorIdentifier, nullptr); + ASSERT_NE(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, SetModeEnhancedTest_001, TestSize.Level1) +{ + SEN_HILOGI("SetModeEnhancedTest_001 in"); + SensorIdentifier sensorIdentifier; + int32_t ret = SetModeEnhanced(sensorIdentifier, nullptr, 1); + ASSERT_NE(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, SetModeEnhancedTest_002, TestSize.Level1) +{ + SEN_HILOGI("SetModeEnhancedTest_002 in"); + SensorIdentifier sensorIdentifier { + .deviceId = g_localDeviceId, + .sensorType = 1, + .sensorId = 0, + .location = 1, + }; + SensorUser user; + user.callback = SensorDataCallbackImpl; + int32_t ret = SubscribeSensorEnhanced(sensorIdentifier, &user); + ASSERT_EQ(ret, OHOS::ERR_OK); + ret = SetModeEnhanced(sensorIdentifier, &user, 1); + ASSERT_EQ(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, SubscribeSensorPlugTest_001, TestSize.Level1) +{ + SEN_HILOGI("SubscribeSensorPlugTest_001 in"); + int32_t ret = SubscribeSensorPlug(nullptr); + ASSERT_NE(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, SubscribeSensorPlugTest_002, TestSize.Level1) +{ + SEN_HILOGI("SubscribeSensorPlugTest_002 in"); + SensorUser user; + user.plugCallback = SensorDataCallbackImpl3; + int32_t ret = SubscribeSensorPlug(&user); + ASSERT_EQ(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, UnsubscribeSensorPlugTest_001, TestSize.Level1) +{ + SEN_HILOGI("UnsubscribeSensorPlugTest_001 in"); + int32_t ret = UnsubscribeSensorPlug(nullptr); + ASSERT_NE(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, UnsubscribeSensorPlugTest_002, TestSize.Level1) +{ + SEN_HILOGI("UnsubscribeSensorPlugTest_002 in"); + SensorUser user; + user.plugCallback = SensorDataCallbackImpl3; + int32_t ret = SubscribeSensorPlug(&user); + ASSERT_EQ(ret, OHOS::ERR_OK); + ret = UnsubscribeSensorPlug(&user); + ASSERT_EQ(ret, OHOS::ERR_OK); +} } // namespace Sensors } // namespace OHOS diff --git a/utils/common/include/active_info.h b/utils/common/include/active_info.h index 9bc1b6f30b5d563eb6514a8480dc6d04bbb1a807..c6fef0236ca7303244b0bc97794aeea64f61808f 100644 --- a/utils/common/include/active_info.h +++ b/utils/common/include/active_info.h @@ -23,10 +23,15 @@ namespace Sensors { class ActiveInfo : public Parcelable { public: ActiveInfo() = default; - ActiveInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + ActiveInfo(int32_t pid, int32_t deviceId, int32_t sensorTypeId, int32_t sensorId, int64_t samplingPeriodNs, + int64_t maxReportDelayNs); ~ActiveInfo() = default; int32_t GetPid() const; void SetPid(int32_t pid); + int32_t GetDeviceId() const; + void SetDeviceId(int32_t deviceId); + int32_t GetSensorTypeId() const; + void SetSensorTypeId(int32_t sensorTypeId); int32_t GetSensorId() const; void SetSensorId(int32_t sensorId); int64_t GetSamplingPeriodNs() const; @@ -38,6 +43,8 @@ public: private: int32_t pid_ { -1 }; + int32_t deviceId_ { -1 }; + int32_t sensorTypeId_ { -1 }; int32_t sensorId_ { -1 }; int64_t samplingPeriodNs_ { -1 }; int64_t maxReportDelayNs_ { -1 }; diff --git a/utils/common/include/print_sensor_data.h b/utils/common/include/print_sensor_data.h index e97d88b59e532f9f200f29d9116d99696ab21b2f..b5c79f59d8a1bf31f167d5b3885eddc1d89aa534 100644 --- a/utils/common/include/print_sensor_data.h +++ b/utils/common/include/print_sensor_data.h @@ -33,8 +33,8 @@ public: virtual ~PrintSensorData() {}; void ControlSensorClientPrint(const RecordSensorCallback callback, const SensorEvent &event); void ControlSensorHdiPrint(const SensorData &sensorData); - void ResetHdiCounter(int32_t sensorId); - bool IsContinuousType(int32_t sensorId); + void ResetHdiCounter(int32_t sensorType); + bool IsContinuousType(int32_t sensorType); void SavePrintUserInfo(const RecordSensorCallback callback); void RemovePrintUserInfo(const RecordSensorCallback callback); void PrintSensorDataLog(const std::string &name, const SensorData &data); @@ -44,7 +44,7 @@ public: private: void PrintClientData(const SensorEvent &event); void PrintHdiData(const SensorData &sensorData); - int32_t GetDataDimension(int32_t sensorId); + int32_t GetDataDimension(int32_t sensorType); void ProcessHdiDFX(const SensorData &sensorData); void ProcessClientDFX(const SensorEvent &event); struct LogPrintInfo { diff --git a/utils/common/include/sensor.h b/utils/common/include/sensor.h index fabc175a591863e6e6a27a4d2bddeefea520d6e1..b2c4d619dd90a79874a38fa90df9d404a443e86a 100644 --- a/utils/common/include/sensor.h +++ b/utils/common/include/sensor.h @@ -18,8 +18,53 @@ #include "parcel.h" +struct SensorDescription { + int32_t deviceId; + int32_t sensorType; + int32_t sensorId; + int32_t location; + bool operator < (const SensorDescription& other) const + { + if (deviceId != other.deviceId) return deviceId < other.deviceId; + if (sensorType != other.sensorType) return sensorType < other.sensorType; + if (sensorId != other.sensorId) return sensorId < other.sensorId; + return location < other.location; + } + + bool operator == (const SensorDescription& other) const + { + return deviceId == other.deviceId && sensorType == other.sensorType && sensorId == other.sensorId && + location == other.location; + } +}; + +namespace std { + template <> + struct hash { + std::size_t operator()(const SensorDescription& obj) const + { + std::size_t h1 = std::hash{}(obj.deviceId); + std::size_t h2 = std::hash{}(obj.sensorType); + std::size_t h3 = std::hash{}(obj.sensorId); + std::size_t h4 = std::hash{}(obj.location); + + return h1 ^ h2 ^ h3 ^ h4; + } + }; +} + namespace OHOS { namespace Sensors { +struct SensorDescriptionIPC : public Parcelable { + int32_t deviceId; + int32_t sensorType; + int32_t sensorId; + int32_t location; + SensorDescriptionIPC(); + SensorDescriptionIPC(int32_t deviceId, int32_t sensorType, int32_t sensorId, int32_t location); + static SensorDescriptionIPC* Unmarshalling(Parcel &parcel); + bool Marshalling(Parcel &parcel) const; +}; class Sensor : public Parcelable { public: Sensor(); @@ -50,6 +95,10 @@ public: void SetMinSamplePeriodNs(int64_t minSamplePeriodNs); int64_t GetMaxSamplePeriodNs() const; void SetMaxSamplePeriodNs(int64_t maxSamplePeriodNs); + int32_t GetDeviceId() const; + void SetDeviceId(int32_t deviceId); + int32_t GetLocation() const; + void SetLocation(int32_t location); bool ReadFromParcel(Parcel &parcel); static Sensor* Unmarshalling(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; @@ -68,6 +117,8 @@ private: int32_t fifoMaxEventCount_; int64_t minSamplePeriodNs_; int64_t maxSamplePeriodNs_; + int32_t deviceId_; + int32_t location_; }; } // namespace Sensors } // namespace OHOS diff --git a/utils/common/include/sensor_basic_data_channel.h b/utils/common/include/sensor_basic_data_channel.h index 7ad633dad0565685a98db84cc7b9ed74a4aa5ea6..be7c8cb9f72a0bc176d817b079760857c287335d 100644 --- a/utils/common/include/sensor_basic_data_channel.h +++ b/utils/common/include/sensor_basic_data_channel.h @@ -19,7 +19,7 @@ #include #include "message_parcel.h" - +#include "sensor.h" #include "sensor_data_event.h" namespace OHOS { @@ -41,7 +41,7 @@ public: int32_t ReceiveData(ClientExcuteCB callBack, void *vaddr, size_t size); bool GetSensorStatus() const; void SetSensorStatus(bool isActive); - const std::unordered_map &GetDataCacheBuf() const; + const std::unordered_map &GetDataCacheBuf() const; std::string GetPackageName(); void SetPackageName(std::string packageName); @@ -51,7 +51,7 @@ private: int32_t receiveFd_; bool isActive_; std::mutex statusLock_; - std::unordered_map dataCacheBuf_; + std::unordered_map dataCacheBuf_; std::string packageName_; std::mutex pkNameLock_; }; diff --git a/utils/common/include/sensor_channel_info.h b/utils/common/include/sensor_channel_info.h index f988b6784f7f62ead3d84efa7e1f5bb69ef6351e..26a715d5c1273f33b2bd8bcb30b671703454f123 100644 --- a/utils/common/include/sensor_channel_info.h +++ b/utils/common/include/sensor_channel_info.h @@ -28,6 +28,10 @@ public: void SetUid(int32_t uid); std::string GetPackageName() const; void SetPackageName(const std::string &packageName); + int32_t GetDeviceId() const; + void SetDeviceId(int32_t deviceId); + int32_t GetSensorType() const; + void SetSensorType(int32_t sensorType); int32_t GetSensorId() const; void SetSensorId(int32_t sensorId); int64_t GetSamplingPeriodNs() const; @@ -40,6 +44,8 @@ public: private: int32_t uid_; std::string packageName_; + int32_t deviceId_; + int32_t sensorType_; int32_t sensorId_; int64_t samplingPeriodNs_; uint32_t fifoCount_; diff --git a/utils/common/include/sensor_data_event.h b/utils/common/include/sensor_data_event.h index 5f27f2f17936e0c65463bd4ed6b426c9b77addd6..7eea424f070ee0fc20770ac68feed6fecd2e5e96 100755 --- a/utils/common/include/sensor_data_event.h +++ b/utils/common/include/sensor_data_event.h @@ -15,7 +15,7 @@ #ifndef SENSOR_DATA_EVENT_H #define SENSOR_DATA_EVENT_H - +#include namespace OHOS { namespace Sensors { constexpr int32_t RESERVED_DATA_LEN = 3; @@ -38,6 +38,9 @@ struct SensorData { int32_t mode; /**< Sensor data reporting mode (described in {@link SensorMode}) */ uint8_t data[SENSOR_MAX_LENGTH]; /**< Sensor data */ uint32_t dataLen; /**< Sensor data length */ + int32_t deviceId; /**< Device ID */ + int32_t sensorId; /**< Sensor ID */ + int32_t location; /**< Is the device a local device or an external device */ }; struct ExtraInfo { @@ -54,6 +57,17 @@ struct ExtraInfo { struct ExtraSensorInfo { ExtraInfo additional_info; }; + +struct SensorPlugData { + int32_t deviceId; /**< Device ID */ + int32_t sensorTypeId; /**< Sensor type ID */ + int32_t sensorId; /**< Sensor ID */ + int32_t location; /**< Is the device a local device or an external device */ + std::string deviceName; /**< Device name */ + int32_t status; /**< Device on or out status */ + int32_t reserved; /**< Reserved */ + int64_t timestamp; /**< Time when sensor plug data was reported */ +}; } // namespace Sensors } // namespace OHOS #endif // SENSOR_DATA_EVENT_H diff --git a/utils/common/src/active_info.cpp b/utils/common/src/active_info.cpp index abf410dd413de372d19c850429105afc9d21fa78..2a678ec7d29fdf33c97d943a16fa7c38d1a8ac76 100644 --- a/utils/common/src/active_info.cpp +++ b/utils/common/src/active_info.cpp @@ -24,8 +24,10 @@ namespace OHOS { namespace Sensors { using namespace OHOS::HiviewDFX; -ActiveInfo::ActiveInfo(int32_t pid, int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) - :pid_(pid), sensorId_(sensorId), samplingPeriodNs_(samplingPeriodNs), maxReportDelayNs_(maxReportDelayNs) +ActiveInfo::ActiveInfo(int32_t pid, int32_t deviceId, int32_t sensorTypeId, int32_t sensorId, int64_t samplingPeriodNs, + int64_t maxReportDelayNs) + :pid_(pid), deviceId_(deviceId), sensorTypeId_(sensorTypeId), sensorId_(sensorId), + samplingPeriodNs_(samplingPeriodNs), maxReportDelayNs_(maxReportDelayNs) {} int32_t ActiveInfo::GetPid() const @@ -38,6 +40,26 @@ void ActiveInfo::SetPid(int32_t pid) pid_ = pid; } +int32_t ActiveInfo::GetDeviceId() const +{ + return deviceId_; +} + +void ActiveInfo::SetDeviceId(int32_t deviceId) +{ + deviceId_ = deviceId; +} + +int32_t ActiveInfo::GetSensorTypeId() const +{ + return sensorTypeId_; +} + +void ActiveInfo::SetSensorTypeId(int32_t sensorTypeId) +{ + sensorTypeId_ = sensorTypeId; +} + int32_t ActiveInfo::GetSensorId() const { return sensorId_; @@ -74,6 +96,14 @@ bool ActiveInfo::Marshalling(Parcel &parcel) const SEN_HILOGE("Write pid failed"); return false; } + if (!parcel.WriteInt32(deviceId_)) { + SEN_HILOGE("Write deviceId failed"); + return false; + } + if (!parcel.WriteInt32(sensorTypeId_)) { + SEN_HILOGE("Write sensorTypeId failed"); + return false; + } if (!parcel.WriteInt32(sensorId_)) { SEN_HILOGE("Write sensorId failed"); return false; @@ -95,8 +125,11 @@ ActiveInfo* ActiveInfo::Unmarshalling(Parcel &parcel) int32_t sensorId = -1; int64_t samplingPeriodNs = -1; int64_t maxReportDelayNs = -1; + int32_t deviceId = -1; + int32_t sensorTypeId = -1; auto activeInfo = new (std::nothrow) ActiveInfo(); - if (activeInfo == nullptr || !(parcel.ReadInt32(pid) && parcel.ReadInt32(sensorId) && + if (activeInfo == nullptr || !(parcel.ReadInt32(pid) && parcel.ReadInt32(deviceId) && + parcel.ReadInt32(sensorTypeId) && parcel.ReadInt32(sensorId) && parcel.ReadInt64(samplingPeriodNs) && parcel.ReadInt64(maxReportDelayNs))) { SEN_HILOGE("Read from parcel is failed"); if (activeInfo != nullptr) { @@ -106,6 +139,8 @@ ActiveInfo* ActiveInfo::Unmarshalling(Parcel &parcel) return activeInfo; } activeInfo->SetPid(pid); + activeInfo->SetDeviceId(deviceId); + activeInfo->SetSensorTypeId(sensorTypeId); activeInfo->SetSensorId(sensorId); activeInfo->SetSamplingPeriodNs(samplingPeriodNs); activeInfo->SetMaxReportDelayNs(maxReportDelayNs); diff --git a/utils/common/src/print_sensor_data.cpp b/utils/common/src/print_sensor_data.cpp index 0cf8ca6e3c8f1827a4bd02da4834e74444066de6..2f8ef6fb8840ef1220dd27c2fa04f2d0c513d999 100644 --- a/utils/common/src/print_sensor_data.cpp +++ b/utils/common/src/print_sensor_data.cpp @@ -82,7 +82,7 @@ void PrintSensorData::ControlSensorHdiPrint(const SensorData &sensorData) if (sensorData.timestamp - it->second.lastTime >= LOG_INTERVAL) { PrintHdiData(sensorData); it->second.lastTime = sensorData.timestamp; - SEN_HILOGI("sensorId: %{public}d, hdiTimes:%{public}s", sensorData.sensorTypeId, + SEN_HILOGI("sensorType: %{public}d, hdiTimes:%{public}s", sensorData.sensorTypeId, std::to_string(it->second.hdiTimes).c_str()); it->second.hdiTimes = 0; } @@ -92,7 +92,10 @@ void PrintSensorData::ControlSensorHdiPrint(const SensorData &sensorData) void PrintSensorData::PrintHdiData(const SensorData &sensorData) { std::string str; - str += "sensorId: " + std::to_string(sensorData.sensorTypeId) + ", "; + str += "deviceId: " + std::to_string(sensorData.deviceId) + ", "; + str += "sensorType: " + std::to_string(sensorData.sensorTypeId) + ", "; + str += "sensorId: " + std::to_string(sensorData.sensorId) + ", "; + str += "location: " + std::to_string(sensorData.location) + ", "; str += "timestamp: " + std::to_string(sensorData.timestamp / LOG_FORMAT_DIVIDER) + ", "; int32_t dataDim = GetDataDimension(sensorData.sensorTypeId); auto data = reinterpret_cast(sensorData.data); @@ -128,9 +131,9 @@ void PrintSensorData::ProcessHdiDFX(const SensorData &sensorData) #endif // HIVIEWDFX_HISYSEVENT_ENABLE } -int32_t PrintSensorData::GetDataDimension(int32_t sensorId) +int32_t PrintSensorData::GetDataDimension(int32_t sensorType) { - switch (sensorId) { + switch (sensorType) { case SENSOR_TYPE_ID_HALL: case SENSOR_TYPE_ID_PROXIMITY: case SENSOR_TYPE_ID_WEAR_DETECTION: @@ -149,7 +152,7 @@ int32_t PrintSensorData::GetDataDimension(int32_t sensorId) case SENSOR_TYPE_ID_ROTATION_VECTOR: return FOUR_DIMENSION; default: - SEN_HILOGW("Unknown sensorId:%{public}d, size:%{public}d", sensorId, DEFAULT_DIMENSION); + SEN_HILOGW("Unknown sensorType:%{public}d, size:%{public}d", sensorType, DEFAULT_DIMENSION); return DEFAULT_DIMENSION; } } @@ -182,7 +185,7 @@ void PrintSensorData::ControlSensorClientPrint(const RecordSensorCallback callba if (event.timestamp - it->second.lastTime >= LOG_INTERVAL) { PrintClientData(event); it->second.lastTime = event.timestamp; - SEN_HILOGI("sensorId: %{public}d, clientTimes:%{public}s", event.sensorTypeId, + SEN_HILOGI("sensorType: %{public}d, clientTimes:%{public}s", event.sensorTypeId, std::to_string(clientTimes_).c_str()); clientTimes_ = 0; } @@ -192,7 +195,10 @@ void PrintSensorData::ControlSensorClientPrint(const RecordSensorCallback callba void PrintSensorData::PrintClientData(const SensorEvent &event) { std::string str; - str += "sensorId: " + std::to_string(event.sensorTypeId) + ", "; + str += "deviceId: " + std::to_string(event.deviceId) + ", "; + str += "sensorType: " + std::to_string(event.sensorTypeId) + ", "; + str += "sensorId: " + std::to_string(event.sensorId) + ", "; + str += "location: " + std::to_string(event.location) + ", "; str += "timestamp: " + std::to_string(event.timestamp / LOG_FORMAT_DIVIDER) + ", "; int32_t dataDim = GetDataDimension(event.sensorTypeId); auto data = reinterpret_cast(event.data); @@ -228,10 +234,10 @@ void PrintSensorData::ProcessClientDFX(const SensorEvent &event) #endif // HIVIEWDFX_HISYSEVENT_ENABLE } -bool PrintSensorData::IsContinuousType(int32_t sensorId) +bool PrintSensorData::IsContinuousType(int32_t sensorType) { return std::find(g_continuousSensorType.begin(), g_continuousSensorType.end(), - sensorId) != g_continuousSensorType.end(); + sensorType) != g_continuousSensorType.end(); } void PrintSensorData::SavePrintUserInfo(const RecordSensorCallback callback) @@ -258,10 +264,10 @@ void PrintSensorData::RemovePrintUserInfo(const RecordSensorCallback callback) clientLoginfo_.erase(callback); } -void PrintSensorData::ResetHdiCounter(int32_t sensorId) +void PrintSensorData::ResetHdiCounter(int32_t sensorType) { std::lock_guard hdiLoginfoLock(hdiLoginfoMutex_); - auto it = hdiLoginfo_.find(sensorId); + auto it = hdiLoginfo_.find(sensorType); if (it == hdiLoginfo_.end()) { return; } @@ -273,7 +279,10 @@ void PrintSensorData::ResetHdiCounter(int32_t sensorId) void PrintSensorData::PrintSensorDataLog(const std::string &name, const SensorData &data) { std::string str; - str += "sensorId: " + std::to_string(data.sensorTypeId) + ", "; + str += "deviceId: " + std::to_string(data.deviceId) + ", "; + str += "sensorType: " + std::to_string(data.sensorTypeId) + ", "; + str += "sensorId: " + std::to_string(data.sensorId) + ", "; + str += "location: " + std::to_string(data.location) + ", "; str += "timestamp: " + std::to_string(data.timestamp / LOG_FORMAT_DIVIDER) + ", "; int32_t dataDim = GetDataDimension(data.sensorTypeId); auto tempData = reinterpret_cast(data.data); diff --git a/utils/common/src/sensor.cpp b/utils/common/src/sensor.cpp index 68ec8f1685a2837f05c165a9fd02b64ef445c536..f109145359bec9869166829606c7e836acffd4c3 100644 --- a/utils/common/src/sensor.cpp +++ b/utils/common/src/sensor.cpp @@ -37,7 +37,9 @@ Sensor::Sensor() flags_(0), fifoMaxEventCount_(0), minSamplePeriodNs_(0), - maxSamplePeriodNs_(0) + maxSamplePeriodNs_(0), + deviceId_(0), + location_(0) {} int32_t Sensor::GetSensorId() const @@ -170,6 +172,26 @@ void Sensor::SetMaxSamplePeriodNs(int64_t maxSamplePeriodNs) maxSamplePeriodNs_ = maxSamplePeriodNs; } +int32_t Sensor::GetDeviceId() const +{ + return deviceId_; +} + +void Sensor::SetDeviceId(int32_t deviceId) +{ + deviceId_ = deviceId; +} + +int32_t Sensor::GetLocation() const +{ + return location_; +} + +void Sensor::SetLocation(int32_t location) +{ + location_ = location; +} + bool Sensor::Marshalling(Parcel &parcel) const { if (!parcel.WriteInt32(sensorId_)) { @@ -224,6 +246,14 @@ bool Sensor::Marshalling(Parcel &parcel) const SEN_HILOGE("Failed, write maxSamplePeriodNs failed"); return false; } + if (!parcel.WriteInt32(deviceId_)) { + SEN_HILOGE("Failed, write deviceId failed"); + return false; + } + if (!parcel.WriteInt32(location_)) { + SEN_HILOGE("Failed, write location_ failed"); + return false; + } return true; } @@ -252,10 +282,70 @@ bool Sensor::ReadFromParcel(Parcel &parcel) (!parcel.ReadUint32(flags_)) || (!parcel.ReadInt32(fifoMaxEventCount_)) || (!parcel.ReadInt64(minSamplePeriodNs_)) || - (!parcel.ReadInt64(maxSamplePeriodNs_))) { + (!parcel.ReadInt64(maxSamplePeriodNs_)) || + (!parcel.ReadInt32(deviceId_)) || + (!parcel.ReadInt32(location_))) { + return false; + } + return true; +} + +SensorDescriptionIPC::SensorDescriptionIPC() +{} + +SensorDescriptionIPC::SensorDescriptionIPC(int32_t deviceId, int32_t sensorTypeId, int32_t sensorId, int32_t location) + :deviceId(deviceId), sensorType(sensorTypeId), sensorId(sensorId), location(location) +{} + +bool SensorDescriptionIPC::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(deviceId)) { + SEN_HILOGE("Failed, write deviceId failed"); + return false; + } + if (!parcel.WriteInt32(sensorType)) { + SEN_HILOGE("Failed, write sensorTypeId failed"); + return false; + } + if (!parcel.WriteInt32(sensorId)) { + SEN_HILOGE("Failed, write sensorId failed"); + return false; + } + if (!parcel.WriteInt32(location)) { + SEN_HILOGE("Failed, write location_ failed"); return false; } return true; } + +SensorDescriptionIPC* SensorDescriptionIPC::Unmarshalling(Parcel &data) +{ + auto sensorDesc = new (std::nothrow) SensorDescriptionIPC(); + if (sensorDesc == nullptr) { + SEN_HILOGE("Read init capacity failed"); + return nullptr; + } + if (!(data.ReadInt32(sensorDesc->deviceId))) { + SEN_HILOGE("Read deviceId failed"); + sensorDesc = nullptr; + return sensorDesc; + } + if (!(data.ReadInt32(sensorDesc->sensorType))) { + SEN_HILOGE("Read sensorTypeId failed"); + sensorDesc = nullptr; + return sensorDesc; + } + if (!(data.ReadInt32(sensorDesc->sensorId))) { + SEN_HILOGE("Read sensorId failed"); + sensorDesc = nullptr; + return sensorDesc; + } + if (!(data.ReadInt32(sensorDesc->location))) { + SEN_HILOGE("Read location_ failed"); + sensorDesc = nullptr; + return sensorDesc; + } + return sensorDesc; +} } // namespace Sensors } // namespace OHOS diff --git a/utils/common/src/sensor_basic_data_channel.cpp b/utils/common/src/sensor_basic_data_channel.cpp index 857cf0de1e5153ae91a155121db5ecc902357ac5..a2d22155f7562da8200162818501663381cb57a9 100644 --- a/utils/common/src/sensor_basic_data_channel.cpp +++ b/utils/common/src/sensor_basic_data_channel.cpp @@ -278,7 +278,7 @@ int32_t SensorBasicDataChannel::DestroySensorBasicChannel() return ERR_OK; } -const std::unordered_map &SensorBasicDataChannel::GetDataCacheBuf() const +const std::unordered_map &SensorBasicDataChannel::GetDataCacheBuf() const { return dataCacheBuf_; } diff --git a/utils/common/src/sensor_channel_info.cpp b/utils/common/src/sensor_channel_info.cpp index cf308e1989e820938d4720eead158a17534a905d..c12ca4467b7dc42d9dc39e07ca756716eda71a84 100644 --- a/utils/common/src/sensor_channel_info.cpp +++ b/utils/common/src/sensor_channel_info.cpp @@ -17,7 +17,8 @@ namespace OHOS { namespace Sensors { -SensorChannelInfo::SensorChannelInfo() : uid_(0), sensorId_(0), samplingPeriodNs_(0), fifoCount_(0) +SensorChannelInfo::SensorChannelInfo() : uid_(0), deviceId_(0), sensorType_(0), sensorId_(0), samplingPeriodNs_(0), + fifoCount_(0) {} int32_t SensorChannelInfo::GetUid() const @@ -40,6 +41,26 @@ void SensorChannelInfo::SetPackageName(const std::string &packageName) packageName_ = packageName; } +int32_t SensorChannelInfo::GetDeviceId() const +{ + return deviceId_; +} + +void SensorChannelInfo::SetDeviceId(int32_t deviceId) +{ + deviceId_ = deviceId; +} + +int32_t SensorChannelInfo::GetSensorType() const +{ + return sensorType_; +} + +void SensorChannelInfo::SetSensorType(int32_t sensorType) +{ + sensorType_ = sensorType; +} + int32_t SensorChannelInfo::GetSensorId() const { return sensorId_;