From 67b26cc459d5bb389aebda9d0e0e33ddd46eefd0 Mon Sep 17 00:00:00 2001 From: Atsws Date: Fri, 25 Apr 2025 17:18:21 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=8A=A8=E6=80=81=E5=A4=9A?= =?UTF-8?q?=E4=BC=A0=E6=84=9F=E5=99=A8=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: lixiangpeng5 --- .../js/napi/include/async_callback_info.h | 2 + frameworks/js/napi/include/sensor_js.h | 4 +- .../js/napi/include/sensor_napi_utils.h | 1 + frameworks/js/napi/src/sensor_js.cpp | 828 +++++++++++++++--- frameworks/js/napi/src/sensor_napi_utils.cpp | 46 + frameworks/native/ISensorService.idl | 8 +- frameworks/native/include/i_sensor_client.h | 5 + .../native/include/sensor_agent_proxy.h | 35 +- .../native/include/sensor_client_proxy.h | 46 + .../native/include/sensor_client_stub.h | 1 + .../native/include/sensor_service_client.h | 23 +- frameworks/native/src/sensor_agent.cpp | 132 ++- frameworks/native/src/sensor_agent_proxy.cpp | 378 ++++++-- frameworks/native/src/sensor_client_stub.cpp | 48 + .../src/sensor_file_descriptor_listener.cpp | 5 +- .../native/src/sensor_service_client.cpp | 243 ++++- interfaces/inner_api/sensor_agent.h | 118 +++ interfaces/inner_api/sensor_agent_type.h | 31 + services/BUILD.gn | 12 +- .../adapter/include/compatible_connection.h | 12 +- .../adapter/include/hdi_connection.h | 18 +- .../adapter/include/sensor_event_callback.h | 8 +- .../adapter/include/sensor_plug_callback.h | 34 + .../adapter/src/compatible_connection.cpp | 92 +- .../adapter/src/hdi_connection.cpp | 231 ++++- .../adapter/src/sensor_event_callback.cpp | 23 +- .../adapter/src/sensor_plug_callback.cpp | 39 + .../hardware/include/hdi_service_impl.h | 9 +- .../hardware/src/hdi_service_impl.cpp | 69 +- .../include/i_sensor_hdi_connection.h | 15 +- .../interface/include/sensor_hdi_connection.h | 12 +- .../interface/src/sensor_hdi_connection.cpp | 188 +++- services/include/client_info.h | 45 +- services/include/sensor_data_processer.h | 15 +- services/include/sensor_manager.h | 22 +- services/include/sensor_power_policy.h | 12 +- services/include/sensor_service.h | 27 +- services/src/client_info.cpp | 257 ++++-- services/src/sensor_data_processer.cpp | 76 +- services/src/sensor_dump.cpp | 41 +- services/src/sensor_manager.cpp | 76 +- services/src/sensor_power_policy.cpp | 87 +- services/src/sensor_service.cpp | 320 +++++-- test/fuzztest/interfaces/BUILD.gn | 1 + .../getactivesensorinfos_fuzzer/BUILD.gn | 1 + .../interfaces/register_fuzzer/BUILD.gn | 1 + .../interfaces/resumesensors_fuzzer/BUILD.gn | 1 + .../interfaces/sensoragent_fuzzer/BUILD.gn | 1 + .../sensoragentenhanced_fuzzer/BUILD.gn | 60 ++ .../sensoragentenhanced_fuzzer/corpus/init | 14 + .../sensoragentenhanced_fuzzer/project.xml | 25 + .../sensoragentenhanced_fuzzer.cpp | 123 +++ .../sensoragentenhanced_fuzzer.h | 22 + .../setdevicestatus_fuzzer/BUILD.gn | 1 + .../interfaces/suspendsensors_fuzzer/BUILD.gn | 1 + .../interfaces/unregister_fuzzer/BUILD.gn | 1 + test/fuzztest/services/BUILD.gn | 5 + .../createdatachannelstub_fuzzer/BUILD.gn | 1 + .../BUILD.gn | 75 ++ .../corpus/init | 14 + .../destroyclientremoteobjectstub_fuzzer.cpp | 95 ++ .../destroyclientremoteobjectstub_fuzzer.h | 22 + .../project.xml | 25 + .../disableactiveinfocbstub_fuzzer/BUILD.gn | 1 + .../enableactiveinfocbstub_fuzzer/BUILD.gn | 1 + .../getactiveinfoliststub_fuzzer/BUILD.gn | 1 + .../getallsensorsstub_fuzzer/BUILD.gn | 1 + .../getsensorlistbydevicestub_fuzzer/BUILD.gn | 75 ++ .../corpus/init | 14 + .../getsensorlistbydevicestub_fuzzer.cpp | 102 +++ .../getsensorlistbydevicestub_fuzzer.h | 22 + .../project.xml | 25 + .../services/resetsensorsstub_fuzzer/BUILD.gn | 1 + .../resumesensorsstub_fuzzer/BUILD.gn | 1 + .../sensordisablestub_fuzzer/BUILD.gn | 1 + .../services/sensorenablestub_fuzzer/BUILD.gn | 1 + .../sensoronremoterequest_fuzzer/BUILD.gn | 1 + .../createsocketchannel_fuzzer/BUILD.gn | 1 + .../service/getactiveinfolist_fuzzer/BUILD.gn | 1 + .../service/getsensordescname_fuzzer/BUILD.gn | 76 ++ .../getsensordescname_fuzzer/corpus/init | 14 + .../getsensordescname_fuzzer.cpp | 106 +++ .../getsensordescname_fuzzer.h | 22 + .../getsensordescname_fuzzer/project.xml | 25 + .../getsensorlistbydevice_fuzzer/BUILD.gn | 76 ++ .../getsensorlistbydevice_fuzzer/corpus/init | 14 + .../getsensorlistbydevice_fuzzer.cpp | 105 +++ .../getsensorlistbydevice_fuzzer.h | 22 + .../getsensorlistbydevice_fuzzer/project.xml | 25 + .../BUILD.gn | 1 + .../registerpermcallback_fuzzer/BUILD.gn | 1 + .../service/reportactiveinfo_fuzzer/BUILD.gn | 1 + .../reportactiveinfo_fuzzer.cpp | 9 +- .../reportonchangedata_fuzzer/BUILD.gn | 1 + .../reportsensorsysevent_fuzzer/BUILD.gn | 1 + .../setdevicestatusservice_fuzzer/BUILD.gn | 1 + .../suspendsensorsstub_fuzzer/BUILD.gn | 1 + .../BUILD.gn | 75 ++ .../corpus/init | 14 + .../project.xml | 25 + .../transferclientremoteobjectstub_fuzzer.cpp | 95 ++ .../transferclientremoteobjectstub_fuzzer.h | 22 + .../inner_api/sensor_agent_test.cpp | 171 ++++ utils/common/include/active_info.h | 9 +- utils/common/include/sensor.h | 16 + .../include/sensor_basic_data_channel.h | 4 +- utils/common/include/sensor_channel_info.h | 6 + utils/common/include/sensor_data_event.h | 16 +- utils/common/src/active_info.cpp | 41 +- utils/common/src/print_sensor_data.cpp | 15 +- utils/common/src/sensor.cpp | 94 +- .../common/src/sensor_basic_data_channel.cpp | 2 +- utils/common/src/sensor_channel_info.cpp | 23 +- 113 files changed, 4891 insertions(+), 670 deletions(-) create mode 100644 services/hdi_connection/adapter/include/sensor_plug_callback.h create mode 100644 services/hdi_connection/adapter/src/sensor_plug_callback.cpp create mode 100644 test/fuzztest/interfaces/sensoragentenhanced_fuzzer/BUILD.gn create mode 100644 test/fuzztest/interfaces/sensoragentenhanced_fuzzer/corpus/init create mode 100644 test/fuzztest/interfaces/sensoragentenhanced_fuzzer/project.xml create mode 100644 test/fuzztest/interfaces/sensoragentenhanced_fuzzer/sensoragentenhanced_fuzzer.cpp create mode 100644 test/fuzztest/interfaces/sensoragentenhanced_fuzzer/sensoragentenhanced_fuzzer.h create mode 100644 test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/BUILD.gn create mode 100644 test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/corpus/init create mode 100644 test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/destroyclientremoteobjectstub_fuzzer.cpp create mode 100644 test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/destroyclientremoteobjectstub_fuzzer.h create mode 100644 test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/project.xml create mode 100644 test/fuzztest/services/getsensorlistbydevicestub_fuzzer/BUILD.gn create mode 100644 test/fuzztest/services/getsensorlistbydevicestub_fuzzer/corpus/init create mode 100644 test/fuzztest/services/getsensorlistbydevicestub_fuzzer/getsensorlistbydevicestub_fuzzer.cpp create mode 100644 test/fuzztest/services/getsensorlistbydevicestub_fuzzer/getsensorlistbydevicestub_fuzzer.h create mode 100644 test/fuzztest/services/getsensorlistbydevicestub_fuzzer/project.xml create mode 100644 test/fuzztest/services/service/getsensordescname_fuzzer/BUILD.gn create mode 100644 test/fuzztest/services/service/getsensordescname_fuzzer/corpus/init create mode 100644 test/fuzztest/services/service/getsensordescname_fuzzer/getsensordescname_fuzzer.cpp create mode 100644 test/fuzztest/services/service/getsensordescname_fuzzer/getsensordescname_fuzzer.h create mode 100644 test/fuzztest/services/service/getsensordescname_fuzzer/project.xml create mode 100644 test/fuzztest/services/service/getsensorlistbydevice_fuzzer/BUILD.gn create mode 100644 test/fuzztest/services/service/getsensorlistbydevice_fuzzer/corpus/init create mode 100644 test/fuzztest/services/service/getsensorlistbydevice_fuzzer/getsensorlistbydevice_fuzzer.cpp create mode 100644 test/fuzztest/services/service/getsensorlistbydevice_fuzzer/getsensorlistbydevice_fuzzer.h create mode 100644 test/fuzztest/services/service/getsensorlistbydevice_fuzzer/project.xml create mode 100644 test/fuzztest/services/transferclientremoteobjectstub_fuzzer/BUILD.gn create mode 100644 test/fuzztest/services/transferclientremoteobjectstub_fuzzer/corpus/init create mode 100644 test/fuzztest/services/transferclientremoteobjectstub_fuzzer/project.xml create mode 100644 test/fuzztest/services/transferclientremoteobjectstub_fuzzer/transferclientremoteobjectstub_fuzzer.cpp create mode 100644 test/fuzztest/services/transferclientremoteobjectstub_fuzzer/transferclientremoteobjectstub_fuzzer.h diff --git a/frameworks/js/napi/include/async_callback_info.h b/frameworks/js/napi/include/async_callback_info.h index 017ea65a..57dd4a1d 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 5e8b0bac..04420ef8 100644 --- a/frameworks/js/napi/include/sensor_js.h +++ b/frameworks/js/napi/include/sensor_js.h @@ -25,9 +25,9 @@ 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); diff --git a/frameworks/js/napi/include/sensor_napi_utils.h b/frameworks/js/napi/include/sensor_napi_utils.h index cbd70ed3..1b5ce939 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 f1d3140a..c437b3bf 100644 --- a/frameworks/js/napi/src/sensor_js.cpp +++ b/frameworks/js/napi/src/sensor_js.cpp @@ -36,7 +36,13 @@ 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 = 0; +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; @@ -51,16 +57,27 @@ 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 void GetSensorDescName(SensorDescription sensorDesc, std::string &sensorDescName) +{ + sensorDescName = std::to_string(sensorDesc.deviceId) + "#" + std::to_string(sensorDesc.sensorType) + + "#" + std::to_string(sensorDesc.sensorId)+ "#" + std::to_string(sensorDesc.location); + return; +} + +static bool CheckSubscribe(SensorDescription sensorDesc) { std::lock_guard onCallbackLock(g_onMutex); - auto iter = g_onCallbackInfos.find(sensorTypeId); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto iter = g_onCallbackInfos.find(sensorDescName); return iter != g_onCallbackInfos.end(); } @@ -75,7 +92,7 @@ static bool copySensorData(sptr callbackInfo, SensorEvent *ev callbackInfo->data.sensorData.sensorAccuracy = event->option; CHKPF(event->data); if (event->dataLen < sizeof(float)) { - SEN_HILOGE("Event dataLen less than float size"); + SEN_HILOGE("Event dataLen less than float size!"); return false; } auto data = reinterpret_cast(event->data); @@ -98,25 +115,25 @@ 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; + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto iter = g_subscribeCallbacks.find(sensorDescName); + 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]; + std::string sensorDescName; + GetSensorDescName({event->deviceId, event->sensorTypeId, event->sensorId, event->location}, sensorDescName); + auto callbacks = g_subscribeCallbacks[sensorDescName]; for (auto &callback : callbacks) { if (!copySensorData(callback, event)) { SEN_HILOGE("Copy sensor data failed"); @@ -129,12 +146,13 @@ 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]; + std::string sensorDescName; + GetSensorDescName({event->deviceId, event->sensorTypeId, event->sensorId, event->location}, sensorDescName); + auto onCallbackInfos = g_onCallbackInfos[sensorDescName]; for (auto &onCallbackInfo : onCallbackInfos) { if (!copySensorData(onCallbackInfo, event)) { SEN_HILOGE("Copy sensor data failed"); @@ -147,9 +165,10 @@ 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); + std::string sensorDescName; + GetSensorDescName({event->deviceId, event->sensorTypeId, event->sensorId, event->location}, sensorDescName); + auto iter = g_onceCallbackInfos.find(sensorDescName); if (iter == g_onceCallbackInfos.end()) { return; } @@ -164,11 +183,13 @@ static void EmitOnceCallback(SensorEvent *event) } EmitUvEventLoop(std::move(onceCallbackInfo)); } - g_onceCallbackInfos.erase(sensorTypeId); + g_onceCallbackInfos.erase(sensorDescName); - 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 +200,60 @@ 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); + EmitAsyncCallbackWork(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, &user); if (ret != ERR_OK) { SEN_HILOGE("DeactivateSensor failed"); return ret; } - return UnsubscribeSensor(sensorTypeId, &user); + return UnsubscribeSensorEnhanced(sensorDesc, &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, &user); if (ret != ERR_OK) { SEN_HILOGE("SubscribeSensor failed"); return ret; } - ret = SetBatch(sensorTypeId, &user, interval, 0); + ret = SetBatchEnhanced(sensorDesc, &user, interval, 0); if (ret != ERR_OK) { SEN_HILOGE("SetBatch failed"); return ret; } - return ActivateSensor(sensorTypeId, &user); + return ActivateSensorEnhanced(sensorDesc, &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 +293,18 @@ 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); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto iter = g_onceCallbackInfos.find(sensorDescName); + 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[sensorDescName]; for (auto callbackInfo : callbackInfos) { CHKPC(callbackInfo); if (callbackInfo->env != env) { @@ -273,11 +320,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 +332,91 @@ 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::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + std::vector> callbackInfos = g_onceCallbackInfos[sensorDescName]; callbackInfos.push_back(asyncCallbackInfo); - g_onceCallbackInfos[sensorTypeId] = callbackInfos; + g_onceCallbackInfos[sensorDescName] = 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, "sensorId"); + if (!IsMatchType(env, napi_sensorId, napi_number)) { + SEN_HILOGE("sensorId 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 bool GetDeviceInfoParameter(napi_env env, size_t argc, napi_value args, SensorDescription &sensorDesc) +{ + int32_t locationDeviceId = DEFAULT_DEVICE_ID; + if (!GetLocationDeviceId(locationDeviceId)) { + ThrowErr(env, SERVICE_EXCEPTION, "location deviceId fail"); + return false; + } + sensorDesc.deviceId = locationDeviceId; + sensorDesc.sensorId = DEFAULT_SENSOR_ID; + sensorDesc.location = IS_LOCAL_DEVICE; + if (argc >= 3 && IsMatchType(env, args, napi_object)) { + if (!GetDeviceId(env, args, sensorDesc.deviceId)) { + SEN_HILOGW("No deviceId, This device is selected by default"); + sensorDesc.deviceId = locationDeviceId; + } + 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"); + } + } + if (sensorDesc.deviceId != locationDeviceId) { + sensorDesc.location = NON_LOCAL_DEVICE; + } + return true; } 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 +427,40 @@ 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)) { + 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; } - if (!CheckSubscribe(sensorTypeId)) { + if (!GetDeviceInfoParameter(env, argc, args[2], sensorDesc)) { + SEN_HILOGE("location deviceId fail"); + return nullptr; + } + if (!CheckSubscribe(sensorDesc)) { SEN_HILOGD("No subscription to change sensor data, registration is required"); - int32_t ret = SubscribeSensor(sensorTypeId, REPORTING_INTERVAL, DataCallbackImpl); + int32_t ret = SubscribeSensor(sensorDesc, REPORTING_INTERVAL, DataCallbackImpl); if (ret != ERR_OK) { ThrowErr(env, ret, "SubscribeSensor fail"); return nullptr; } } - UpdateOnceCallback(env, sensorTypeId, args[1]); + UpdateOnceCallback(env, sensorDesc, 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); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto iter = g_onCallbackInfos.find(sensorDescName); + 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[sensorDescName]; for (auto callbackInfo : callbackInfos) { CHKPC(callbackInfo); if (callbackInfo->env != env) { @@ -345,11 +476,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 +488,11 @@ 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::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + std::vector> callbackInfos = g_onCallbackInfos[sensorDescName]; callbackInfos.push_back(asyncCallbackInfo); - g_onCallbackInfos[sensorTypeId] = callbackInfos; + g_onCallbackInfos[sensorDescName] = callbackInfos; } static bool GetInterval(napi_env env, napi_value value, int64_t &interval) @@ -390,6 +523,124 @@ 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 GetDeviceIdByDeviceInfo(napi_env env, napi_value value, int32_t &deviceId) +{ + napi_value napiDeviceInfo = GetNamedProperty(env, value, "deviceInfo"); + if (!IsMatchType(env, napiDeviceInfo, napi_object)) { + SEN_HILOGW("deviceInfo failed"); + return false; + } + if (!GetDeviceId(env, napiDeviceInfo, deviceId)) { + return false; + } + return true; +} + +static bool GetSensorIdByDeviceInfo(napi_env env, napi_value value, int32_t &sensorId) +{ + napi_value napiDeviceInfo = GetNamedProperty(env, value, "deviceInfo"); + if (!IsMatchType(env, napiDeviceInfo, napi_object)) { + SEN_HILOGW("deviceInfo failed"); + return false; + } + if (!GetSensorId(env, napiDeviceInfo, sensorId)) { + return false; + } + return true; +} + +static bool GetOptionalParameter(napi_env env, size_t argc, napi_value args, int64_t &interval, + SensorDescription &sensorDesc) +{ + int32_t locationDeviceId = DEFAULT_DEVICE_ID; + if (!GetLocationDeviceId(locationDeviceId)) { + ThrowErr(env, SERVICE_EXCEPTION, "location deviceId fail"); + return false; + } + sensorDesc.deviceId = locationDeviceId; + sensorDesc.sensorId = DEFAULT_SENSOR_ID; + sensorDesc.location = IS_LOCAL_DEVICE; + if (argc >= 3 && IsMatchType(env, args, napi_object)) { + if (!GetInterval(env, args, interval)) { + SEN_HILOGW("Get interval failed"); + } + if (!GetDeviceIdByDeviceInfo(env, args, sensorDesc.deviceId)) { + SEN_HILOGW("No deviceId, This device is selected by default"); + sensorDesc.deviceId = locationDeviceId; + } + if (!GetSensorIdByDeviceInfo(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 != locationDeviceId) { + 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 +652,120 @@ 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[2], 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::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + std::vector> callbackInfos = g_onCallbackInfos[sensorDescName]; for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) { CHKPC(*iter); if ((*iter)->env != env) { @@ -441,18 +776,20 @@ 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(sensorDescName); + return DEFAULT_SUBSCRIBE_SIZE; } - g_onCallbackInfos[sensorTypeId] = callbackInfos; + g_onCallbackInfos[sensorDescName] = 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::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + std::vector> callbackInfos = g_onCallbackInfos[sensorDescName]; for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) { CHKPC(*iter); if ((*iter)->env != env) { @@ -473,45 +810,53 @@ 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(sensorDescName); + return DEFAULT_SUBSCRIBE_SIZE; } - g_onCallbackInfos[sensorTypeId] = callbackInfos; + g_onCallbackInfos[sensorDescName] = callbackInfos; return callbackInfos.size(); } 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; + sensorDesc.sensorType = INVALID_SENSOR_TYPE; + if ((!IsMatchType(env, args[0], napi_number)) || (!GetNativeInt32(env, args[0], sensorDesc.sensorType))) { ThrowErr(env, PARAMETER_ERROR, "Wrong argument type or get number fail"); return nullptr; } - int32_t subscribeSize = -1; + if (!GetDeviceInfoParameter(env, argc, args[2], sensorDesc)) { + SEN_HILOGE("location deviceId fail"); + return nullptr; + } + int32_t subscribeSize = INVALID_SUBSCRIBE_SIZE; if (argc == 1) { - subscribeSize = RemoveAllCallback(env, sensorTypeId); + subscribeSize = RemoveAllCallback(env, sensorDesc); } else if (IsMatchType(env, args[1], napi_undefined) || IsMatchType(env, args[1], napi_null)) { - subscribeSize = RemoveAllCallback(env, sensorTypeId); + subscribeSize = RemoveAllCallback(env, sensorDesc); } else if (IsMatchType(env, args[1], napi_function)) { - subscribeSize = RemoveCallback(env, sensorTypeId, args[1]); + subscribeSize = RemoveCallback(env, sensorDesc, args[1]); } else { ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, args[1] 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 +1436,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 +1492,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 +1527,265 @@ 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 GetSensorListByDevice(napi_env env, napi_callback_info info) +{ + CALL_LOG_ENTER; + size_t argc = 1; + napi_value args[1] = { 0 }; + napi_value thisVar = nullptr; + napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr); + if (status != napi_ok || argc < 0) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return nullptr; + } + int32_t locationDeviceId = DEFAULT_DEVICE_ID; + if (!GetLocationDeviceId(locationDeviceId)) { + ThrowErr(env, SERVICE_EXCEPTION, "location deviceId fail"); + return nullptr; + } + int32_t deviceId = locationDeviceId; + if (IsMatchType(env, args[0], napi_number)) { + if (!GetNativeInt32(env, args[0], deviceId)) { + deviceId = locationDeviceId; + } + } + SensorInfo *sensorInfos = nullptr; + int32_t count = 0; + int32_t ret = GetDeviceSensors(deviceId, &sensorInfos, &count); + sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, GET_SENSOR_LIST); + CHKPP(asyncCallbackInfo); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Get sensor list fail"); + asyncCallbackInfo->type = FAIL; + asyncCallbackInfo->error.code = ret; + } else { + FilteringSensorList(sensorInfos, asyncCallbackInfo->sensorInfos, count); + if (asyncCallbackInfo->sensorInfos.empty()) { + uint32_t targetVersion = 0; + if (GetSelfTargetVersion(targetVersion) && (targetVersion < COMPATIBILITY_CHANGE_VERSION_API12)) { + ThrowErr(env, PARAMETER_ERROR, "The sensor is not supported by the device"); + return nullptr; + } + ThrowErr(env, SENSOR_NO_SUPPORT, "The sensor is not supported by the device"); + return nullptr; + } + } + return EmitAsyncWork(nullptr, asyncCallbackInfo); +} + +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) { + ThrowErr(env, PARAMETER_ERROR, "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)) { + ThrowErr(env, PARAMETER_ERROR, "Failed to obtain the deviceId of the local device"); + return result; + } + } + SensorInfo *sensorInfos = nullptr; + int32_t count = 0; + int32_t ret = GetDeviceSensors(deviceId, &sensorInfos, &count); + if (ret != OHOS::ERR_OK) { + ThrowErr(env, ret, "Get sensor list fail"); + return result; + } + vector sensorInfoVec; + FilteringSensorList(sensorInfos, sensorInfoVec, count); + if (napi_create_array(env, &result) != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "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)) { + ThrowErr(env, PARAMETER_ERROR, "Convert sensor info fail"); + return result; + } + if (napi_set_element(env, result, i, value) != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "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 GetSingleSensorTypeByDevice(napi_env env, napi_callback_info info) +{ + CALL_LOG_ENTER; + size_t argc = 2; + napi_value args[2] = { 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_TYPE; + if (!GetNativeInt32(env, args[0], sensorTypeId)) { + ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get number fail"); + return nullptr; + } + int32_t locationDeviceId = DEFAULT_DEVICE_ID; + if (!GetLocationDeviceId(locationDeviceId)) { + ThrowErr(env, SERVICE_EXCEPTION, "location deviceId fail"); + return nullptr; + } + int32_t deviceId = locationDeviceId; + if (IsMatchType(env, args[1], napi_number)) { + if (!GetNativeInt32(env, args[1], deviceId)) { + deviceId = locationDeviceId; + } + } + SensorInfo *sensorInfos = nullptr; + int32_t count = 0; + int32_t ret = GetDeviceSensors(deviceId, &sensorInfos, &count); + sptr asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, GET_SENSOR_LIST); + CHKPP(asyncCallbackInfo); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("Get sensor list fail"); + asyncCallbackInfo->type = FAIL; + asyncCallbackInfo->error.code = ret; + } else { + FilteringSingleSensorList(sensorInfos, asyncCallbackInfo->sensorInfos, count, sensorTypeId); + if (asyncCallbackInfo->sensorInfos.empty()) { + uint32_t targetVersion = 0; + if (GetSelfTargetVersion(targetVersion) && (targetVersion < COMPATIBILITY_CHANGE_VERSION_API12)) { + ThrowErr(env, PARAMETER_ERROR, "The sensor is not supported by the device"); + return nullptr; + } + ThrowErr(env, SENSOR_NO_SUPPORT, "The sensor is not supported by the device"); + return nullptr; + } + } + return EmitAsyncWork(nullptr, asyncCallbackInfo); +} + +static napi_value GetSingleSensorTypeByDeviceSync(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) { + ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid"); + return result; + } + int32_t sensorTypeId = INVALID_SENSOR_TYPE; + if (!GetNativeInt32(env, args[0], sensorTypeId)) { + ThrowErr(env, PARAMETER_ERROR, "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)) { + ThrowErr(env, PARAMETER_ERROR, "Failed to obtain the deviceId of the local device"); + return result; + } + } + SensorInfo *sensorInfos = nullptr; + int32_t count = 0; + int32_t ret = GetDeviceSensors(deviceId, &sensorInfos, &count); + if (ret != OHOS::ERR_OK) { + ThrowErr(env, ret, "Get sensor list fail"); + return result; + } + vector sensorInfoVec; + FilteringSingleSensorList(sensorInfos, sensorInfoVec, count, sensorTypeId); + if (napi_create_array(env, &result) != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "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)) { + ThrowErr(env, PARAMETER_ERROR, "Convert sensor info fail"); + return result; + } + if (napi_set_element(env, result, i, value) != napi_ok) { + ThrowErr(env, PARAMETER_ERROR, "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 +1810,15 @@ 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); + napi_value napiFail; + CHKCP(RegisterSubscribeCallback(env, args[0], asyncCallbackInfo, napiFail, interval), "register callback failed"); + int32_t deviceId = DEFAULT_DEVICE_ID; + if (!GetLocationDeviceId(deviceId)) { + ThrowErr(env, SERVICE_EXCEPTION, "location deviceId fail"); return nullptr; } - int32_t ret = SubscribeSensor(sensorTypeId, g_samplingPeriod[interval], DataCallbackImpl); + 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 +1826,21 @@ 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::string sensorDescName; + GetSensorDescName({deviceId, sensorTypeId, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE}, sensorDescName); + std::vector> callbackInfos = g_subscribeCallbacks[sensorDescName]; callbackInfos.push_back(asyncCallbackInfo); - g_subscribeCallbacks[sensorTypeId] = callbackInfos; + g_subscribeCallbacks[sensorDescName] = 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::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + std::vector> callbackInfos = g_subscribeCallbacks[sensorDescName]; for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) { CHKPC(*iter); if ((*iter)->env != env) { @@ -1248,7 +1850,7 @@ static bool RemoveSubscribeCallback(napi_env env, int32_t sensorTypeId) iter = callbackInfos.erase(iter); } if (callbackInfos.empty()) { - g_subscribeCallbacks.erase(sensorTypeId); + g_subscribeCallbacks.erase(sensorDescName); return true; } return false; @@ -1265,11 +1867,17 @@ 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)) { + ThrowErr(env, SERVICE_EXCEPTION, "location deviceId fail"); + return nullptr; + } + 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 +2044,10 @@ 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("getSensorListbyDevice", GetSensorListByDevice), + DECLARE_NAPI_FUNCTION("getSensorListbyDeviceSync", GetSensorListByDeviceSync), + DECLARE_NAPI_FUNCTION("getSingleSensorTypebyDevice", GetSingleSensorTypeByDevice), + DECLARE_NAPI_FUNCTION("getSingleSensorTypebyDeviceSync", GetSingleSensorTypeByDeviceSync), 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 66d14d78..5d183e7e 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[0]), "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[0], "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[0], "sensorType", 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[0], "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[0], "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[0], "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[0], "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[0], "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 e1d4ad4b..6e0706a8 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 438a688d..85db6dc4 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(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 7c2353c0..a79a1610 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(SensorDescription sensorDesc, const SensorUser *user); + int32_t DeactivateSensor(SensorDescription sensorDesc, const SensorUser *user); + int32_t SetBatch(SensorDescription sensorDesc, const SensorUser *user, int64_t samplingInterval, + int64_t reportInterval); + int32_t SubscribeSensor(SensorDescription sensorDesc, const SensorUser *user); + int32_t UnsubscribeSensor(SensorDescription sensorDesc, const SensorUser *user); + int32_t SetMode(SensorDescription sensorDesc, const SensorUser *user, int32_t mode); + int32_t SetOption(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(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(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 04b01f56..b1f893d4 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,51 @@ public: explicit SensorClientProxy(const sptr &impl) : IRemoteProxy(impl) {} virtual ~SensorClientProxy() = default; + int32_t ProcessPlugEvent(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; + } + 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 674558e3..3d3e585c 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(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 713ec602..4e0219f8 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(SensorDescription sensorDesc, int64_t samplingPeriod, int64_t maxReportDelay); + int32_t DisableSensor(SensorDescription sensorDesc); int32_t TransferDataChannel(sptr sensorDataChannel); int32_t DestroyDataChannel(); void ProcessDeathObserver(const wptr &object); - bool IsValid(int32_t sensorId); + bool IsValid(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,24 @@ public: void Disconnect(); void HandleNetPacke(NetPacket &pkt); void SetDeviceStatus(uint32_t deviceStatus); + void GetSensorDescName(SensorDescription sensorDesc, std::string &sensorDescName); + void ParseIndex(const std::string &sensorDescName, int32_t &deviceId, int32_t &sensorType, int32_t &sensorId, + int32_t &location); + 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(SensorDescription sensorDesc, int64_t samplingPeriod, int64_t maxReportDelay); + void DeleteSensorInfoItem(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 +77,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 f4088949..9ea66f18 100644 --- a/frameworks/native/src/sensor_agent.cpp +++ b/frameworks/native/src/sensor_agent.cpp @@ -25,6 +25,8 @@ 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; static int32_t NormalizeErrCode(int32_t code) { @@ -54,9 +56,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_HILOGE("The local deviceId cannot be found"); + return SERVICE_EXCEPTION; + } + 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 +83,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_HILOGE("The local deviceId cannot be found"); + return SERVICE_EXCEPTION; + } + 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 +98,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_HILOGE("The local deviceId cannot be found"); + return SERVICE_EXCEPTION; + } + 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 +114,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_HILOGE("The local deviceId cannot be found"); + return SERVICE_EXCEPTION; + } + 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 +129,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_HILOGE("The local deviceId cannot be found"); + return SERVICE_EXCEPTION; + } + 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 +145,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_HILOGE("The local deviceId cannot be found"); + return SERVICE_EXCEPTION; + } + return SENSOR_AGENT_IMPL->SetMode({deviceId, sensorId, DEFAULT_SENSOR_ID, DEFAULT_LOCATION}, user, mode); } int32_t SuspendSensors(int32_t pid) @@ -174,4 +218,80 @@ int32_t ResetSensors() void SetDeviceStatus(uint32_t deviceStatus) { SENSOR_AGENT_IMPL->SetDeviceStatus(deviceStatus); +} + +int32_t ActivateSensorEnhanced(SensorDescription sensorDesc, const SensorUser *user) +{ + int32_t ret = SENSOR_AGENT_IMPL->ActivateSensor(sensorDesc, user); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("ActivateSensor failed"); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t DeactivateSensorEnhanced(SensorDescription sensorDesc, const SensorUser *user) +{ + int32_t ret = SENSOR_AGENT_IMPL->DeactivateSensor(sensorDesc, user); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("DeactivateSensor failed"); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t SetBatchEnhanced(SensorDescription sensorDesc, const SensorUser *user, int64_t samplingInterval, + int64_t reportInterval) +{ + int32_t ret = SENSOR_AGENT_IMPL->SetBatch(sensorDesc, user, samplingInterval, reportInterval); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("SetBatch failed"); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t SubscribeSensorEnhanced(SensorDescription sensorDesc, const SensorUser *user) +{ + int32_t ret = SENSOR_AGENT_IMPL->SubscribeSensor(sensorDesc, user); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("SubscribeSensor failed"); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t UnsubscribeSensorEnhanced(SensorDescription sensorDesc, const SensorUser *user) +{ + int32_t ret = SENSOR_AGENT_IMPL->UnsubscribeSensor(sensorDesc, user); + if (ret != OHOS::ERR_OK) { + SEN_HILOGE("UnsubscribeSensor failed"); + return NormalizeErrCode(ret); + } + return ret; +} + +int32_t SetModeEnhanced(SensorDescription sensorDesc, const SensorUser *user, int32_t mode) +{ + return SENSOR_AGENT_IMPL->SetMode(sensorDesc, 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 dfb11bc2..ed259f37 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,12 @@ SensorAgentProxy::~SensorAgentProxy() ClearSensorInfos(); } -std::set SensorAgentProxy::GetSubscribeUserCallback(int32_t sensorId) +std::set SensorAgentProxy::GetSubscribeUserCallback(SensorDescription sensorDesc) { std::lock_guard subscribeLock(subscribeMutex_); - auto iter = subscribeMap_.find(sensorId); + std::string sensorDescName; + SEN_CLIENT.GetSensorDescName(sensorDesc, sensorDescName); + auto iter = subscribeMap_.find(sensorDescName); if (iter == subscribeMap_.end()) { SEN_HILOGE("Sensor is not subscribed"); return {}; @@ -76,7 +81,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 +163,29 @@ int32_t SensorAgentProxy::DestroySensorDataChannel() return ERR_OK; } -int32_t SensorAgentProxy::ActivateSensor(int32_t sensorId, const SensorUser *user) +int32_t SensorAgentProxy::ActivateSensor(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()) { + std::string sensorDescName; + SEN_CLIENT.GetSensorDescName(sensorDesc, sensorDescName); + if (subscribeMap_.find(sensorDescName) == subscribeMap_.end()) { SEN_HILOGE("Subscribe sensorId first"); return ERROR; } - auto& subscribeSet = subscribeMap_[sensorId]; + auto& subscribeSet = subscribeMap_[sensorDescName]; if (subscribeSet.find(user) == subscribeSet.end()) { SEN_HILOGE("Subscribe user first"); return ERROR; @@ -183,66 +193,73 @@ 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(sensorDescName); } 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(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()) { + std::string sensorDescName; + SEN_CLIENT.GetSensorDescName(sensorDesc, sensorDescName); + if (subscribeMap_.find(sensorDescName) == subscribeMap_.end()) { SEN_HILOGE("Subscribe sensorId first"); return OHOS::Sensors::ERROR; } - auto& subscribeSet = subscribeMap_[sensorId]; + auto& subscribeSet = subscribeMap_[sensorDescName]; if (subscribeSet.find(user) == subscribeSet.end()) { SEN_HILOGE("Subscribe user first"); return OHOS::Sensors::ERROR; } - auto status = unsubscribeMap_[sensorId].insert(user); + auto status = unsubscribeMap_[sensorDescName].insert(user); if (!status.second) { SEN_HILOGE("User has been unsubscribed"); } subscribeSet.erase(user); if (subscribeSet.empty()) { - subscribeMap_.erase(sensorId); + subscribeMap_.erase(sensorDescName); 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, +int32_t SensorAgentProxy::SetBatch(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 +267,13 @@ 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()) { + std::string sensorDescName; + SEN_CLIENT.GetSensorDescName(sensorDesc, sensorDescName); + if (subscribeMap_.find(sensorDescName) == subscribeMap_.end()) { SEN_HILOGE("Subscribe sensorId first"); return OHOS::Sensors::ERROR; } - auto& subscribeSet = subscribeMap_[sensorId]; + auto& subscribeSet = subscribeMap_[sensorDescName]; if (subscribeSet.find(user) == subscribeSet.end()) { SEN_HILOGE("Subscribe user first"); return OHOS::Sensors::ERROR; @@ -264,13 +283,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(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 +301,18 @@ 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); + std::string sensorDescName; + SEN_CLIENT.GetSensorDescName(sensorDesc, sensorDescName); + auto status = subscribeMap_[sensorDescName].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 +322,32 @@ bool SensorAgentProxy::IsSubscribeMapEmpty() const return subscribeMap_.empty(); } -int32_t SensorAgentProxy::UnsubscribeSensor(int32_t sensorId, const SensorUser *user) +int32_t SensorAgentProxy::UnsubscribeSensor(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()) { + std::string sensorDescName; + SEN_CLIENT.GetSensorDescName(sensorDesc, sensorDescName); + if (unsubscribeMap_.find(sensorDescName) == unsubscribeMap_.end()) { SEN_HILOGE("Deactivate sensorId first"); return OHOS::Sensors::ERROR; } - auto& unsubscribeSet = unsubscribeMap_[sensorId]; + auto& unsubscribeSet = unsubscribeMap_[sensorDescName]; 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(sensorDescName); } } std::lock_guard createChannelLock(createChannelMutex_); @@ -331,28 +358,32 @@ 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(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()) { + std::string sensorDescName; + SEN_CLIENT.GetSensorDescName(sensorDesc, sensorDescName); + if (subscribeMap_.find(sensorDescName) == subscribeMap_.end()) { SEN_HILOGE("Subscribe sensorId first"); return OHOS::Sensors::ERROR; } - auto& subscribeSet = subscribeMap_[sensorId]; + auto& subscribeSet = subscribeMap_[sensorDescName]; if (subscribeSet.find(user) == subscribeSet.end()) { SEN_HILOGE("Subscribe user first"); return OHOS::Sensors::ERROR; @@ -418,20 +449,153 @@ 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; + std::unique_ptr sensorInfosPtr(sensorInfoCheck_.sensorInfos); + for (const auto& sensor : singleDevSensors) { + if (FindSensorInfo(sensor.GetDeviceId(), sensor.GetSensorId(), sensor.GetSensorTypeId())) { + SEN_HILOGI("SensorInfo already exists"); + } else { + SEN_HILOGI("SensorInfo NOT FOND"); + size_t newCount = static_cast(sensorInfoCount_) + 1; + if (newCount > MAX_SENSOR_LIST_SIZE) { + SEN_HILOGE("The number of sensors exceeds the maximum value"); + return ERROR; + } + std::unique_ptr newSensorInfos = std::make_unique(newCount); + if (newSensorInfos == nullptr) { + SEN_HILOGE("Failed to allocate memory for newSensorInfos"); + return ERROR; + } + for (int32_t i = 0; i < sensorInfoCount_; ++i) { + newSensorInfos[i] = sensorInfosPtr[i]; + } + SensorInfo* newSensorInfo = &newSensorInfos[sensorInfoCount_]; + UpdateSensorInfo(newSensorInfo, sensor); + sensorInfosPtr = std::move(newSensorInfos); + sensorInfoCount_++; + } + } + sensorInfoCheck_.sensorInfos = sensorInfosPtr.release(); + 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 +753,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(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 6a6f4435..1705b416 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,52 @@ 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; + } + int32_t result = ProcessPlugEvent(info); + reply.WriteInt32(result); + return NO_ERROR; +} + +int32_t SensorClientStub::ProcessPlugEvent(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 074ee3af..ec1a564f 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 b6a257c4..e544c984 100644 --- a/frameworks/native/src/sensor_service_client.cpp +++ b/frameworks/native/src/sensor_service_client.cpp @@ -33,6 +33,7 @@ namespace Sensors { using namespace OHOS::HiviewDFX; namespace { +constexpr int32_t DEFAULT_BASE = 10; #ifdef OHOS_BUILD_ENABLE_RUST extern "C" { void ReadClientPackets(RustStreamBuffer *, OHOS::Sensors::SensorServiceClient *, @@ -55,6 +56,7 @@ SensorServiceClient::~SensorServiceClient() remoteObject->RemoveDeathRecipient(serviceDeathObserver_); } } + DestroyClientRemoteObject(); Disconnect(); } @@ -90,6 +92,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 +108,7 @@ int32_t SensorServiceClient::InitServiceClient() return SENSOR_NATIVE_GET_SERVICE_ERR; } -bool SensorServiceClient::IsValid(int32_t sensorId) +bool SensorServiceClient::IsValid(SensorDescription sensorDesc) { int32_t ret = InitServiceClient(); if (ret != ERR_OK) { @@ -113,14 +120,15 @@ 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(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(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,12 @@ 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()); + SensorDescription sensorDesc; + ParseIndex(it.first, sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location); + int32_t ret = sensorServer_->EnableSensor({sensorDesc.deviceId, + sensorDesc.sensorType, sensorDesc.sensorId, sensorDesc.location}, + it.second.GetSamplingPeriodNs(), it.second.GetMaxReportDelayNs()); WriteHiSysIPCEvent(ISensorServiceIpcCode::COMMAND_ENABLE_SENSOR, ret); } } @@ -264,6 +351,64 @@ void SensorServiceClient::ReenableSensor() CreateSocketChannel(); } +int32_t SensorServiceClient::CreateClientRemoteObject() +{ + CALL_LOG_ENTER; + if (sensorServer_ == nullptr) { + int32_t ret = InitServiceClient(); + if (ret != ERR_OK) { + SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret); + return ret; + } + return ret; + } + return ERR_OK; +} + +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 +450,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 +528,8 @@ void SensorServiceClient::ProcessDeathObserver(const wptr &object ReenableSensor(); } -void SensorServiceClient::UpdateSensorInfoMap(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay) +void SensorServiceClient::UpdateSensorInfoMap(SensorDescription sensorDesc, int64_t samplingPeriod, + int64_t maxReportDelay) { SEN_HILOGI("In"); SensorBasicInfo sensorInfo; @@ -370,16 +537,20 @@ void SensorServiceClient::UpdateSensorInfoMap(int32_t sensorId, int64_t sampling sensorInfo.SetMaxReportDelayNs(maxReportDelay); sensorInfo.SetSensorState(true); std::lock_guard mapLock(mapMutex_); - sensorInfoMap_[sensorId] = sensorInfo; + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + sensorInfoMap_[sensorDescName] = sensorInfo; SEN_HILOGI("Done"); return; } -void SensorServiceClient::DeleteSensorInfoItem(int32_t sensorId) +void SensorServiceClient::DeleteSensorInfoItem(SensorDescription sensorDesc) { SEN_HILOGI("In"); std::lock_guard mapLock(mapMutex_); - auto it = sensorInfoMap_.find(sensorId); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = sensorInfoMap_.find(sensorDescName); if (it != sensorInfoMap_.end()) { sensorInfoMap_.erase(it); } @@ -686,5 +857,49 @@ void SensorServiceClient::SetDeviceStatus(uint32_t deviceStatus) FinishTrace(HITRACE_TAG_SENSORS); #endif // HIVIEWDFX_HITRACE_ENABLE } + +void SensorServiceClient::GetSensorDescName(SensorDescription sensorDesc, std::string &sensorDescName) +{ + sensorDescName = std::to_string(sensorDesc.deviceId) + "#" + std::to_string(sensorDesc.sensorType) + + "#" + std::to_string(sensorDesc.sensorId)+ "#" + std::to_string(sensorDesc.location); + return; +} + +void SensorServiceClient::ParseIndex(const std::string &sensorDescName, int32_t &deviceId, int32_t &sensorType, + int32_t &sensorId, int32_t &location) +{ + size_t first_hash = sensorDescName.find('#'); + size_t second_hash = sensorDescName.find('#', first_hash + 1); + size_t third_hash = sensorDescName.find('#', second_hash + 1); + + deviceId = static_cast(strtol(sensorDescName.substr(0, first_hash).c_str(), nullptr, DEFAULT_BASE)); + sensorType = static_cast(strtol(sensorDescName.substr(first_hash + 1, + second_hash - first_hash - 1).c_str(), nullptr, DEFAULT_BASE)); + sensorId = static_cast(strtol(sensorDescName.substr(second_hash + 1, + third_hash - second_hash - 1).c_str(), nullptr, DEFAULT_BASE)); + location = static_cast(strtol(sensorDescName.substr(third_hash + 1).c_str(), nullptr, DEFAULT_BASE)); + return; +} + +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 6ce08dc7..92d88fe6 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 18 + */ +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 sensorDesc including the sensorid, deviceid, and sensortype required for dynamic multi-sensors, + * see {@link SensorDescription}. + * @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 18 + */ +int32_t SubscribeSensorEnhanced(SensorDescription sensorDesc, const SensorUser *user); + +/** + * @brief Unsubscribes from sensor data. + * + * @param sensorDesc including the sensorid, deviceid, and sensortype required for dynamic multi-sensors, + * see {@link SensorDescription}. + * @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 18 + */ +int32_t UnsubscribeSensorEnhanced(SensorDescription sensorDesc, const SensorUser *user); + +/** + * @brief Sets the data sampling interval and data reporting interval for the specified sensor. + * + * @param sensorDesc including the sensorid, deviceid, and sensortype required for dynamic multi-sensors, + * see {@link SensorDescription}. + * @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 18 + */ +int32_t SetBatchEnhanced(SensorDescription sensorDesc, 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 sensorDesc including the sensorid, deviceid, and sensortype required for dynamic multi-sensors, + * see {@link SensorDescription}. + * @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 18 + */ +int32_t ActivateSensorEnhanced(SensorDescription sensorDesc, const SensorUser *user); + +/** + * @brief Disables an enabled sensor. + * + * @param sensorDesc including the sensorid, deviceid, and sensortype required for dynamic multi-sensors, + * see {@link SensorDescription}. + * @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 18 + */ +int32_t DeactivateSensorEnhanced(SensorDescription sensorDesc, const SensorUser *user); + +/** + * @brief Sets the data reporting mode for the specified sensor. + * + * @param sensorDesc including the sensorid, deviceid, and sensortype required for dynamic multi-sensors, + * see {@link SensorDescription}. + * @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 18 + */ +int32_t SetModeEnhanced(SensorDescription sensorDesc, 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 18 + */ +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 18 + */ +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 5d57cb2e..192e3390 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 SensorDescription { + 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 */ +} SensorDescription; + typedef void (*SensorActiveInfoCB)(SensorActiveInfo &sensorActiveInfo); #ifdef __cplusplus diff --git a/services/BUILD.gn b/services/BUILD.gn index a2b7bc27..d79b5fbd 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", ] @@ -123,7 +124,10 @@ ohos_shared_library("libsensor_service") { [ "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include" ] } - external_deps += [ "drivers_interface_sensor:libsensor_proxy_2.1" ] + external_deps += [ + "drivers_interface_sensor:libsensor_proxy_2.1", + "drivers_interface_sensor:libsensor_proxy_3.0" + ] } shlib_type = "sa" @@ -222,6 +226,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", ] @@ -241,7 +246,10 @@ ohos_static_library("libsensor_service_static") { [ "$SUBSYSTEM_DIR/services/hdi_connection/hardware/include" ] } - external_deps += [ "drivers_interface_sensor:libsensor_proxy_2.1" ] + external_deps += [ + "drivers_interface_sensor:libsensor_proxy_2.1", + "drivers_interface_sensor:libsensor_proxy_3.0" + ] } part_name = "sensor" diff --git a/services/hdi_connection/adapter/include/compatible_connection.h b/services/hdi_connection/adapter/include/compatible_connection.h index 75460182..084a8477 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(SensorDescription sensorDesc) override; + int32_t DisableSensor(SensorDescription sensorDesc) override; + int32_t SetBatch(SensorDescription sensorDesc, int64_t samplingInterval, int64_t reportInterval) override; + int32_t SetMode(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 fbc192b0..5b25b668 100644 --- a/services/hdi_connection/adapter/include/hdi_connection.h +++ b/services/hdi_connection/adapter/include/hdi_connection.h @@ -28,19 +28,23 @@ 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(SensorDescription sensorDesc) override; + int32_t DisableSensor(SensorDescription sensorDesc) override; + int32_t SetBatch(SensorDescription sensorDesc, int64_t samplingInterval, int64_t reportInterval) override; + int32_t SetMode(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(); @@ -49,6 +53,12 @@ private: 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(SensorDescription sensorDesc, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + void SetSensorBasicInfoState(SensorDescription sensorDesc, bool state); + void DeleteSensorBasicInfoState(SensorDescription sensorDesc); + void GetSensorDescName(SensorDescription sensorDesc, std::string &sensorDescName); + void ParseIndex(const std::string &sensorDescName, int32_t &deviceId, int32_t &sensorType, int32_t &sensorId, + int32_t &location); }; } // namespace Sensors } // namespace OHOS diff --git a/services/hdi_connection/adapter/include/sensor_event_callback.h b/services/hdi_connection/adapter/include/sensor_event_callback.h index 46b5d1b9..a51f8c81 100644 --- a/services/hdi_connection/adapter/include/sensor_event_callback.h +++ b/services/hdi_connection/adapter/include/sensor_event_callback.h @@ -16,11 +16,11 @@ #ifndef SENSOR_EVENT_CALLBACK_H #define SENSOR_EVENT_CALLBACK_H -#include "v2_1/isensor_callback.h" -#include "v2_1/sensor_types.h" +#include "v3_0/isensor_callback.h" +#include "v3_0/sensor_types.h" -using OHOS::HDI::Sensor::V2_1::HdfSensorEvents; -using OHOS::HDI::Sensor::V2_1::ISensorCallback; +using OHOS::HDI::Sensor::V3_0::HdfSensorEvents; +using OHOS::HDI::Sensor::V3_0::ISensorCallback; namespace OHOS { namespace Sensors { 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 00000000..5cb108a0 --- /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 a368fda1..8fcd8964 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,45 @@ int32_t CompatibleConnection::GetSensorList(std::vector &sensorList) return ERR_OK; } -int32_t CompatibleConnection::EnableSensor(int32_t sensorId) +int32_t CompatibleConnection::EnableSensor(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(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(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(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 +132,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 +173,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 bdca2348..6ca5d05d 100644 --- a/services/hdi_connection/adapter/src/hdi_connection.cpp +++ b/services/hdi_connection/adapter/src/hdi_connection.cpp @@ -21,11 +21,12 @@ #include "hisysevent.h" #endif // HIVIEWDFX_HISYSEVENT_ENABLE #include "iproxy_broker.h" -#include "v2_1/isensor_interface.h" +#include "v3_0/isensor_interface.h" #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,20 +34,24 @@ namespace OHOS { namespace Sensors { using namespace OHOS::HiviewDFX; -using OHOS::HDI::Sensor::V2_1::ISensorInterface; -using OHOS::HDI::Sensor::V2_1::ISensorCallback; -using OHOS::HDI::Sensor::V2_1::HdfSensorInformation; +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; constexpr int32_t HEADPOSTURE_FIFO_COUNT = 5; +constexpr int32_t DEFAULT_BASE = 10; } // namespace ReportDataCb HdiConnection::reportDataCb_ = nullptr; +DevicePlugCallback HdiConnection::reportPlugDataCb_ = nullptr; sptr HdiConnection::reportDataCallback_ = nullptr; int32_t HdiConnection::ConnectHdi() @@ -56,9 +61,11 @@ int32_t HdiConnection::ConnectHdi() while (retry < GET_HDI_SERVICE_COUNT) { g_sensorInterface = ISensorInterface::Get(); if (g_sensorInterface != nullptr) { - SEN_HILOGI("Connect v2_1 hdi success"); + 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; } @@ -70,7 +77,7 @@ int32_t HdiConnection::ConnectHdi() HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "HDF_SERVICE_EXCEPTION", HiSysEvent::EventType::FAULT, "PKG_NAME", "ConnectHdi", "ERROR_CODE", CONNECT_SENSOR_HDF_ERR); #endif // HIVIEWDFX_HISYSEVENT_ENABLE - SEN_HILOGE("Connect v2_1 hdi failed"); + SEN_HILOGE("Connect v3_0 hdi failed"); return ERR_NO_INIT; } @@ -95,8 +102,10 @@ int32_t HdiConnection::GetSensorList(std::vector &sensorList) } for (size_t i = 0; i < count; i++) { Sensor sensor; - sensor.SetSensorId(sensorInfos[i].sensorId); - sensor.SetSensorTypeId(sensorInfos[i].sensorId); + sensor.SetDeviceId(sensorInfos[i].deviceSensorInfo.deviceId); + sensor.SetSensorId(sensorInfos[i].deviceSensorInfo.sensorId); + sensor.SetSensorTypeId(sensorInfos[i].deviceSensorInfo.sensorTypeId); + sensor.SetLocation(sensorInfos[i].deviceSensorInfo.location); sensor.SetFirmwareVersion(sensorInfos[i].firmwareVersion); sensor.SetHardwareVersion(sensorInfos[i].hardwareVersion); sensor.SetMaxRange(sensorInfos[i].maxRange); @@ -114,29 +123,34 @@ int32_t HdiConnection::GetSensorList(std::vector &sensorList) return ERR_OK; } -int32_t HdiConnection::EnableSensor(int32_t sensorId) +int32_t HdiConnection::EnableSensor(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); - int32_t ret = g_sensorInterface->Enable(sensorId); + 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", HiSysEvent::EventType::FAULT, "PKG_NAME", "EnableSensor", "ERROR_CODE", ret); #endif // HIVIEWDFX_HISYSEVENT_ENABLE - SEN_HILOGE("Connect v2_1 hdi failed"); + 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(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); - int32_t ret = g_sensorInterface->Disable(sensorId); + 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", @@ -145,15 +159,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(SensorDescription sensorDesc, int64_t samplingInterval, int64_t reportInterval) { CHKPR(g_sensorInterface, ERR_NO_INIT); - int32_t ret = g_sensorInterface->SetBatch(sensorId, 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", @@ -162,15 +178,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(SensorDescription sensorDesc, int32_t mode) { CALL_LOG_ENTER; CHKPR(g_sensorInterface, ERR_NO_INIT); - int32_t ret = g_sensorInterface->SetMode(sensorId, 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", @@ -214,11 +231,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) { @@ -235,43 +288,54 @@ sptr HdiConnection::GetReportDataCallback() return reportDataCallback_; } -void HdiConnection::UpdateSensorBasicInfo(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) +void HdiConnection::UpdateSensorBasicInfo(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); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = g_sensorBasicInfoMap.find(sensorDescName); if (it != g_sensorBasicInfoMap.end()) { - if (g_sensorBasicInfoMap[sensorId].GetSensorState()) { + if (g_sensorBasicInfoMap[sensorDescName].GetSensorState()) { sensorBasicInfo.SetSensorState(true); } } - g_sensorBasicInfoMap[sensorId] = sensorBasicInfo; + g_sensorBasicInfoMap[sensorDescName] = sensorBasicInfo; } -void HdiConnection::SetSensorBasicInfoState(int32_t sensorId, bool state) +void HdiConnection::SetSensorBasicInfoState(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); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = g_sensorBasicInfoMap.find(sensorDescName); 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[sensorDescName].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(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); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = g_sensorBasicInfoMap.find(sensorDescName); if (it != g_sensorBasicInfoMap.end()) { - g_sensorBasicInfoMap.erase(sensorId); + g_sensorBasicInfoMap.erase(sensorDescName); } - 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() @@ -317,6 +381,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) { @@ -325,22 +394,94 @@ void HdiConnection::Reconnect() } std::lock_guard sensorInfoLock(g_sensorBasicInfoMutex); for (const auto &sensorInfo: g_sensorBasicInfoMap) { - int32_t sensorTypeId = sensorInfo.first; + SensorDescription sensorDesc; + ParseIndex(sensorInfo.first, sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location); 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", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId); continue; } - ret = g_sensorInterface->SetBatch(sensorTypeId, info.GetSamplingPeriodNs(), info.GetMaxReportDelayNs()); + ret = g_sensorInterface->SetBatch(sensorDesc, 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, error:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, ret); continue; } - ret = g_sensorInterface->Enable(sensorTypeId); + ret = g_sensorInterface->Enable(sensorDesc); 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, error:%{public}d", + sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.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.sensorTypeId); + 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].sensorId == SENSOR_TYPE_ID_HEADPOSTURE) { + sensor.SetFifoMaxEventCount(HEADPOSTURE_FIFO_COUNT); + } + singleDevSensors.push_back(sensor); + } + return ERR_OK; +} + +void HdiConnection::GetSensorDescName(SensorDescription sensorDesc, std::string &sensorDescName) +{ + sensorDescName = std::to_string(sensorDesc.deviceId) + "#" + std::to_string(sensorDesc.sensorType) + + "#" + std::to_string(sensorDesc.sensorId)+ "#" + std::to_string(sensorDesc.location); + return; +} + +void HdiConnection::ParseIndex(const std::string &sensorDescName, int32_t &deviceId, int32_t &sensorType, + int32_t &sensorId, int32_t &location) +{ + size_t first_hash = sensorDescName.find('#'); + size_t second_hash = sensorDescName.find('#', first_hash + 1); + size_t third_hash = sensorDescName.find('#', second_hash + 1); + + deviceId = static_cast(strtol(sensorDescName.substr(0, first_hash).c_str(), nullptr, DEFAULT_BASE)); + sensorType = static_cast(strtol(sensorDescName.substr(first_hash + 1, + second_hash - first_hash - 1).c_str(), nullptr, DEFAULT_BASE)); + sensorId = static_cast(strtol(sensorDescName.substr(second_hash + 1, + third_hash - second_hash - 1).c_str(), nullptr, DEFAULT_BASE)); + location = static_cast(strtol(sensorDescName.substr(third_hash + 1).c_str(), nullptr, DEFAULT_BASE)); + return; +} } // 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 d99d3080..3951ff4a 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.sensorId, - .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 00000000..9e2ce202 --- /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 bb0b3918..f13d3c6b 100644 --- a/services/hdi_connection/hardware/include/hdi_service_impl.h +++ b/services/hdi_connection/hardware/include/hdi_service_impl.h @@ -28,10 +28,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(SensorDescription sensorDesc); + int32_t DisableSensor(SensorDescription sensorDesc); + int32_t SetBatch(SensorDescription sensorDesc, int64_t samplingInterval, int64_t reportInterval); + int32_t SetMode(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 bf1c15e9..d8e1664e 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_; @@ -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; @@ -231,18 +259,18 @@ void HdiServiceImpl::DataReportThread() return; } -int32_t HdiServiceImpl::EnableSensor(int32_t sensorId) +int32_t HdiServiceImpl::EnableSensor(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 sensorId:%{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("sensorId:%{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(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("sensorId:%{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(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(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 5997a9b6..9185a2af 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(SensorDescription sensorDesc) = 0; + virtual int32_t DisableSensor(SensorDescription sensorDesc) = 0; + virtual int32_t SetBatch(SensorDescription sensorDesc, int64_t samplingInterval, int64_t reportInterval) = 0; + virtual int32_t SetMode(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 df45cfd3..f8a210bb 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(SensorDescription sensorDesc) override; + int32_t DisableSensor(SensorDescription sensorDesc) override; + int32_t SetBatch(SensorDescription sensorDesc, int64_t samplingInterval, int64_t reportInterval) override; + int32_t SetMode(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); diff --git a/services/hdi_connection/interface/src/sensor_hdi_connection.cpp b/services/hdi_connection/interface/src/sensor_hdi_connection.cpp index 6dff811f..4f154c16 100644 --- a/services/hdi_connection/interface/src/sensor_hdi_connection.cpp +++ b/services/hdi_connection/interface/src/sensor_hdi_connection.cpp @@ -34,6 +34,7 @@ namespace OHOS { namespace Sensors { using namespace OHOS::HiviewDFX; namespace { +constexpr int32_t IS_LOCAL_DEVICE = 1; #ifdef BUILD_VARIANT_ENG constexpr float MAX_RANGE = 9999.0; constexpr float POWER = 20.0; @@ -47,6 +48,9 @@ std::unordered_set g_supportMockSensors = { SENSOR_TYPE_ID_HEADPOSTURE, SENSOR_TYPE_ID_PROXIMITY1 }; +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 @@ -135,8 +139,10 @@ bool SensorHdiConnection::FindOneInMockSet(int32_t sensorId) 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,6 +227,11 @@ int32_t SensorHdiConnection::GetSensorList(std::vector &sensorList) if (!hdiConnectionStatus_) { return ERR_OK; } + for (const auto& sensor : sensorList) { + if (sensor.GetLocation() == IS_LOCAL_DEVICE) { + localDeviceId_ = sensor.GetDeviceId(); + } + } for (const auto &sensorId : mockSet_) { switch (sensorId) { case SENSOR_TYPE_ID_COLOR: @@ -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(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(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,70 @@ 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(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(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 +441,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 (sensorList_[0].GetLocation() == IS_LOCAL_DEVICE) { + if (!hdiConnectionStatus_) { + return ERR_OK; + } + localDeviceId_ = sensorList_[0].GetDeviceId(); + for (const auto &sensorId : mockSet_) { + switch (sensorId) { + 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 01c4e5b5..2f83d6fc 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,37 +38,37 @@ 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(SensorDescription sensorDesc); + SensorBasicInfo GetBestSensorInfo(SensorDescription sensorDesc); + bool OnlyCurPidSensorEnabled(SensorDescription sensorDesc, int32_t pid); + std::vector> GetSensorChannel(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(SensorDescription sensorDesc, int32_t pid, const SensorBasicInfo &sensorInfo); + void RemoveSubscriber(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(SensorDescription sensorDesc); + void ClearCurPidSensorInfo(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(SensorDescription sensorDesc, int32_t pid); + uint64_t ComputeBestPeriodCount(SensorDescription sensorDesc, sptr &channel); + uint64_t ComputeBestFifoCount(SensorDescription sensorDesc, sptr &channel); + int32_t GetStoreEvent(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 DestroyCmd(int32_t uid); void UpdateDataQueue(int32_t sensorId, SensorData &data); - std::unordered_map> GetDumpQueue(); - void ClearDataQueue(int32_t sensorId); + std::unordered_map> GetDumpQueue(); + void ClearDataQueue(SensorDescription sensorDesc); int32_t GetUidByPid(int32_t pid); AccessTokenID GetTokenIdByPid(int32_t pid); int32_t AddActiveInfoCBPid(int32_t pid); @@ -79,6 +80,12 @@ public: void ChangeSensorPerm(AccessTokenID tokenId, const std::string &permName, bool state); void SetDeviceStatus(uint32_t deviceStatus); uint32_t GetDeviceStatus(); + void GetSensorDescName(SensorDescription sensorDesc, std::string &sensorDescName); + void ParseIndex(const std::string &sensorDescName, int32_t &deviceId, int32_t &sensorType, + int32_t &sensorId, int32_t &location); + void SaveSensorClient(const sptr &sensorClient); + void DestroySensorClient(const sptr &sensorClient); + void SendMsgToClient(SensorPlugData info); private: DISALLOW_COPY_AND_MOVE(ClientInfo); @@ -90,17 +97,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/sensor_data_processer.h b/services/include/sensor_data_processer.h index 25731815..281ce9a9 100755 --- a/services/include/sensor_data_processer.h +++ b/services/include/sensor_data_processer.h @@ -24,7 +24,7 @@ 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); @@ -34,22 +34,23 @@ public: 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_manager.h b/services/include/sensor_manager.h index ab8370e9..158110d4 100644 --- a/services/include/sensor_manager.h +++ b/services/include/sensor_manager.h @@ -31,19 +31,21 @@ 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(SensorDescription sensorDesc, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + bool ResetBestSensorParams(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(SensorDescription sensorDesc, uint32_t pid, int64_t samplingPeriodNs, + int64_t maxReportDelayNs); + SensorBasicInfo GetSensorInfo(SensorDescription sensorDesc, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + bool IsOtherClientUsingSensor(SensorDescription sensorDesc, int32_t clientPid); + ErrCode AfterDisableSensor(SensorDescription sensorDesc); void GetPackageName(AccessTokenID tokenId, std::string &packageName, bool isAccessTokenServiceActive = false); + void UpdataSensorMap(SensorPlugData sensorPlugData); private: #ifdef HDF_DRIVERS_INTERFACE_SENSOR @@ -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 b1dba0d6..7cfc4822 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 @@ -36,13 +37,14 @@ public: 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 Suspend(int32_t pid, const std::vector &sensorIdList, + std::unordered_map &SensorInfoMap); + bool Resume(int32_t pid, SensorDescription sensorDesc, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + ErrCode RestoreSensorInfo(int32_t pid, 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 39286c8a..d0146da2 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,19 @@ 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(SensorDescription sensorDesc, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + void ReportPlugEventCallback(const SensorPlugInfo sensorPlugInfo); + ErrCode EnableSensorSplit(SensorDescription sensorDesc, int64_t samplingPeriodNs, int64_t maxReportDelayNs, + int32_t pid); class PermStateChangeCb : public Security::AccessToken::PermStateChangeCallbackCustomize { public: @@ -79,26 +87,28 @@ private: void RegisterClientDeathRecipient(sptr sensorClient, int32_t pid); void UnregisterClientDeathRecipient(sptr sensorClient); bool InitSensorPolicy(); - void ReportOnChangeData(int32_t sensorId); + void ReportOnChangeData(SensorDescription sensorDesc); void ReportSensorSysEvent(int32_t sensorId, bool enable, int32_t pid, int64_t samplingPeriodNs = 0, int64_t maxReportDelayNs = 0); - ErrCode DisableSensor(int32_t sensorId, int32_t pid); + ErrCode DisableSensor(SensorDescription sensorDesc, int32_t pid); bool RegisterPermCallback(int32_t sensorId); void UnregisterPermCallback(); - void ReportActiveInfo(int32_t sensorId, int32_t pid); - bool CheckSensorId(int32_t sensorId); + void ReportActiveInfo(SensorDescription sensorDesc, int32_t pid); + bool CheckSensorId(SensorDescription sensorDesc); bool IsSystemServiceCalling(); bool IsSystemCalling(); + void GetSensorDescName(SensorDescription sensorDesc, std::string &sensorDescName); SensorServiceState state_; std::mutex serviceLock_; 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; @@ -111,6 +121,7 @@ private: sptr clientDeathObserver_ = nullptr; std::shared_ptr permStateChangeCb_ = nullptr; ErrCode SaveSubscriber(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs); + ErrCode SaveSubscriber(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 7746625e..3e5fe732 100644 --- a/services/src/client_info.cpp +++ b/services/src/client_info.cpp @@ -16,6 +16,7 @@ #include "permission_util.h" #include "securec.h" #include "sensor_manager.h" +#include "i_sensor_client.h" #ifdef HDF_DRIVERS_INTERFACE_SENSOR #include "sensor_hdi_connection.h" #endif // HDF_DRIVERS_INTERFACE_SENSOR @@ -35,6 +36,7 @@ constexpr int32_t MIN_MAP_SIZE = 0; constexpr uint32_t NO_STORE_EVENT = -2; constexpr uint32_t MAX_SUPPORT_CHANNEL = 200; constexpr uint32_t MAX_DUMP_DATA_SIZE = 10; +constexpr int32_t DEFAULT_BASE = 10; } // namespace std::unordered_map> ClientInfo::userGrantPermMap_ = { @@ -42,17 +44,20 @@ std::unordered_map> ClientInfo::userGrantPermMap_ { READ_HEALTH_DATA_PERMISSION, { SENSOR_TYPE_ID_HEART_RATE } } }; -bool ClientInfo::GetSensorState(int32_t sensorId) +bool ClientInfo::GetSensorState(SensorDescription sensorDesc) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); - if (sensorId == INVALID_SENSOR_ID) { + 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("sensorId is invalid"); return false; } std::lock_guard clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = clientMap_.find(sensorDescName); if (it == clientMap_.end()) { - SEN_HILOGE("Can't find sensorId:%{public}d", sensorId); + SEN_HILOGE("Can't find sensorId:%{public}d", sensorDesc.sensorType); return false; } for (const auto &pidIt : it->second) { @@ -60,26 +65,30 @@ 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(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) { + if (sensorDesc.sensorType == INVALID_SENSOR_ID) { SEN_HILOGE("sensorId is invalid"); return sensorInfo; } std::lock_guard clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = clientMap_.find(sensorDescName); 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 +102,20 @@ SensorBasicInfo ClientInfo::GetBestSensorInfo(int32_t sensorId) return sensorInfo; } -bool ClientInfo::OnlyCurPidSensorEnabled(int32_t sensorId, int32_t pid) +bool ClientInfo::OnlyCurPidSensorEnabled(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_HILOGI("In, sensorId:%{public}d, pid:%{public}d", sensorDesc.sensorType, pid); + if ((sensorDesc.sensorType == INVALID_SENSOR_ID) || (pid <= INVALID_PID)) { SEN_HILOGE("sensorId or pid is invalid"); return false; } std::lock_guard clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = clientMap_.find(sensorDescName); 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 +129,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, sensorId:%{public}d, pid:%{public}d", sensorDesc.sensorType, pid); return ret; } @@ -202,16 +214,20 @@ sptr ClientInfo::GetSensorChannelByPid(int32_t pid) return channelIt->second; } -std::vector> ClientInfo::GetSensorChannel(int32_t sensorId) +std::vector> ClientInfo::GetSensorChannel(SensorDescription sensorDesc) { - if (sensorId == INVALID_SENSOR_ID) { + if (sensorDesc.sensorType == INVALID_SENSOR_ID) { SEN_HILOGE("sensorId is invalid"); return {}; } std::lock_guard clientLock(clientMutex_); - auto clientIt = clientMap_.find(sensorId); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto clientIt = clientMap_.find(sensorDescName); 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 +245,21 @@ std::vector> ClientInfo::GetSensorChannel(int32_t s return sensorChannel; } -bool ClientInfo::UpdateSensorInfo(int32_t sensorId, int32_t pid, const SensorBasicInfo &sensorInfo) +bool ClientInfo::UpdateSensorInfo(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, sensorId:%{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); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = clientMap_.find(sensorDescName); 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(sensorDescName, pidMap)); return pidRet.second && clientRet.second; } auto pidIt = it->second.find(pid); @@ -250,15 +268,17 @@ 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, sensorId:%{public}d, pid:%{public}d", sensorDesc.sensorType, pid); return true; } -void ClientInfo::RemoveSubscriber(int32_t sensorId, uint32_t pid) +void ClientInfo::RemoveSubscriber(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); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = clientMap_.find(sensorDescName); if (it == clientMap_.end()) { SEN_HILOGW("sensorId not exist"); return; @@ -267,7 +287,7 @@ void ClientInfo::RemoveSubscriber(int32_t sensorId, uint32_t pid) if (pidIt != it->second.end()) { it->second.erase(pidIt); } - SEN_HILOGI("Done, sensorId:%{public}d, pid:%{public}d", sensorId, pid); + SEN_HILOGI("Done, sensorTypeId:%{public}d, pid:%{public}u", sensorDesc.sensorType, pid); } bool ClientInfo::UpdateSensorChannel(int32_t pid, const sptr &channel) @@ -294,32 +314,37 @@ bool ClientInfo::UpdateSensorChannel(int32_t pid, const sptr clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = clientMap_.find(sensorDescName); if (it == clientMap_.end()) { SEN_HILOGD("sensorId not exist, no need to clear it"); return; } clientMap_.erase(it); - SEN_HILOGI("Done, sensorId:%{public}d", sensorId); + SEN_HILOGI("Done, sensorId:%{public}d", sensorDesc.sensorType); } -void ClientInfo::ClearCurPidSensorInfo(int32_t sensorId, int32_t pid) +void ClientInfo::ClearCurPidSensorInfo(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_HILOGI("In, sensorId:%{public}d, pid:%{public}d", sensorDesc.sensorType, pid); + if ((sensorDesc.sensorType == INVALID_SENSOR_ID) || (pid <= INVALID_PID)) { SEN_HILOGE("sensorId or pid is invalid"); return; } std::lock_guard clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = clientMap_.find(sensorDescName); if (it == clientMap_.end()) { SEN_HILOGD("sensorId not exist, no need to clear it"); return; @@ -333,7 +358,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, sensorId:%{public}d, pid:%{public}d", sensorDesc.sensorType, pid); } bool ClientInfo::DestroySensorChannel(int32_t pid) @@ -368,21 +393,24 @@ bool ClientInfo::DestroySensorChannel(int32_t pid) return true; } -SensorBasicInfo ClientInfo::GetCurPidSensorInfo(int32_t sensorId, int32_t pid) +SensorBasicInfo ClientInfo::GetCurPidSensorInfo(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)) { + if ((sensorDesc.sensorType == INVALID_SENSOR_ID) || (pid <= INVALID_PID)) { SEN_HILOGE("sensorId or channel is invalid"); return sensorInfo; } std::lock_guard clientLock(clientMutex_); - auto it = clientMap_.find(sensorId); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = clientMap_.find(sensorDescName); 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,9 +423,9 @@ SensorBasicInfo ClientInfo::GetCurPidSensorInfo(int32_t sensorId, int32_t pid) return sensorInfo; } -uint64_t ClientInfo::ComputeBestPeriodCount(int32_t sensorId, sptr &channel) +uint64_t ClientInfo::ComputeBestPeriodCount(SensorDescription sensorDesc, sptr &channel) { - if (sensorId == INVALID_SENSOR_ID || channel == nullptr) { + if (sensorDesc.sensorType == INVALID_SENSOR_ID || channel == nullptr) { SEN_HILOGE("sensorId is invalid or channel cannot be null"); return 0UL; } @@ -410,8 +438,8 @@ uint64_t ClientInfo::ComputeBestPeriodCount(int32_t sensorId, sptr &channel) +uint64_t ClientInfo::ComputeBestFifoCount(SensorDescription sensorDesc, sptr &channel) { - if (channel == nullptr || sensorId == INVALID_SENSOR_ID) { + if (channel == nullptr || sensorDesc.sensorType == INVALID_SENSOR_ID) { SEN_HILOGE("sensorId is invalid or channel cannot be null"); return 0UL; } @@ -435,8 +463,8 @@ uint64_t ClientInfo::ComputeBestFifoCount(int32_t sensorId, sptr lock(eventMutex_); - auto storedEvent = storedEvent_.find(sensorId); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto storedEvent = storedEvent_.find(sensorDescName); 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 +517,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 +526,10 @@ void ClientInfo::StoreEvent(const SensorData &data) if (foundSensor) { std::lock_guard lock(eventMutex_); - storedEvent_[storedEvent.sensorTypeId] = storedEvent; + std::string sensorDescName; + GetSensorDescName({storedEvent.deviceId, storedEvent.sensorTypeId, storedEvent.sensorId, + storedEvent.location}, sensorDescName); + storedEvent_[sensorDescName] = storedEvent; } } @@ -543,18 +579,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 sensorIndexVec; 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); + sensorIndexVec.push_back(itClientMap.first); } } - return sensorIdVec; + return sensorIndexVec; } AppThreadInfo ClientInfo::GetAppInfoByChannel(const sptr &channel) @@ -597,8 +633,13 @@ void ClientInfo::GetSensorChannelInfo(std::vector &channelInf continue; } SensorChannelInfo channel; + SensorDescription sensorDesc; + ParseIndex(sensorIt.first, sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location); channel.SetUid(uid); - channel.SetSensorId(sensorIt.first); + channel.SetDeviceId(sensorDesc.deviceId); + channel.SetSensorType(sensorDesc.sensorType); + channel.SetSensorId(sensorDesc.sensorType); std::string packageName; SensorManager::GetInstance().GetPackageName(GetTokenIdByPid(pid), packageName); channel.SetPackageName(packageName); @@ -607,7 +648,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(sensorDesc.sensorType, uid)); channelInfo.push_back(channel); } } @@ -683,11 +724,13 @@ void ClientInfo::UpdateDataQueue(int32_t sensorId, SensorData &data) return; } std::lock_guard queueLock(dataQueueMutex_); - auto it = dumpQueue_.find(sensorId); + std::string sensorDescName; + GetSensorDescName({data.deviceId, data.sensorTypeId, data.sensorId, data.location}, sensorDescName); + auto it = dumpQueue_.find(sensorDescName); if (it == dumpQueue_.end()) { std::queue q; q.push(data); - dumpQueue_.insert(std::make_pair(sensorId, q)); + dumpQueue_.insert(std::make_pair(sensorDescName, q)); return; } it->second.push(data); @@ -696,15 +739,17 @@ 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(SensorDescription sensorDesc) { std::lock_guard queueLock(dataQueueMutex_); - auto it = dumpQueue_.find(sensorId); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = dumpQueue_.find(sensorDescName); if (it != dumpQueue_.end()) { dumpQueue_.erase(it); } @@ -777,14 +822,19 @@ int32_t ClientInfo::GetPidByTokenId(AccessTokenID tokenId) void ClientInfo::UpdatePermState(int32_t pid, int32_t sensorId, 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();) { + SensorDescription sensorDesc; + ParseIndex(it->first, sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location); + if (sensorDesc.sensorType != sensorId) { + it++; + continue; + } + auto clientInfo = it->second.find(pid); + if (clientInfo != it->second.end()) { + clientInfo->second.SetPermState(state); + } + it++; } } @@ -814,5 +864,58 @@ uint32_t ClientInfo::GetDeviceStatus() { return deviceStatus_; } + +void ClientInfo::GetSensorDescName(SensorDescription sensorDesc, std::string &sensorDescName) +{ + sensorDescName = std::to_string(sensorDesc.deviceId) + "#" + std::to_string(sensorDesc.sensorType) + + "#" + std::to_string(sensorDesc.sensorId)+ "#" + std::to_string(sensorDesc.location); + return; +} + +void ClientInfo::ParseIndex(const std::string &sensorDescName, int32_t &deviceId, int32_t &sensorType, + int32_t &sensorId, int32_t &location) +{ + size_t first_hash = sensorDescName.find('#'); + size_t second_hash = sensorDescName.find('#', first_hash + 1); + size_t third_hash = sensorDescName.find('#', second_hash + 1); + + deviceId = static_cast(strtol(sensorDescName.substr(0, first_hash).c_str(), nullptr, DEFAULT_BASE)); + sensorType = static_cast(strtol(sensorDescName.substr(first_hash + 1, + second_hash - first_hash - 1).c_str(), nullptr, DEFAULT_BASE)); + sensorId = static_cast(strtol(sensorDescName.substr(second_hash + 1, + third_hash - second_hash - 1).c_str(), nullptr, DEFAULT_BASE)); + location = static_cast(strtol(sensorDescName.substr(third_hash + 1).c_str(), nullptr, DEFAULT_BASE)); + return; +} + +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/sensor_data_processer.cpp b/services/src/sensor_data_processer.cpp index 34e69cc3..2217ea34 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,23 @@ SensorDataProcesser::~SensorDataProcesser() sensorMap_.clear(); } -void SensorDataProcesser::SendNoneFifoCacheData(std::unordered_map &cacheBuf, +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); + std::string sensorDescName; + clientInfo_.GetSensorDescName({data.deviceId, data.sensorTypeId, data.sensorId, data.location}, sensorDescName); + auto dataCountIt = dataCountMap_.find(sensorDescName); 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::make_pair(sensorDescName, channelFifoList)); SendRawData(cacheBuf, channel, sendEvents); return; } @@ -99,12 +101,14 @@ 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); + std::string sensorDescName; + clientInfo_.GetSensorDescName({data.deviceId, data.sensorTypeId, data.sensorId, data.location}, sensorDescName); + auto dataCountIt = dataCountMap_.find(sensorDescName); // there is no channelFifoList if (dataCountIt == dataCountMap_.end()) { std::vector> channelFifoList; @@ -112,7 +116,7 @@ void SensorDataProcesser::SendFifoCacheData(std::unordered_mapSetChannel(channel); channelFifoList.push_back(fifoCacheData); - dataCountMap_.insert(std::make_pair(data.sensorTypeId, channelFifoList)); + dataCountMap_.insert(std::make_pair(sensorDescName, channelFifoList)); return; } // find channel in channelFifoList @@ -149,13 +153,19 @@ 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); @@ -163,16 +173,18 @@ void SensorDataProcesser::ReportData(sptr &channel, Sens if (sensorId == 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,12 +192,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; std::lock_guard sensorLock(sensorMutex_); - auto sensor = sensorMap_.find(sensorId); + std::string sensorDescName; + clientInfo_.GetSensorDescName({data.deviceId, data.sensorTypeId, data.sensorId, data.location}, sensorDescName); + auto sensor = sensorMap_.find(sensorDescName); if (sensor == sensorMap_.end()) { SEN_HILOGE("Data's sensorId is not supported"); return false; @@ -204,7 +218,7 @@ bool SensorDataProcesser::ReportNotContinuousData(std::unordered_map &cacheBuf, +void SensorDataProcesser::SendRawData(std::unordered_map &cacheBuf, sptr channel, std::vector events) { CHKPV(channel); @@ -214,10 +228,12 @@ 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]; + std::string sensorDescName; + clientInfo_.GetSensorDescName({events[eventSize - 1].deviceId, events[eventSize - 1].sensorTypeId, + events[eventSize - 1].sensorId, events[eventSize - 1].location}, sensorDescName); + cacheBuf[sensorDescName] = events[eventSize - 1]; } } @@ -225,12 +241,13 @@ 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()); + std::string sensorDescName; + clientInfo_.GetSensorDescName({data.deviceId, data.sensorTypeId, data.sensorId, data.location}, sensorDescName); + if (data.sensorTypeId == SENSOR_TYPE_ID_HALL_EXT) { PrintSensorData::GetInstance().PrintSensorDataLog("CacheSensorEvent", data); } - auto cacheEvent = cacheBuf.find(sensorId); + auto cacheEvent = cacheBuf.find(sensorDescName); 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; @@ -243,7 +260,7 @@ 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 bc6f670f..982bfaa2 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,13 @@ 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()) { + int32_t deviceId, sensorTypeId, sensorId, location; + clientInfo.ParseIndex(sensorData.first, deviceId, sensorTypeId, sensorId, location); + if (sensorMap_.find(sensorTypeId) == sensorMap_.end()) { continue; } - dprintf(fd, "sensorId: %8u | sensorType: %s:\n", sensorId, sensorMap_[sensorId].c_str()); + dprintf(fd, "deviceId:%d | sensorType:%s |sensorId:%8u :\n", deviceId, sensorMap_[sensorTypeId].c_str(), + 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 +279,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(sensorTypeId, data).c_str()); } } return true; diff --git a/services/src/sensor_manager.cpp b/services/src/sensor_manager.cpp index e79c215e..32ea6eff 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(SensorDescription sensorDesc, int64_t samplingPeriodNs, + int64_t maxReportDelayNs) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); - if (sensorId == INVALID_SENSOR_ID) { + SEN_HILOGI("In, sensorType:%{public}d", sensorDesc.sensorType); + if (sensorDesc.sensorType == INVALID_SENSOR_ID) { SEN_HILOGE("sensorId 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, sensorId:%{public}d", sensorDesc.sensorType); return true; } -bool SensorManager::ResetBestSensorParams(int32_t sensorId) +bool SensorManager::ResetBestSensorParams(SensorDescription sensorDesc) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); - if (sensorId == INVALID_SENSOR_ID) { + 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("sensorId 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, sensorId:%{public}d", sensorDesc.sensorId); 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,25 +106,28 @@ 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(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, sensorId:%{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(SensorDescription sensorDesc, int64_t samplingPeriodNs, + int64_t maxReportDelayNs) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); + SEN_HILOGI("In, sensorId:%{public}d", sensorDesc.sensorType); SensorBasicInfo sensorInfo; std::lock_guard sensorMapLock(sensorMapMutex_); - auto it = sensorMap_.find(sensorId); + std::string sensorDescName; + clientInfo_.GetSensorDescName(sensorDesc, sensorDescName); + auto it = sensorMap_.find(sensorDescName); if (it == sensorMap_.end()) { sensorInfo.SetSamplingPeriodNs(samplingPeriodNs); sensorInfo.SetMaxReportDelayNs(maxReportDelayNs); @@ -142,42 +147,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, sensorId:%{public}d", sensorDesc.sensorType); return sensorInfo; } -bool SensorManager::IsOtherClientUsingSensor(int32_t sensorId, int32_t clientPid) +bool SensorManager::IsOtherClientUsingSensor(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, sensorId:%{public}d, clientPid:%{public}d", sensorDesc.sensorType, clientPid); return true; } -ErrCode SensorManager::AfterDisableSensor(int32_t sensorId) +ErrCode SensorManager::AfterDisableSensor(SensorDescription sensorDesc) { - SEN_HILOGI("In, sensorId:%{public}d", sensorId); - clientInfo_.ClearSensorInfo(sensorId); - if (sensorId == PROXIMITY_SENSOR_ID) { + SEN_HILOGI("In, sensorId:%{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, sensorId:%{public}d", sensorDesc.sensorType); return ERR_OK; } diff --git a/services/src/sensor_power_policy.cpp b/services/src/sensor_power_policy.cpp index e5c81748..05b19510 100644 --- a/services/src/sensor_power_policy.cpp +++ b/services/src/sensor_power_policy.cpp @@ -43,24 +43,24 @@ bool SensorPowerPolicy::CheckFreezingSensor(int32_t sensorId) ErrCode SensorPowerPolicy::SuspendSensors(int32_t pid) { CALL_LOG_ENTER; - std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); - if (sensorIdList.empty()) { + std::vector sensorIndexList = clientInfo_.GetSensorIdByPid(pid); + if (sensorIndexList.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, sensorIndexList, 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, sensorIndexList, 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,35 @@ 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 &sensorIndexList, + std::unordered_map &sensorInfoMap) { CALL_LOG_ENTER; bool isAllSuspend = true; - for (const auto &sensorId : sensorIdList) { - if (CheckFreezingSensor(sensorId)) { + for (const auto &sensorIndex : sensorIndexList) { + SensorDescription sensorDesc; + clientInfo_.ParseIndex(sensorIndex, sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location); + 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, sensorId:%{public}d", + sensorDesc.sensorType); + sensorInfoMap.insert(std::make_pair(sensorIndex, 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, sensorId:%{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(sensorIndex, sensorInfo)); + sensorManager_.AfterDisableSensor(sensorDesc); } return isAllSuspend; } @@ -109,13 +113,15 @@ 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; + SensorDescription sensorDesc; + clientInfo_.ParseIndex(sensorIt->first, sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location); 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, sensorDesc, samplingPeriodNs, maxReportDelayNs)) { + SEN_HILOGE("Resume sensor failed, sensorId:%{public}d", sensorDesc.sensorType); isAllResume = false; ++sensorIt; } else { @@ -131,53 +137,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, 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"); 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, sensorId:%{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, sensorId:%{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, 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 +224,14 @@ std::vector SensorPowerPolicy::GetActiveInfoList(int32_t pid) { CALL_LOG_ENTER; std::vector activeInfoList; - std::vector sensorIdList = clientInfo_.GetSensorIdByPid(pid); + 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()); + SensorDescription sensorDesc; + clientInfo_.ParseIndex(sensorId, sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location); + 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 132203d9..675024b8 100644 --- a/services/src/sensor_service.cpp +++ b/services/src/sensor_service.cpp @@ -45,6 +45,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 @@ -123,6 +124,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 @@ -162,6 +166,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(); @@ -186,7 +201,10 @@ bool SensorService::InitSensorList() { std::lock_guard sensorMapLock(sensorMapMutex_); for (const auto &it : sensors_) { - if (!(sensorMap_.insert(std::make_pair(it.GetSensorId(), it)).second)) { + std::string sensorDescName; + GetSensorDescName({it.GetDeviceId(), it.GetSensorTypeId(), it.GetSensorId(), it.GetLocation()}, + sensorDescName); + if (!(sensorMap_.insert(std::make_pair(sensorDescName, it)).second)) { SEN_HILOGW("sensorMap_ insert failed"); } } @@ -249,10 +267,12 @@ void SensorService::ReportSensorSysEvent(int32_t sensorId, bool enable, int32_t } } -void SensorService::ReportOnChangeData(int32_t sensorId) +void SensorService::ReportOnChangeData(SensorDescription sensorDesc) { std::lock_guard sensorMapLock(sensorMapMutex_); - auto it = sensorMap_.find(sensorId); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = sensorMap_.find(sensorDescName); if (it == sensorMap_.end()) { SEN_HILOGE("sensorId is invalid"); return; @@ -262,7 +282,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; @@ -276,33 +296,39 @@ void SensorService::ReportOnChangeData(int32_t sensorId) } } -ErrCode SensorService::SaveSubscriber(int32_t sensorId, int64_t samplingPeriodNs, int64_t maxReportDelayNs) +ErrCode SensorService::SaveSubscriber(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(SensorDescription sensorDesc) { std::lock_guard sensorMapLock(sensorMapMutex_); - auto it = sensorMap_.find(sensorId); + std::string sensorDescName; + GetSensorDescName(sensorDesc, sensorDescName); + auto it = sensorMap_.find(sensorDescName); 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; @@ -328,25 +354,25 @@ 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(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("sensorId:%{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"); return ERR_NO_INIT; @@ -354,63 +380,76 @@ ErrCode SensorService::CheckAuthAndParameter(int32_t sensorId, int64_t samplingP 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 EnableSensorSplit(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::EnableSensorSplit(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(SensorDescription sensorDesc, int32_t pid) { CALL_LOG_ENTER; - if (!CheckSensorId(sensorId)) { + if (!CheckSensorId(sensorDesc)) { SEN_HILOGE("sensorId is invalid"); return ERR_NO_INIT; } @@ -418,44 +457,50 @@ ErrCode SensorService::DisableSensor(int32_t sensorId, int32_t pid) 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("sensorId:%{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) @@ -472,6 +517,70 @@ 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_) { + std::string sensorDescName; + GetSensorDescName({it.GetDeviceId(), it.GetSensorTypeId(), it.GetSensorId(), it.GetLocation()}, + sensorDescName); + auto iter = sensorMap_.find(sensorDescName); + if (iter != sensorMap_.end()) { + iter->second = it; + } else { + sensorMap_.insert(std::make_pair(sensorDescName, it)); + } + } + return singleDevSensors; +} + std::vector SensorService::GetSensorList() { std::lock_guard sensorLock(sensorsMutex_); @@ -484,7 +593,10 @@ 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)); + std::string sensorDescName; + GetSensorDescName({it.GetDeviceId(), it.GetSensorTypeId(), it.GetSensorId(), it.GetLocation()}, + sensorDescName); + sensorMap_.insert(std::make_pair(sensorDescName, it)); } return sensors_; } @@ -552,9 +664,12 @@ 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); + SensorDescription sensorDesc; + clientInfo_.ParseIndex(activeSensors[i], sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId, + sensorDesc.location); + int32_t ret = DisableSensor(sensorDesc, pid); if (ret != ERR_OK) { SEN_HILOGE("DisableSensor failed, ret:%{public}d", ret); } @@ -756,7 +871,7 @@ ErrCode SensorService::ResetSensors() return POWER_POLICY.ResetSensors(); } -void SensorService::ReportActiveInfo(int32_t sensorId, int32_t pid) +void SensorService::ReportActiveInfo(SensorDescription sensorDesc, int32_t pid) { CALL_LOG_ENTER; std::vector sessionList; @@ -767,9 +882,9 @@ 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); } @@ -819,5 +934,72 @@ ErrCode SensorService::SetDeviceStatus(uint32_t deviceStatus) clientInfo_.SetDeviceStatus(deviceStatus); return ERR_OK; } + +void SensorService::GetSensorDescName(SensorDescription sensorDesc, std::string &sensorDescName) +{ + sensorDescName = std::to_string(sensorDesc.deviceId) + "#" + std::to_string(sensorDesc.sensorType) + + "#" + std::to_string(sensorDesc.sensorId)+ "#" + std::to_string(sensorDesc.location); + return; +} + +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) { + std::string sensorDescName; + GetSensorDescName({info.deviceSensorInfo.deviceId, info.deviceSensorInfo.sensorType, + info.deviceSensorInfo.sensorId, info.deviceSensorInfo.location}, sensorDescName); + auto it = sensorMap_.find(sensorDescName); + 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); + } + std::string sensorDescName; + GetSensorDescName({info.deviceSensorInfo.deviceId, info.deviceSensorInfo.sensorType, + info.deviceSensorInfo.sensorId,info.deviceSensorInfo.location}, sensorDescName); + auto iter = sensorMap_.find(sensorDescName); + if (iter != sensorMap_.end()) { + sensorMap_.erase(iter); + } + } + 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 = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count() + }; + clientInfo_.SendMsgToClient(sensorPlugData); +} } // namespace Sensors } // namespace OHOS diff --git a/test/fuzztest/interfaces/BUILD.gn b/test/fuzztest/interfaces/BUILD.gn index 9012ffc2..054343a7 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 209be307..aaae2dd0 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 4365a141..1bff0bde 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 8ab0ebed..d509f67a 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 c379e577..b888d597 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", ] } diff --git a/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/BUILD.gn b/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/BUILD.gn new file mode 100644 index 00000000..2722a964 --- /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 00000000..e010f588 --- /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 00000000..2eb360c2 --- /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 00000000..a8585f44 --- /dev/null +++ b/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/sensoragentenhanced_fuzzer.cpp @@ -0,0 +1,123 @@ +/* + * 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 g_samplingInterval = 200000000; +constexpr int64_t g_reportInterval = 200000000; +constexpr size_t DATA_MIN_SIZE = sizeof(int32_t) + sizeof(SensorDescription) + sizeof(SensorUser); +} // 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); + + SensorDescription sensorDesc; + GetObject(sensorDesc, data + startPos, size - startPos); + + SensorUser user; + user.callback = SensorDataCallbackImpl; + + SensorInfo *sensorInfo = nullptr; + int32_t count = 0; + GetDeviceSensors(deviceId, &sensorInfo, &count); + + SubscribeSensorEnhanced(sensorDesc, &user); + SetBatchEnhanced(sensorDesc, &user, g_samplingInterval, g_reportInterval); + ActivateSensorEnhanced(sensorDesc, &user); + + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + + DeactivateSensorEnhanced(sensorDesc, &user); + UnsubscribeSensorEnhanced(sensorDesc, &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 00000000..7fd2dc60 --- /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 1b330732..54324326 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 7da3d06f..ac818842 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 35c128bd..5ce2fe2f 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 e541b0ae..037edae1 100644 --- a/test/fuzztest/services/BUILD.gn +++ b/test/fuzztest/services/BUILD.gn @@ -19,10 +19,12 @@ group("fuzztest") { testonly = true deps = [ "createdatachannelstub_fuzzer:fuzztest", + "destroyclientremoteobjectstub_fuzzer:fuzztest", "disableactiveinfocbstub_fuzzer:fuzztest", "enableactiveinfocbstub_fuzzer:fuzztest", "getactiveinfoliststub_fuzzer:fuzztest", "getallsensorsstub_fuzzer:fuzztest", + "getsensorlistbydevicestub_fuzzer:fuzztest", "resetsensorsstub_fuzzer:fuzztest", "resumesensorsstub_fuzzer:fuzztest", "sensordisablestub_fuzzer:fuzztest", @@ -30,6 +32,8 @@ group("fuzztest") { "sensoronremoterequest_fuzzer:fuzztest", "service/createsocketchannel_fuzzer:fuzztest", "service/getactiveinfolist_fuzzer:fuzztest", + "service/getsensordescname_fuzzer:fuzztest", + "service/getsensorlistbydevice_fuzzer:fuzztest", "service/registerclientdeathrecipient_fuzzer:fuzztest", "service/registerpermcallback_fuzzer:fuzztest", "service/reportactiveinfo_fuzzer:fuzztest", @@ -37,5 +41,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 12ef1264..ba1dda73 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/destroyclientremoteobjectstub_fuzzer/BUILD.gn b/test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/BUILD.gn new file mode 100644 index 00000000..e6f7d88f --- /dev/null +++ b/test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/BUILD.gn @@ -0,0 +1,75 @@ +# 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("DestroyClientRemoteObjectStubFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = + "$SUBSYSTEM_DIR/test/fuzztest/services/destroyclientremoteobjectstub_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/destroyclientremoteobjectstub_fuzzer", + "$SUBSYSTEM_DIR/utils/common/include", + "$SUBSYSTEM_DIR/utils/ipc/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "destroyclientremoteobjectstub_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 + ":DestroyClientRemoteObjectStubFuzzTest", + ] +} diff --git a/test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/corpus/init b/test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/corpus/init new file mode 100644 index 00000000..65af8ee8 --- /dev/null +++ b/test/fuzztest/services/destroyclientremoteobjectstub_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/destroyclientremoteobjectstub_fuzzer/destroyclientremoteobjectstub_fuzzer.cpp b/test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/destroyclientremoteobjectstub_fuzzer.cpp new file mode 100644 index 00000000..9c48a105 --- /dev/null +++ b/test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/destroyclientremoteobjectstub_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 "destroyclientremoteobjectstub_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 = "DestroyClientRemoteObjectStubFuzzTest", + .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_GET_ACTIVE_INFO_LIST), + 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/destroyclientremoteobjectstub_fuzzer/destroyclientremoteobjectstub_fuzzer.h b/test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/destroyclientremoteobjectstub_fuzzer.h new file mode 100644 index 00000000..7e75397c --- /dev/null +++ b/test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/destroyclientremoteobjectstub_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 DESTROY_CLIENT_REMOTE_OBJECT_STUB_FUZZER_H +#define DESTROY_CLIENT_REMOTE_OBJECT_STUB_FUZZER_H + +#define FUZZ_PROJECT_NAME "destroyclientremoteobjectstub_fuzzer" + +#endif // DESTROY_CLIENT_REMOTE_OBJECT_STUB_FUZZER_H + diff --git a/test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/project.xml b/test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/project.xml new file mode 100644 index 00000000..2eb360c2 --- /dev/null +++ b/test/fuzztest/services/destroyclientremoteobjectstub_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + diff --git a/test/fuzztest/services/disableactiveinfocbstub_fuzzer/BUILD.gn b/test/fuzztest/services/disableactiveinfocbstub_fuzzer/BUILD.gn index 8add4d57..dd764d1f 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 0c2bd42e..87ec6ccf 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 da44777e..1803c61a 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 c90b3a70..170affea 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 00000000..8d0cbaaf --- /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 00000000..65af8ee8 --- /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 00000000..77b68836 --- /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 00000000..1e0ef024 --- /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 00000000..2eb360c2 --- /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 91e0e642..4a4e6204 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 fb32eb60..89a1f910 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 1d91b758..22cc93e4 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/sensorenablestub_fuzzer/BUILD.gn b/test/fuzztest/services/sensorenablestub_fuzzer/BUILD.gn index 2480cf83..4dcb036d 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/sensoronremoterequest_fuzzer/BUILD.gn b/test/fuzztest/services/sensoronremoterequest_fuzzer/BUILD.gn index e7a593a1..16ae1890 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 ae530830..91d845d8 100644 --- a/test/fuzztest/services/service/createsocketchannel_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/createsocketchannel_fuzzer/BUILD.gn @@ -60,6 +60,7 @@ ohos_fuzztest("CreateSocketChannelFuzzTest") { "access_token:libnativetoken", "access_token:libtoken_setproc", "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 8641fdcc..58e75a36 100644 --- a/test/fuzztest/services/service/getactiveinfolist_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/getactiveinfolist_fuzzer/BUILD.gn @@ -60,6 +60,7 @@ ohos_fuzztest("GetActiveInfoListFuzzTest") { "access_token:libnativetoken", "access_token:libtoken_setproc", "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/getsensordescname_fuzzer/BUILD.gn b/test/fuzztest/services/service/getsensordescname_fuzzer/BUILD.gn new file mode 100644 index 00000000..bcf678cd --- /dev/null +++ b/test/fuzztest/services/service/getsensordescname_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("GetSensorDescNameFuzzTest") { + module_out_path = FUZZ_MODULE_OUT_PATH + + fuzz_config_file = "$SUBSYSTEM_DIR/test/fuzztest/services/service/getsensordescname_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/getsensordescname_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 = [ "getsensordescname_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 + ":GetSensorDescNameFuzzTest", + ] +} diff --git a/test/fuzztest/services/service/getsensordescname_fuzzer/corpus/init b/test/fuzztest/services/service/getsensordescname_fuzzer/corpus/init new file mode 100644 index 00000000..65af8ee8 --- /dev/null +++ b/test/fuzztest/services/service/getsensordescname_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/getsensordescname_fuzzer/getsensordescname_fuzzer.cpp b/test/fuzztest/services/service/getsensordescname_fuzzer/getsensordescname_fuzzer.cpp new file mode 100644 index 00000000..aa500787 --- /dev/null +++ b/test/fuzztest/services/service/getsensordescname_fuzzer/getsensordescname_fuzzer.cpp @@ -0,0 +1,106 @@ +/* + * 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 "getsensordescname_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 GetSensorDescNameFuzzTest(const uint8_t *data, size_t size) +{ + SetUpTestCase(); + SensorDescription sensorDesc; + size_t consumed = GetObject(sensorDesc, data, size); + if (consumed == 0) { + return false; + } + std::string sensorDescName; + g_service->GetSensorDescName(sensorDesc, sensorDescName); + 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::GetSensorDescNameFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/services/service/getsensordescname_fuzzer/getsensordescname_fuzzer.h b/test/fuzztest/services/service/getsensordescname_fuzzer/getsensordescname_fuzzer.h new file mode 100644 index 00000000..18d7acdc --- /dev/null +++ b/test/fuzztest/services/service/getsensordescname_fuzzer/getsensordescname_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_DESC_NAME_FUZZER_H +#define RET_SENSOR_DESC_NAME_FUZZER_H + +#define FUZZ_PROJECT_NAME "getsensordescname_fuzzer" + +#endif // RET_SENSOR_DESC_NAME_FUZZER_H + diff --git a/test/fuzztest/services/service/getsensordescname_fuzzer/project.xml b/test/fuzztest/services/service/getsensordescname_fuzzer/project.xml new file mode 100644 index 00000000..2eb360c2 --- /dev/null +++ b/test/fuzztest/services/service/getsensordescname_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 120 + + 2048 + + 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 00000000..e1bda175 --- /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 00000000..65af8ee8 --- /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 00000000..bdfa8a20 --- /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 00000000..8bbaae9c --- /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 00000000..2eb360c2 --- /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 2f25de6a..fcab3c3c 100644 --- a/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/BUILD.gn @@ -59,6 +59,7 @@ ohos_fuzztest("RegisterClientDeathRecipientFuzzTest") { "access_token:libnativetoken", "access_token:libtoken_setproc", "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 9daf65dc..360c5e05 100644 --- a/test/fuzztest/services/service/registerpermcallback_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/registerpermcallback_fuzzer/BUILD.gn @@ -59,6 +59,7 @@ ohos_fuzztest("RegisterPermCallbackFuzzTest") { "access_token:libnativetoken", "access_token:libtoken_setproc", "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 56fa0096..4d48ac6f 100644 --- a/test/fuzztest/services/service/reportactiveinfo_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/reportactiveinfo_fuzzer/BUILD.gn @@ -60,6 +60,7 @@ ohos_fuzztest("ReportActiveInfoFuzzTest") { "access_token:libnativetoken", "access_token:libtoken_setproc", "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 f597b240..48f8cf0c 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 26fe9783..8016a14f 100644 --- a/test/fuzztest/services/service/reportonchangedata_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/reportonchangedata_fuzzer/BUILD.gn @@ -60,6 +60,7 @@ ohos_fuzztest("ReportOnChangeDataFuzzTest") { "access_token:libnativetoken", "access_token:libtoken_setproc", "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/reportsensorsysevent_fuzzer/BUILD.gn b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/BUILD.gn index 881f1ff3..cae1bf0b 100644 --- a/test/fuzztest/services/service/reportsensorsysevent_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/BUILD.gn @@ -59,6 +59,7 @@ ohos_fuzztest("ReportSensorSysEventFuzzTest") { "access_token:libnativetoken", "access_token:libtoken_setproc", "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 8b0baf5a..08755b6e 100644 --- a/test/fuzztest/services/service/setdevicestatusservice_fuzzer/BUILD.gn +++ b/test/fuzztest/services/service/setdevicestatusservice_fuzzer/BUILD.gn @@ -59,6 +59,7 @@ ohos_fuzztest("SetDeviceStatusServiceFuzzTest") { "access_token:libnativetoken", "access_token:libtoken_setproc", "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 eb7123d8..bf49c685 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 00000000..2c7a5eb5 --- /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 00000000..65af8ee8 --- /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 00000000..2eb360c2 --- /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 00000000..a680a43e --- /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 00000000..6dc60c57 --- /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 1c6c640d..8484352a 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 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) { + 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,164 @@ 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 = 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 = 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"); + SensorDescription sensorDesc; + int32_t ret = SubscribeSensorEnhanced(sensorDesc, nullptr); + ASSERT_NE(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, SubscribeSensorEnhancedTest_002, TestSize.Level1) +{ + SEN_HILOGI("SubscribeSensorEnhancedTest_002 in"); + SensorDescription sensorDesc { + .deviceId = localDeviceId, + .sensorType = 1, + .sensorId = 0, + .location = 1, + }; + SensorUser user; + user.callback = SensorDataCallbackImpl; + int32_t ret = SubscribeSensorEnhanced(sensorDesc, &user); + ASSERT_EQ(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, UnsubscribeSensorEnhancedTest_001, TestSize.Level1) +{ + SEN_HILOGI("UnsubscribeSensorEnhancedTest_001 in"); + SensorDescription sensorDesc { + .deviceId = localDeviceId, + .sensorType = 1, + .sensorId = 0, + .location = 1, + }; + SensorUser user; + user.callback = SensorDataCallbackImpl; + int32_t ret = SubscribeSensorEnhanced(sensorDesc, &user); + ASSERT_EQ(ret, OHOS::ERR_OK); + ret = SetBatchEnhanced(sensorDesc, &user, 100000000, 100000000); + ASSERT_EQ(ret, OHOS::ERR_OK); + ret = ActivateSensorEnhanced(sensorDesc, &user); + ASSERT_EQ(ret, OHOS::ERR_OK); + ret = DeactivateSensorEnhanced(sensorDesc, &user); + ASSERT_EQ(ret, OHOS::ERR_OK); + ret = UnsubscribeSensorEnhanced(sensorDesc, &user); + ASSERT_EQ(ret, OHOS::ERR_OK); + +} + +HWTEST_F(SensorAgentTest, UnsubscribeSensorEnhancedTest_002, TestSize.Level1) +{ + SEN_HILOGI("UnsubscribeSensorEnhancedTest_002 in"); + SensorDescription sensorDesc; + int32_t ret = UnsubscribeSensorEnhanced(sensorDesc, nullptr); + ASSERT_NE(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, SetBatchEnhancedTest_001, TestSize.Level1) +{ + SEN_HILOGI("SetBatchEnhancedTest_001 in"); + SensorDescription sensorDesc; + int32_t ret = SetBatchEnhanced(sensorDesc, nullptr, 100, 100); + ASSERT_NE(ret, OHOS::ERR_OK); +} + + +HWTEST_F(SensorAgentTest, ActivateSensorEnhancedTest_001, TestSize.Level1) +{ + SEN_HILOGI("ActivateSensorEnhancedTest_001 in"); + SensorDescription sensorDesc; + int32_t ret = ActivateSensorEnhanced(sensorDesc, nullptr); + ASSERT_NE(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, DeactivateSensorEnhancedTest_001, TestSize.Level1) +{ + SEN_HILOGI("DeactivateSensorEnhancedTest_001 in"); + SensorDescription sensorDesc; + int32_t ret = DeactivateSensorEnhanced(sensorDesc, nullptr); + ASSERT_NE(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, SetModeEnhancedTest_001, TestSize.Level1) +{ + SEN_HILOGI("SetModeEnhancedTest_001 in"); + SensorDescription sensorDesc; + int32_t ret = SetModeEnhanced(sensorDesc, nullptr, 1); + ASSERT_NE(ret, OHOS::ERR_OK); +} + +HWTEST_F(SensorAgentTest, SetModeEnhancedTest_002, TestSize.Level1) +{ + SEN_HILOGI("SetModeEnhancedTest_002 in"); + SensorDescription sensorDesc { + .deviceId = localDeviceId, + .sensorType = 1, + .sensorId = 0, + .location = 1, + }; + SensorUser user; + user.callback = SensorDataCallbackImpl; + int32_t ret = SubscribeSensorEnhanced(sensorDesc, &user); + ASSERT_EQ(ret, OHOS::ERR_OK); + ret = SetModeEnhanced(sensorDesc, &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 9bc1b6f3..c6fef023 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/sensor.h b/utils/common/include/sensor.h index fabc175a..5f750659 100644 --- a/utils/common/include/sensor.h +++ b/utils/common/include/sensor.h @@ -20,6 +20,16 @@ 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 +60,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 +82,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 7ad633da..099d81b6 100644 --- a/utils/common/include/sensor_basic_data_channel.h +++ b/utils/common/include/sensor_basic_data_channel.h @@ -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 f988b678..26a715d5 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 5f27f2f1..7eea424f 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 abf410dd..2a678ec7 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 0cf8ca6e..d85c546e 100644 --- a/utils/common/src/print_sensor_data.cpp +++ b/utils/common/src/print_sensor_data.cpp @@ -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); @@ -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); @@ -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 68ec8f16..f1091453 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 857cf0de..c371d8c9 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 cf308e19..c12ca446 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_; -- Gitee