diff --git a/OAT.xml b/OAT.xml
index 23dfddadcf88eacdbc5d064c6686ece2c52c2856..9c356f7c11f79c7f46211368895a21d48a991e1c 100755
--- a/OAT.xml
+++ b/OAT.xml
@@ -67,8 +67,7 @@
-
-
+
diff --git a/bundle.json b/bundle.json
index 1f60658af12fe30ba5ec55111265e8d8825c517c..ed802e350852cc7ba68c2c8204160681e62a9df6 100644
--- a/bundle.json
+++ b/bundle.json
@@ -22,22 +22,19 @@
"bundle_framework",
"c_utils",
"hilog",
- "build_framework",
"hisysevent",
"napi",
"drivers_interface_sensor",
"access_token",
+ "hicollie",
"hitrace",
"ipc",
"memmgr",
"safwk",
"samgr",
"eventhandler",
- "hicollie",
"init",
- "selinux_adapter",
- "cJSON",
- "runtime_core"
+ "runtime_core"
],
"third_party": []
},
diff --git a/frameworks/js/ani/include/sensor_ani.h b/frameworks/js/ani/include/sensor_ani.h
index be11ac1711c37a0a90df2978ea5e93a182a7a27d..cc306ac64b052753ede234091df6688d0aa9ea19 100644
--- a/frameworks/js/ani/include/sensor_ani.h
+++ b/frameworks/js/ani/include/sensor_ani.h
@@ -117,15 +117,11 @@ public:
~AsyncCallbackInfo()
{
CALL_LOG_ENTER;
- if (type != ONCE_CALLBACK) {
- for (int32_t i = 0; i < CALLBACK_NUM; ++i) {
- if (callback[i] != nullptr) {
- SEN_HILOGD("Delete reference, i:%{public}d", i);
- env->GlobalReference_Delete(callback[i]);
- callback[i] = nullptr;
- env = nullptr;
- vm = nullptr;
- }
+ for (int32_t i = 0; i < CALLBACK_NUM; ++i) {
+ if (callback[i] != nullptr) {
+ SEN_HILOGD("Delete reference, i:%{public}d", i);
+ env->GlobalReference_Delete(callback[i]);
+ callback[i] = nullptr;
}
}
}
diff --git a/frameworks/js/ani/src/sensor_ani.cpp b/frameworks/js/ani/src/sensor_ani.cpp
index 84f037ec0cc57b6ffcc0c2137be575e0c43c75bf..f6532aad1385bace2328d07f22c5952acfb06522 100644
--- a/frameworks/js/ani/src/sensor_ani.cpp
+++ b/frameworks/js/ani/src/sensor_ani.cpp
@@ -628,13 +628,14 @@ static int32_t RemoveCallback(ani_env *env, int32_t sensorTypeId, ani_object cal
return callbackInfos.size();
}
-static int32_t UnsubscribeSensor(int32_t sensorTypeId)
+static int32_t UnaniSubscribeSensor(int32_t sensorTypeId)
{
int32_t ret = DeactivateSensor(sensorTypeId, &user);
if (ret != ERR_OK) {
SEN_HILOGE("DeactivateSensor failed");
return ret;
}
+
return UnsubscribeSensor(sensorTypeId, &user);
}
@@ -671,9 +672,9 @@ static void Off([[maybe_unused]] ani_env *env, ani_string type, ani_object callb
SEN_HILOGW("There are other client subscribe system js api as well, not need unsubscribe");
return;
}
- int32_t ret = UnsubscribeSensor(sensorTypeId);
+ int32_t ret = UnaniSubscribeSensor(sensorTypeId);
if (ret == PARAMETER_ERROR || ret == PERMISSION_DENIED) {
- ThrowBusinessError(env, ret, "UnsubscribeSensor fail");
+ ThrowBusinessError(env, ret, "UnaniSubscribeSensor fail");
}
return;
}
diff --git a/frameworks/js/napi/BUILD.gn b/frameworks/js/napi/BUILD.gn
index 7fde7b06be299fd86a6758fa692fb50a3e7181c7..23f37569a7584d99b2db2eb029b6ce939e2bd63f 100644
--- a/frameworks/js/napi/BUILD.gn
+++ b/frameworks/js/napi/BUILD.gn
@@ -45,6 +45,7 @@ ohos_shared_library("libsensor") {
"hilog:libhilog",
"ipc:ipc_single",
"napi:ace_napi",
+ "samgr:samgr_proxy",
]
relative_install_dir = "module"
part_name = "sensor"
diff --git a/frameworks/js/napi/include/sensor_napi_utils.h b/frameworks/js/napi/include/sensor_napi_utils.h
index 88bab2d7003bd0d59ed14c5011985a4582f28eab..1b5ce939f644d65ea47bb6140789a2ab684d7631 100644
--- a/frameworks/js/napi/include/sensor_napi_utils.h
+++ b/frameworks/js/napi/include/sensor_napi_utils.h
@@ -41,15 +41,14 @@ bool GetNativeFloat(const napi_env &env, const napi_value &value, float &number)
napi_value GetNapiInt32(const napi_env &env, int32_t number);
bool GetStringValue(const napi_env &env, const napi_value &value, string &result);
void EmitAsyncCallbackWork(sptr asyncCallbackInfo);
-void EmitUvEventLoop(sptr asyncCallbackInfo, std::shared_ptr cb);
+void EmitUvEventLoop(sptr asyncCallbackInfo);
void EmitPromiseWork(sptr asyncCallbackInfo);
bool ConvertToFailData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]);
bool ConvertToGeomagneticData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]);
bool ConvertToNumber(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]);
bool ConvertToArray(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]);
bool ConvertToRotationMatrix(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]);
-bool ConvertToSensorData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2],
- int32_t resultSize, std::shared_ptr data);
+bool ConvertToSensorData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]);
bool CreateNapiArray(const napi_env &env, float *data, int32_t dataLength, napi_value &result);
bool ConvertToSensorInfos(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]);
bool ConvertToSingleSensor(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2]);
diff --git a/frameworks/js/napi/src/sensor_js.cpp b/frameworks/js/napi/src/sensor_js.cpp
index 4e93c67aa252cec800bc1b400fe33aa29976beb0..a05aa59ff61334494f6a8a064b4b4197439dbbaf 100644
--- a/frameworks/js/napi/src/sensor_js.cpp
+++ b/frameworks/js/napi/src/sensor_js.cpp
@@ -75,26 +75,29 @@ static bool CheckSubscribe(SensorDescription sensorDesc)
return iter != g_onCallbackInfos.end();
}
-static bool CopySensorData(SensorEvent *event, std::shared_ptr cb)
+static bool copySensorData(sptr callbackInfo, SensorEvent *event)
{
+ CHKPF(callbackInfo);
CHKPF(event);
- CHKPF(cb);
int32_t sensorTypeId = event->sensorTypeId;
- cb->sensorTypeId = sensorTypeId;
- cb->dataLength = event->dataLen;
- cb->timestamp = event->timestamp;
- cb->sensorAccuracy = event->option;
+ callbackInfo->data.sensorData.sensorTypeId = sensorTypeId;
+ callbackInfo->data.sensorData.dataLength = event->dataLen;
+ callbackInfo->data.sensorData.timestamp = event->timestamp;
+ callbackInfo->data.sensorData.sensorAccuracy = event->option;
CHKPF(event->data);
if (event->dataLen < sizeof(float)) {
SEN_HILOGE("Event dataLen less than float size");
return false;
}
- if (sizeof(cb->data) < event->dataLen) {
- SEN_HILOGE("cb space is insufficient");
- return false;
- }
auto data = reinterpret_cast(event->data);
- if (memcpy_s(cb->data, sizeof(cb->data),
+ if (sensorTypeId == SENSOR_TYPE_ID_WEAR_DETECTION && callbackInfo->type == SUBSCRIBE_CALLBACK) {
+ std::lock_guard onBodyLock(g_bodyMutex);
+ g_bodyState = *data;
+ callbackInfo->data.sensorData.data[0] =
+ (fabs(g_bodyState - BODY_STATE_EXCEPT) < THRESHOLD) ? true : false;
+ return true;
+ }
+ if (memcpy_s(callbackInfo->data.sensorData.data, sizeof(callbackInfo->data.sensorData.data),
data, event->dataLen) != EOK) {
SEN_HILOGE("Copy data failed");
return false;
@@ -116,20 +119,13 @@ static void EmitSubscribeCallback(SensorEvent *event)
return;
}
std::lock_guard subscribeLock(g_mutex);
- std::shared_ptr cb = std::make_shared();
- if (!CopySensorData(event, cb)) {
- SEN_HILOGE("Copy sensor data failed");
- return;
- }
- auto data = reinterpret_cast(event->data);
auto callbacks = g_subscribeCallbacks[{event->deviceId, event->sensorTypeId, event->sensorId, event->location}];
for (auto &callback : callbacks) {
- if (event->sensorTypeId == SENSOR_TYPE_ID_WEAR_DETECTION && callback->type == SUBSCRIBE_CALLBACK) {
- std::lock_guard onBodyLock(g_bodyMutex);
- g_bodyState = *data;
- cb->data[0] = (fabs(g_bodyState - BODY_STATE_EXCEPT) < THRESHOLD) ? true : false;
+ if (!copySensorData(callback, event)) {
+ SEN_HILOGE("Copy sensor data failed");
+ continue;
}
- EmitUvEventLoop(callback, cb);
+ EmitUvEventLoop(callback);
}
}
@@ -140,14 +136,13 @@ static void EmitOnCallback(SensorEvent *event)
return;
}
std::lock_guard onCallbackLock(g_onMutex);
- std::shared_ptr cb = std::make_shared();
- if (!CopySensorData(event, cb)) {
- SEN_HILOGE("Copy sensor data failed");
- return;
- }
auto onCallbackInfos = g_onCallbackInfos[{event->deviceId, event->sensorTypeId, event->sensorId, event->location}];
for (auto &onCallbackInfo : onCallbackInfos) {
- EmitUvEventLoop(onCallbackInfo, cb);
+ if (!copySensorData(onCallbackInfo, event)) {
+ SEN_HILOGE("Copy sensor data failed");
+ continue;
+ }
+ EmitUvEventLoop(onCallbackInfo);
}
}
@@ -159,17 +154,16 @@ static void EmitOnceCallback(SensorEvent *event)
if (iter == g_onceCallbackInfos.end()) {
return;
}
- std::shared_ptr cb = std::make_shared();
- if (!CopySensorData(event, cb)) {
- SEN_HILOGE("Copy sensor data failed");
- return;
- }
auto &onceCallbackInfos = iter->second;
while (!onceCallbackInfos.empty()) {
auto onceCallbackInfo = onceCallbackInfos.front();
auto beginIter = onceCallbackInfos.begin();
onceCallbackInfos.erase(beginIter);
- EmitUvEventLoop(std::move(onceCallbackInfo), cb);
+ if (!copySensorData(onceCallbackInfo, event)) {
+ SEN_HILOGE("Copy sensor data failed");
+ continue;
+ }
+ EmitUvEventLoop(std::move(onceCallbackInfo));
}
g_onceCallbackInfos.erase({event->deviceId, event->sensorTypeId, event->sensorId, event->location});
@@ -203,10 +197,9 @@ void PlugDataCallbackImpl(SensorStatusEvent *plugEvent)
CALL_LOG_ENTER;
CHKPV(plugEvent);
std::lock_guard plugCallbackLock(g_plugMutex);
- std::shared_ptr cb = std::make_shared();
for (auto& callback : g_plugCallbackInfo) {
UpdatePlugInfo(plugEvent, callback);
- EmitUvEventLoop(callback, cb);
+ EmitUvEventLoop(callback);
}
}
@@ -1493,8 +1486,12 @@ static napi_value GetSingleSensorSync(napi_env env, napi_callback_info info)
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 == 0) {
- ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
+ if (status != napi_ok) {
+ ThrowErr(env, PARAMETER_ERROR, "Get the parameter info fail");
+ return result;
+ }
+ if (argc == 0) {
+ ThrowErr(env, PARAMETER_ERROR, "Number of parameter invalid");
return result;
}
int32_t sensorTypeId = INVALID_SENSOR_TYPE;
@@ -1813,8 +1810,7 @@ napi_value GetBodyState(napi_env env, napi_callback_info info)
std::lock_guard onBodyLock(g_bodyMutex);
asyncCallbackInfo->data.sensorData.data[0] =
(fabs(g_bodyState - BODY_STATE_EXCEPT) < THRESHOLD) ? true : false;
- std::shared_ptr cb = std::make_shared();
- EmitUvEventLoop(asyncCallbackInfo, cb);
+ EmitUvEventLoop(asyncCallbackInfo);
return nullptr;
}
diff --git a/frameworks/js/napi/src/sensor_napi_error.cpp b/frameworks/js/napi/src/sensor_napi_error.cpp
index e7855f64d746d9a570e5bc14a42b4ec64eafc88a..b2696e48dbc4163b35b87f01c1d81af4970b944a 100644
--- a/frameworks/js/napi/src/sensor_napi_error.cpp
+++ b/frameworks/js/napi/src/sensor_napi_error.cpp
@@ -29,7 +29,7 @@ napi_value CreateBusinessError(const napi_env &env, const int32_t errCode, const
napi_value msg = nullptr;
NAPI_CALL(env, napi_create_int32(env, errCode, &code));
NAPI_CALL(env, napi_create_string_utf8(env, errMessage.c_str(), NAPI_AUTO_LENGTH, &msg));
- NAPI_CALL(env, napi_create_error(env, nullptr, msg, &businessError));
+ napi_create_error(env, nullptr, msg, &businessError);
napi_set_named_property(env, businessError, "code", code);
return businessError;
}
diff --git a/frameworks/js/napi/src/sensor_napi_utils.cpp b/frameworks/js/napi/src/sensor_napi_utils.cpp
index cb649b8966f95f6f7593fcccb5a832244a076c9d..e6f9019db84ec4821d99dfac7ff02b81912a302c 100644
--- a/frameworks/js/napi/src/sensor_napi_utils.cpp
+++ b/frameworks/js/napi/src/sensor_napi_utils.cpp
@@ -30,7 +30,6 @@ namespace OHOS {
namespace Sensors {
namespace {
constexpr int32_t STRING_LENGTH_MAX = 64;
-constexpr int32_t RESULT_SIZE = 2;
} // namespace
static std::mutex g_sensorAttrListMutex;
bool IsSameValue(const napi_env &env, const napi_value &lhs, const napi_value &rhs)
@@ -62,7 +61,7 @@ bool GetFloatArray(const napi_env &env, const napi_value &value, vector &
CALL_LOG_ENTER;
uint32_t arrayLength = 0;
CHKNRF(env, napi_get_array_length(env, value, &arrayLength), "napi_get_array_length");
- for (uint32_t i = 0; i < arrayLength; ++i) {
+ for (size_t i = 0; i < arrayLength; ++i) {
napi_value element = nullptr;
CHKNRF(env, napi_get_element(env, value, i, &element), "napi_get_element");
CHKNCF(env, IsMatchType(env, element, napi_number), "Wrong argument type. Number or function expected");
@@ -194,6 +193,8 @@ std::map> g_sensorAttributeList = {
std::map g_convertfuncList = {
{FAIL, ConvertToFailData},
+ {ON_CALLBACK, ConvertToSensorData},
+ {ONCE_CALLBACK, ConvertToSensorData},
{GET_GEOMAGNETIC_FIELD, ConvertToGeomagneticData},
{GET_ALTITUDE, ConvertToNumber},
{GET_GEOMAGNETIC_DIP, ConvertToNumber},
@@ -206,6 +207,7 @@ std::map g_convertfuncList = {
{GET_SENSOR_LIST, ConvertToSensorInfos},
{GET_SINGLE_SENSOR, ConvertToSingleSensor},
{GET_BODY_STATE, ConvertToBodyData},
+ {SUBSCRIBE_CALLBACK, ConvertToSensorData},
{SUBSCRIBE_COMPASS, ConvertToCompass},
{SENSOR_STATE_CHANGE, ConvertToSensorState},
};
@@ -363,42 +365,34 @@ bool ConvertToSensorState(const napi_env &env, sptr asyncCall
return true;
}
-bool ConvertToSensorData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2],
- int32_t resultSize, std::shared_ptr data)
+bool ConvertToSensorData(const napi_env &env, sptr asyncCallbackInfo, napi_value result[2])
{
CHKPF(asyncCallbackInfo);
- CHKPF(data);
- CHKCF(!(resultSize < RESULT_SIZE), "result size Invalid");
- int32_t sensorTypeId = data->sensorTypeId;
+ int32_t sensorTypeId = asyncCallbackInfo->data.sensorData.sensorTypeId;
std::lock_guard sensorAttrListLock(g_sensorAttrListMutex);
CHKNCF(env, (g_sensorAttributeList.find(sensorTypeId) != g_sensorAttributeList.end()), "Invalid sensor type");
if (sensorTypeId == SENSOR_TYPE_ID_WEAR_DETECTION && asyncCallbackInfo->type == SUBSCRIBE_CALLBACK) {
- CHKNRF(env, napi_create_object(env, &result[1]), "napi_create_object");
- napi_value status = nullptr;
- CHKNRF(env, napi_get_boolean(env, data->data[0], &status),
- "napi_get_boolean");
- CHKNRF(env, napi_set_named_property(env, result[1], "value", status), "napi_set_named_property");
- return true;
+ return ConvertToBodyData(env, asyncCallbackInfo, result);
}
size_t size = g_sensorAttributeList[sensorTypeId].size();
- uint32_t dataLength = data->dataLength / sizeof(float);
+ uint32_t dataLength = asyncCallbackInfo->data.sensorData.dataLength / sizeof(float);
CHKNCF(env, (size <= dataLength), "Data length mismatch");
CHKNRF(env, napi_create_object(env, &result[1]), "napi_create_object");
napi_value message = nullptr;
auto sensorAttributes = g_sensorAttributeList[sensorTypeId];
for (uint32_t i = 0; i < size; ++i) {
- CHKNRF(env, napi_create_double(env, data->data[i], &message),
+ CHKNRF(env, napi_create_double(env, asyncCallbackInfo->data.sensorData.data[i], &message),
"napi_create_double");
CHKNRF(env, napi_set_named_property(env, result[1], sensorAttributes[i].c_str(), message),
"napi_set_named_property");
message = nullptr;
}
- CHKNRF(env, napi_create_int64(env, data->timestamp, &message),
+ CHKNRF(env, napi_create_int64(env, asyncCallbackInfo->data.sensorData.timestamp, &message),
"napi_create_int64");
CHKNRF(env, napi_set_named_property(env, result[1], "timestamp", message), "napi_set_named_property");
message = nullptr;
- CHKNRF(env, napi_create_int32(env, data->sensorAccuracy, &message),
+ CHKNRF(env, napi_create_int32(env, asyncCallbackInfo->data.sensorData.sensorAccuracy, &message),
"napi_create_int32");
CHKNRF(env, napi_set_named_property(env, result[1], "accuracy", message), "napi_set_named_property");
return true;
@@ -559,14 +553,20 @@ void DeleteWork(uv_work_t *work)
work = nullptr;
}
-void EmitUvEventLoop(sptr asyncCallbackInfo, std::shared_ptr cb)
+void EmitUvEventLoop(sptr asyncCallbackInfo)
{
CHKPV(asyncCallbackInfo);
- CHKPV(cb);
+ uv_loop_s *loop(nullptr);
+ CHKCV((napi_get_uv_event_loop(asyncCallbackInfo->env, &loop) == napi_ok), "napi_get_uv_event_loop fail");
+ CHKPV(loop);
+ uv_work_t *work = new(std::nothrow) uv_work_t;
+ CHKPV(work);
asyncCallbackInfo->IncStrongRef(nullptr);
- auto event = asyncCallbackInfo.GetRefPtr();
- auto task = [event, cb]() {
- sptr asyncCallbackInfo(static_cast(event));
+ work->data = asyncCallbackInfo.GetRefPtr();
+ int32_t ret = uv_queue_work_with_qos(loop, work, [] (uv_work_t *work) { }, [] (uv_work_t *work, int status) {
+ CHKPV(work);
+ sptr asyncCallbackInfo(static_cast(work->data));
+ DeleteWork(work);
/**
* After the asynchronous task is created, the asyncCallbackInfo reference count is reduced
* to 0 destruction, so you need to add 1 to the asyncCallbackInfo reference count when the
@@ -593,25 +593,14 @@ void EmitUvEventLoop(sptr asyncCallbackInfo, std::shared_ptr<
}
napi_value callResult = nullptr;
napi_value result[2] = {0};
- if (asyncCallbackInfo->type == ON_CALLBACK || asyncCallbackInfo->type == ONCE_CALLBACK ||
- asyncCallbackInfo->type == SUBSCRIBE_CALLBACK) {
- if (!ConvertToSensorData(env, asyncCallbackInfo, result, RESULT_SIZE, cb)) {
- SEN_HILOGE("ConvertToSensorData fail");
- napi_throw_error(env, nullptr, "ConvertToSensorData fail");
- ReleaseCallback(asyncCallbackInfo);
- napi_close_handle_scope(asyncCallbackInfo->env, scope);
- return;
- }
- } else {
- if (!(g_convertfuncList.find(asyncCallbackInfo->type) != g_convertfuncList.end())) {
- SEN_HILOGE("asyncCallbackInfo type is invalid");
- napi_throw_error(env, nullptr, "asyncCallbackInfo type is invalid");
- ReleaseCallback(asyncCallbackInfo);
- napi_close_handle_scope(asyncCallbackInfo->env, scope);
- return;
- }
- g_convertfuncList[asyncCallbackInfo->type](env, asyncCallbackInfo, result);
+ if (!(g_convertfuncList.find(asyncCallbackInfo->type) != g_convertfuncList.end())) {
+ SEN_HILOGE("asyncCallbackInfo type is invalid");
+ napi_throw_error(env, nullptr, "asyncCallbackInfo type is invalid");
+ ReleaseCallback(asyncCallbackInfo);
+ napi_close_handle_scope(asyncCallbackInfo->env, scope);
+ return;
}
+ g_convertfuncList[asyncCallbackInfo->type](env, asyncCallbackInfo, result);
if (napi_call_function(env, nullptr, callback, 1, &result[1], &callResult) != napi_ok) {
SEN_HILOGE("napi_call_function callback fail");
napi_throw_error(env, nullptr, "napi_call_function callback fail");
@@ -621,12 +610,11 @@ void EmitUvEventLoop(sptr asyncCallbackInfo, std::shared_ptr<
}
ReleaseCallback(asyncCallbackInfo);
napi_close_handle_scope(asyncCallbackInfo->env, scope);
- };
- auto ret = napi_send_event(asyncCallbackInfo->env, task, napi_eprio_immediate);
- if (ret != napi_ok) {
- SEN_HILOGE("Failed to SendEvent, ret:%{public}d", ret);
+ }, uv_qos_default);
+ if (ret != 0) {
+ SEN_HILOGE("uv_queue_work_with_qos fail");
asyncCallbackInfo->DecStrongRef(nullptr);
- ReleaseCallback(asyncCallbackInfo);
+ DeleteWork(work);
}
}
diff --git a/frameworks/native/BUILD.gn b/frameworks/native/BUILD.gn
index 74a921a99eb8732b54c568e69f64f24f839e5093..3d0d3a67caecc25e67c94cf0ec884bb411de19c4 100644
--- a/frameworks/native/BUILD.gn
+++ b/frameworks/native/BUILD.gn
@@ -90,18 +90,12 @@ ohos_shared_library("libsensor_client") {
"eventhandler:libeventhandler",
"hicollie:libhicollie",
"hilog:libhilog",
+ "hisysevent:libhisysevent",
+ "hitrace:hitrace_meter",
"ipc:ipc_single",
"samgr:samgr_proxy",
]
- if (hiviewdfx_hisysevent_enable) {
- external_deps += [ "hisysevent:libhisysevent" ]
- }
-
- if (hiviewdfx_hitrace_enable) {
- external_deps += [ "hitrace:hitrace_meter" ]
- }
-
innerapi_tags = [ "platformsdk_indirect" ]
part_name = "sensor"
subsystem_name = "sensors"
@@ -132,9 +126,6 @@ ohos_shared_library("sensor_interface_native") {
"src/sensor_algorithm.cpp",
]
- configs = [ ":sensor_private_config" ]
- public_configs = [ ":sensor_public_config" ]
-
branch_protector_ret = "pac_ret"
sanitize = {
cfi = true
@@ -145,6 +136,9 @@ ohos_shared_library("sensor_interface_native") {
ubsan = true
}
+ configs = [ ":sensor_private_config" ]
+ public_configs = [ ":sensor_public_config" ]
+
deps = [ "$SUBSYSTEM_DIR/frameworks/native:libsensor_client" ]
external_deps = [
diff --git a/frameworks/native/include/sensor_client_proxy.h b/frameworks/native/include/sensor_client_proxy.h
index a2a5ca18d68c05fb9785b24dd0dcfad1037ec1ef..3358373c634b3ea5474549f135886d8458539a52 100755
--- a/frameworks/native/include/sensor_client_proxy.h
+++ b/frameworks/native/include/sensor_client_proxy.h
@@ -12,10 +12,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
#ifndef SENSOR_CLIENT_PROXY_H
#define SENSOR_CLIENT_PROXY_H
-
+#include
#include "iremote_proxy.h"
#include "sensor_agent_type.h"
diff --git a/frameworks/native/include/sensor_service_client.h b/frameworks/native/include/sensor_service_client.h
index 8fa645e8e757ba331439da11aa9de020a75777b0..5a4dba62877f4fd46e1e89afc7f8ea298f2e60e8 100755
--- a/frameworks/native/include/sensor_service_client.h
+++ b/frameworks/native/include/sensor_service_client.h
@@ -62,7 +62,6 @@ private:
int32_t InitServiceClient();
void UpdateSensorInfoMap(const SensorDescription &sensorDesc, int64_t samplingPeriod, int64_t maxReportDelay);
void DeleteSensorInfoItem(const SensorDescription &sensorDesc);
- int32_t CreateSocketClientFd(int32_t &clientFd);
int32_t CreateSocketChannel();
void ReenableSensor();
void WriteHiSysIPCEvent(ISensorServiceIpcCode code, int32_t ret);
diff --git a/frameworks/native/src/fd_listener.cpp b/frameworks/native/src/fd_listener.cpp
index 807ca6d5a43347c69fd11b71dbd8b852fe8b2055..ddad6614ae38314607b73e1a529a6a7266b4863d 100644
--- a/frameworks/native/src/fd_listener.cpp
+++ b/frameworks/native/src/fd_listener.cpp
@@ -25,7 +25,7 @@ namespace Sensors {
using namespace OHOS::AppExecFwk;
namespace {
constexpr int32_t MAX_DATA_BUF_SIZE = 256;
-} // namespace
+}
void FdListener::SetChannel(SensorDataChannel *channel)
{
diff --git a/frameworks/native/src/geomagnetic_field.cpp b/frameworks/native/src/geomagnetic_field.cpp
index c05327c61a052ca9c04d3cd7cf24b2d7b0c5c978..43d11b29b3754468a56ec102a99f27d56dabccec 100644
--- a/frameworks/native/src/geomagnetic_field.cpp
+++ b/frameworks/native/src/geomagnetic_field.cpp
@@ -19,6 +19,7 @@
#include "sensor_utils.h"
+using namespace std;
using namespace OHOS::Sensors;
namespace {
constexpr float EARTH_MAJOR_AXIS_RADIUS = 6378.137f;
@@ -108,7 +109,7 @@ std::vector> polynomialsDerivative(GAUSSIAN_COEFFICIENT_DIMEN
std::vector relativeRadiusPower(GAUSSIAN_COEFFICIENT_DIMENSION + 2);
std::vector sinMLongitude(GAUSSIAN_COEFFICIENT_DIMENSION);
std::vector cosMLongitude(GAUSSIAN_COEFFICIENT_DIMENSION);
-} // namespace
+}
GeomagneticField::GeomagneticField(float latitude, float longitude, float altitude, int64_t timeMillis)
{
diff --git a/frameworks/native/src/sensor_agent_proxy.cpp b/frameworks/native/src/sensor_agent_proxy.cpp
index d86e4e87b113b0dd69e12844212f3f30a0136350..10a010f58e3c63e1b4a2e79d93c700e502b49b14 100644
--- a/frameworks/native/src/sensor_agent_proxy.cpp
+++ b/frameworks/native/src/sensor_agent_proxy.cpp
@@ -33,7 +33,7 @@ SensorInfoCheck sensorInfoCheck_;
std::mutex sensorActiveInfoMutex_;
SensorActiveInfo *sensorActiveInfos_ = nullptr;
int32_t sensorInfoCount_ = 0;
-} // namespace
+} // namespace
#define SEN_CLIENT SensorServiceClient::GetInstance()
std::recursive_mutex SensorAgentProxy::subscribeMutex_;
@@ -102,7 +102,7 @@ void SensorAgentProxy::SetIsChannelCreated(bool isChannelCreated)
int32_t SensorAgentProxy::CreateSensorDataChannel()
{
- SEN_HILOGI("In");
+ CALL_LOG_ENTER;
std::lock_guard chanelLock(chanelMutex_);
if (isChannelCreated_) {
SEN_HILOGI("The channel has already been created");
@@ -121,23 +121,20 @@ int32_t SensorAgentProxy::CreateSensorDataChannel()
SEN_HILOGE("Create data channel failed, ret:%{public}d", ret);
return ret;
}
- {
- SensorXcollie SensorXcollie("SensorAgentProxy:TransferDataChannel", XCOLLIE_TIMEOUT_5S);
- ret = SEN_CLIENT.TransferDataChannel(dataChannel_);
- }
+ SensorXcollie sensorXcollie("SensorAgentProxy:TransferDataChannel", XCOLLIE_TIMEOUT_5S);
+ ret = SEN_CLIENT.TransferDataChannel(dataChannel_);
if (ret != ERR_OK) {
auto destroyRet = dataChannel_->DestroySensorDataChannel();
SEN_HILOGE("Transfer data channel failed, ret:%{public}d, destroyRet:%{public}d", ret, destroyRet);
return ret;
}
isChannelCreated_ = true;
- SEN_HILOGI("Done");
return ERR_OK;
}
int32_t SensorAgentProxy::DestroySensorDataChannel()
{
- SEN_HILOGI("In");
+ CALL_LOG_ENTER;
std::lock_guard chanelLock(chanelMutex_);
if (!isChannelCreated_) {
SEN_HILOGI("Channel has been destroyed");
@@ -149,16 +146,13 @@ int32_t SensorAgentProxy::DestroySensorDataChannel()
SEN_HILOGE("Destroy data channel failed, ret:%{public}d", ret);
return ret;
}
- {
- SensorXcollie SensorXcollie("SensorAgentProxy:DestroyDataChannel", XCOLLIE_TIMEOUT_5S);
- ret = SEN_CLIENT.DestroyDataChannel();
- }
+ SensorXcollie sensorXcollie("SensorAgentProxy:DestroyDataChannel", XCOLLIE_TIMEOUT_5S);
+ ret = SEN_CLIENT.DestroyDataChannel();
if (ret != ERR_OK) {
SEN_HILOGE("Destroy service data channel fail, ret:%{public}d", ret);
return ret;
}
isChannelCreated_ = false;
- SEN_HILOGI("Done");
return ERR_OK;
}
@@ -187,11 +181,8 @@ int32_t SensorAgentProxy::ActivateSensor(const SensorDescription &sensorDesc, co
SEN_HILOGE("Subscribe user first");
return ERROR;
}
- int32_t ret = 0;
- {
- SensorXcollie SensorXcollie("SensorAgentProxy:EnableSensor", XCOLLIE_TIMEOUT_15S);
- ret = SEN_CLIENT.EnableSensor(sensorDesc, samplingInterval_, reportInterval_);
- }
+ SensorXcollie sensorXcollie("SensorAgentProxy:EnableSensor", XCOLLIE_TIMEOUT_15S);
+ int32_t ret = SEN_CLIENT.EnableSensor(sensorDesc, samplingInterval_, reportInterval_);
if (ret != 0) {
SEN_HILOGE("Enable sensor failed, ret:%{public}d", ret);
subscribeSet.erase(user);
@@ -212,8 +203,7 @@ int32_t SensorAgentProxy::DeactivateSensor(const SensorDescription &sensorDesc,
CHKPR(user, OHOS::Sensors::ERROR);
CHKPR(user->callback, OHOS::Sensors::ERROR);
std::lock_guard subscribeLock(subscribeMutex_);
- if (!(SEN_CLIENT.IsValid(sensorDesc) ||
- ((!SEN_CLIENT.IsValid(sensorDesc)) && subscribeMap_.find(sensorDesc) != subscribeMap_.end()))) {
+ if ((!SEN_CLIENT.IsValid(sensorDesc)) && subscribeMap_.find(sensorDesc) == subscribeMap_.end()) {
SEN_HILOGE("sensorDesc is invalid, deviceIndex:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d",
sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId);
return PARAMETER_ERROR;
@@ -234,15 +224,12 @@ int32_t SensorAgentProxy::DeactivateSensor(const SensorDescription &sensorDesc,
subscribeSet.erase(user);
if (subscribeSet.empty()) {
subscribeMap_.erase(sensorDesc);
- int32_t ret = 0;
- {
- if (!SEN_CLIENT.IsValid(sensorDesc)) {
- SEN_HILOGW("No need to call DisableSensor");
- return OHOS::Sensors::SUCCESS;
- }
- SensorXcollie SensorXcollie("SensorAgentProxy:DisableSensor", XCOLLIE_TIMEOUT_15S);
- ret = SEN_CLIENT.DisableSensor(sensorDesc);
+ if (!SEN_CLIENT.IsValid(sensorDesc)) {
+ SEN_HILOGW("No need to call DisableSensor");
+ return OHOS::Sensors::SUCCESS;
}
+ SensorXcollie sensorXcollie("SensorAgentProxy:DisableSensor", XCOLLIE_TIMEOUT_15S);
+ int32_t ret = SEN_CLIENT.DisableSensor(sensorDesc);
if (ret != 0) {
SEN_HILOGE("DisableSensor failed, ret:%{public}d", ret);
return ret;
@@ -325,8 +312,7 @@ int32_t SensorAgentProxy::UnsubscribeSensor(const SensorDescription &sensorDesc,
CHKPR(user->callback, OHOS::Sensors::ERROR);
{
std::lock_guard subscribeLock(subscribeMutex_);
- if (!(SEN_CLIENT.IsValid(sensorDesc) ||
- ((!SEN_CLIENT.IsValid(sensorDesc)) && unsubscribeMap_.find(sensorDesc) != unsubscribeMap_.end()))) {
+ if ((!SEN_CLIENT.IsValid(sensorDesc)) && unsubscribeMap_.find(sensorDesc) == unsubscribeMap_.end()) {
SEN_HILOGE("sensorDesc is invalid, deviceIndex:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d",
sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId);
return PARAMETER_ERROR;
@@ -399,11 +385,8 @@ void SensorAgentProxy::ClearSensorInfos() const
int32_t SensorAgentProxy::ConvertSensorInfos() const
{
CALL_LOG_ENTER;
- std::vector sensorList;
- {
- SensorXcollie SensorXcollie("SensorAgentProxy:GetSensorList", XCOLLIE_TIMEOUT_5S);
- sensorList = SEN_CLIENT.GetSensorList();
- }
+ SensorXcollie sensorXcollie("SensorAgentProxy:GetSensorList", XCOLLIE_TIMEOUT_5S);
+ std::vector sensorList = SEN_CLIENT.GetSensorList();
if (sensorList.empty()) {
SEN_HILOGE("Get sensor lists failed");
return ERROR;
@@ -473,7 +456,6 @@ int32_t SensorAgentProxy::GetDeviceSensors(int32_t deviceId, SensorInfo **single
}
}
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");
@@ -629,11 +611,8 @@ int32_t SensorAgentProxy::SuspendSensors(int32_t pid)
SEN_HILOGE("Pid is invalid, pid:%{public}d", pid);
return PARAMETER_ERROR;
}
- int32_t ret = 0;
- {
- SensorXcollie SensorXcollie("SensorAgentProxy:SuspendSensors", XCOLLIE_TIMEOUT_5S);
- ret = SEN_CLIENT.SuspendSensors(pid);
- }
+ SensorXcollie sensorXcollie("SensorAgentProxy:SuspendSensors", XCOLLIE_TIMEOUT_5S);
+ int32_t ret = SEN_CLIENT.SuspendSensors(pid);
if (ret != ERR_OK) {
SEN_HILOGD("Suspend sensors failed, ret:%{public}d", ret);
}
@@ -647,11 +626,8 @@ int32_t SensorAgentProxy::ResumeSensors(int32_t pid)
SEN_HILOGE("Pid is invalid, pid:%{public}d", pid);
return PARAMETER_ERROR;
}
- int32_t ret = 0;
- {
- SensorXcollie SensorXcollie("SensorAgentProxy:ResumeSensors", XCOLLIE_TIMEOUT_5S);
- ret = SEN_CLIENT.ResumeSensors(pid);
- }
+ SensorXcollie sensorXcollie("SensorAgentProxy:ResumeSensors", XCOLLIE_TIMEOUT_5S);
+ int32_t ret = SEN_CLIENT.ResumeSensors(pid);
if (ret != ERR_OK) {
SEN_HILOGD("Resume sensors failed, ret:%{public}d", ret);
}
@@ -674,11 +650,8 @@ int32_t SensorAgentProxy::GetSensorActiveInfos(int32_t pid,
sensorActiveInfos_ = nullptr;
}
std::vector activeInfoList;
- int32_t ret = 0;
- {
- SensorXcollie SensorXcollie("SensorAgentProxy:GetActiveInfoList", XCOLLIE_TIMEOUT_5S);
- ret = SEN_CLIENT.GetActiveInfoList(pid, activeInfoList);
- }
+ SensorXcollie sensorXcollie("SensorAgentProxy:GetActiveInfoList", XCOLLIE_TIMEOUT_5S);
+ int32_t ret = SEN_CLIENT.GetActiveInfoList(pid, activeInfoList);
if (ret != ERR_OK) {
SEN_HILOGE("Get active info list failed, ret:%{public}d", ret);
return ret;
@@ -712,11 +685,8 @@ int32_t SensorAgentProxy::Register(SensorActiveInfoCB callback)
{
CHKPR(callback, OHOS::Sensors::ERROR);
CHKPR(dataChannel_, INVALID_POINTER);
- int32_t ret = 0;
- {
- SensorXcollie SensorXcollie("SensorAgentProxy:Register", XCOLLIE_TIMEOUT_5S);
- ret = SEN_CLIENT.Register(callback, dataChannel_);
- }
+ SensorXcollie sensorXcollie("SensorAgentProxy:Register", XCOLLIE_TIMEOUT_5S);
+ int32_t ret = SEN_CLIENT.Register(callback, dataChannel_);
if (ret != ERR_OK) {
SEN_HILOGE("Register sensor active info callback failed, ret:%{public}d", ret);
}
@@ -726,11 +696,8 @@ int32_t SensorAgentProxy::Register(SensorActiveInfoCB callback)
int32_t SensorAgentProxy::Unregister(SensorActiveInfoCB callback)
{
CHKPR(callback, OHOS::Sensors::ERROR);
- int32_t ret = 0;
- {
- SensorXcollie SensorXcollie("SensorAgentProxy:Unregister", XCOLLIE_TIMEOUT_5S);
- ret = SEN_CLIENT.Unregister(callback);
- }
+ SensorXcollie sensorXcollie("SensorAgentProxy:Unregister", XCOLLIE_TIMEOUT_5S);
+ int32_t ret = SEN_CLIENT.Unregister(callback);
if (ret != ERR_OK) {
SEN_HILOGE("Unregister sensor active info callback failed, ret:%{public}d", ret);
}
@@ -739,11 +706,8 @@ int32_t SensorAgentProxy::Unregister(SensorActiveInfoCB callback)
int32_t SensorAgentProxy::ResetSensors() const
{
- int32_t ret = 0;
- {
- SensorXcollie SensorXcollie("SensorAgentProxy:ResetSensors", XCOLLIE_TIMEOUT_5S);
- ret = SEN_CLIENT.ResetSensors();
- }
+ SensorXcollie sensorXcollie("SensorAgentProxy:ResetSensors", XCOLLIE_TIMEOUT_5S);
+ int32_t ret = SEN_CLIENT.ResetSensors();
if (ret != ERR_OK) {
SEN_HILOGE("Reset sensors failed, ret:%{public}d", ret);
}
@@ -763,10 +727,7 @@ int32_t SensorAgentProxy::SubscribeSensorPlug(const SensorUser *user)
CHKPR(user->plugCallback, OHOS::Sensors::ERROR);
int32_t ret = 0;
- {
- SensorXcollie SensorXcollie("SensorAgentProxy:CreateClientRemoteObject()", XCOLLIE_TIMEOUT_5S);
- ret = SEN_CLIENT.CreateClientRemoteObject();
- }
+ ret = SEN_CLIENT.CreateClientRemoteObject();
if (ret != ERR_OK) {
SEN_HILOGE("CreateClientRemoteObject failed, ret:%{public}d", ret);
return ret;
@@ -831,7 +792,6 @@ bool SensorAgentProxy::UpdateSensorInfo(const SensorPlugData &info)
int32_t ret = 0;
if (subscribeMap_.find({info.deviceId, info.sensorTypeId, info.sensorId, info.location}) !=
subscribeMap_.end()) {
- SensorXcollie SensorXcollie("SensorAgentProxy:DisableSensor", XCOLLIE_TIMEOUT_15S);
ret = SEN_CLIENT.DisableSensor({info.deviceId, info.sensorTypeId, info.sensorId, info.location});
}
if (ret != 0) {
diff --git a/frameworks/native/src/sensor_client_stub.cpp b/frameworks/native/src/sensor_client_stub.cpp
index 81ac153fe46c05c8dcf6ca5091ec08d72a4851be..cdb914f876936a6f7b89923ce02bf89649adee1b 100644
--- a/frameworks/native/src/sensor_client_stub.cpp
+++ b/frameworks/native/src/sensor_client_stub.cpp
@@ -13,6 +13,7 @@
* limitations under the License.
*/
+#include
#include "sensor_client_stub.h"
#include "sensor_agent_proxy.h"
@@ -65,5 +66,5 @@ int32_t SensorClientStub::ProcessPlugEvent(const SensorPlugData &info)
SEN_HILOGD("Success to process plug event");
return NO_ERROR;
}
-} // namespace Sensors
-} // namespace OHOS
+} // namespace Sensors
+} // namespace OHOS
diff --git a/frameworks/native/src/sensor_service_client.cpp b/frameworks/native/src/sensor_service_client.cpp
index 42b7211845c1e3c22e4d022732f8845c928da761..1383bd75dd8bbc0e219a9a0170465a4ce9df5be4 100644
--- a/frameworks/native/src/sensor_service_client.cpp
+++ b/frameworks/native/src/sensor_service_client.cpp
@@ -798,22 +798,6 @@ void SensorServiceClient::Disconnect()
Close();
}
-int32_t SensorServiceClient::CreateSocketClientFd(int32_t &clientFd)
-{
-#ifdef HIVIEWDFX_HITRACE_ENABLE
- StartTrace(HITRACE_TAG_SENSORS, "CreateSocketChannel");
-#endif // HIVIEWDFX_HITRACE_ENABLE
- CHKPR(sensorClientStub_, INVALID_POINTER);
- auto remoteObject = sensorClientStub_->AsObject();
- CHKPR(remoteObject, INVALID_POINTER);
- int ret = sensorServer_->CreateSocketChannel(remoteObject, clientFd);
- WriteHiSysIPCEvent(ISensorServiceIpcCode::COMMAND_CREATE_SOCKET_CHANNEL, ret);
-#ifdef HIVIEWDFX_HITRACE_ENABLE
- FinishTrace(HITRACE_TAG_SENSORS);
-#endif // HIVIEWDFX_HITRACE_ENABLE
- return ret;
-}
-
int32_t SensorServiceClient::CreateSocketChannel()
{
CALL_LOG_ENTER;
@@ -825,8 +809,16 @@ int32_t SensorServiceClient::CreateSocketChannel()
std::lock_guard clientLock(clientMutex_);
CHKPR(sensorServer_, ERROR);
int32_t clientFd = -1;
- ret = CreateSocketClientFd(clientFd);
+#ifdef HIVIEWDFX_HITRACE_ENABLE
+ StartTrace(HITRACE_TAG_SENSORS, "CreateSocketChannel");
+#endif // HIVIEWDFX_HITRACE_ENABLE
+ CHKPR(sensorClientStub_, INVALID_POINTER);
+ ret = sensorServer_->CreateSocketChannel(sensorClientStub_->AsObject(), clientFd);
+ WriteHiSysIPCEvent(ISensorServiceIpcCode::COMMAND_CREATE_SOCKET_CHANNEL, ret);
fdsan_exchange_owner_tag(clientFd, 0, TAG);
+#ifdef HIVIEWDFX_HITRACE_ENABLE
+ FinishTrace(HITRACE_TAG_SENSORS);
+#endif // HIVIEWDFX_HITRACE_ENABLE
if (ret != ERR_OK || clientFd < 0) {
Close();
SEN_HILOGE("Create socket channel failed, ret:%{public}d", ret);
diff --git a/interfaces/inner_api/sensor_agent_type.h b/interfaces/inner_api/sensor_agent_type.h
index 3a020696efa24c687756871f2bcc9ad3976e3abc..4447b446f7f21bf5670cf9086cca6ab870830bbf 100644
--- a/interfaces/inner_api/sensor_agent_type.h
+++ b/interfaces/inner_api/sensor_agent_type.h
@@ -535,7 +535,7 @@ typedef struct HeadPostureData {
} HeadPostureData;
typedef struct DropDetectionData {
- float status = 0.0;
+ float status = 0.0F;
} DropDetectionData;
typedef struct SensorActiveInfo {
diff --git a/rust/utils/socket_ipc_rust_ffi/src/stream_buffer.rs b/rust/utils/socket_ipc_rust_ffi/src/stream_buffer.rs
index 35cb254f367d740ecb69f7150072ca68e91cf8b2..48b57faac06c1b14ad1a81986574c99b2f3eba8d 100644
--- a/rust/utils/socket_ipc_rust_ffi/src/stream_buffer.rs
+++ b/rust/utils/socket_ipc_rust_ffi/src/stream_buffer.rs
@@ -163,12 +163,10 @@ impl StreamBuffer {
}
}
fn get_error_status_remark(&self) -> *const c_char {
- // Creating a new C-compatible string will never fail,
- // because the supplied bytes always contain greater than 0.
- let s: CString = match self.rw_error_status {
- ErrorStatus::Ok => CString::new("OK").unwrap_or_default(),
- ErrorStatus::Read => CString::new("READ_ERROR").unwrap_or_default(),
- ErrorStatus::Write => CString::new("WRITE_ERROR").unwrap_or_default(),
+ let s: &[c_char] = match self.rw_error_status {
+ ErrorStatus::Ok => b"OK\0",
+ ErrorStatus::Read => b"READ_ERROR\0",
+ ErrorStatus::Write => b"WRITE_ERROR\0",
};
s.as_ptr()
}
diff --git a/rust/utils/socket_ipc_rust_ffi/src/stream_buffer/ffi.rs b/rust/utils/socket_ipc_rust_ffi/src/stream_buffer/ffi.rs
index a72de8fd503959e33d74e7d80d32f112342d966b..a56ef5dc5bfed0dde1f8edaf18a5a55d5b93a72c 100644
--- a/rust/utils/socket_ipc_rust_ffi/src/stream_buffer/ffi.rs
+++ b/rust/utils/socket_ipc_rust_ffi/src/stream_buffer/ffi.rs
@@ -176,7 +176,6 @@ pub unsafe extern "C" fn StreamBufferChkRWError(object: *const StreamBuffer) ->
pub unsafe extern "C" fn StreamBufferGetErrorStatusRemark(object: *const StreamBuffer) -> *const c_char {
info!(LOG_LABEL, "enter StreamBufferGetErrorStatusRemark");
if let Some(obj) = StreamBuffer::as_ref(object) {
- // SAFETY: The Rust side creates a CString string and this function should be called only here
obj.get_error_status_remark()
} else {
std::ptr::null()
diff --git a/services/BUILD.gn b/services/BUILD.gn
index 20d195ed7e7e4f9c44af1babb4674d717542ee8d..9ec077d011ff7e8c624017afda23ae749cde96c3 100644
--- a/services/BUILD.gn
+++ b/services/BUILD.gn
@@ -74,6 +74,8 @@ ohos_shared_library("libsensor_service") {
"c_utils:utils",
"hicollie:libhicollie",
"hilog:libhilog",
+ "hisysevent:libhisysevent",
+ "hitrace:hitrace_meter",
"init:libbegetutil",
"ipc:ipc_single",
"safwk:system_ability_fwk",
@@ -93,14 +95,6 @@ ohos_shared_library("libsensor_service") {
defines += [ "MSDP_MOTION_ENABLE" ]
}
- if (hiviewdfx_hisysevent_enable) {
- external_deps += [ "hisysevent:libhisysevent" ]
- }
-
- if (hiviewdfx_hitrace_enable) {
- external_deps += [ "hitrace:hitrace_meter" ]
- }
-
if (hdf_drivers_interface_sensor) {
sources += [
"hdi_connection/adapter/src/hdi_connection.cpp",
@@ -194,6 +188,8 @@ ohos_static_library("libsensor_service_static") {
"c_utils:utils",
"hicollie:libhicollie",
"hilog:libhilog",
+ "hisysevent:libhisysevent",
+ "hitrace:hitrace_meter",
"init:libbegetutil",
"ipc:ipc_single",
"safwk:system_ability_fwk",
@@ -213,14 +209,6 @@ ohos_static_library("libsensor_service_static") {
defines += [ "MSDP_MOTION_ENABLE" ]
}
- if (hiviewdfx_hisysevent_enable) {
- external_deps += [ "hisysevent:libhisysevent" ]
- }
-
- if (hiviewdfx_hitrace_enable) {
- external_deps += [ "hitrace:hitrace_meter" ]
- }
-
if (hdf_drivers_interface_sensor) {
sources += [
"hdi_connection/adapter/src/hdi_connection.cpp",
diff --git a/services/hdi_connection/adapter/include/hdi_connection.h b/services/hdi_connection/adapter/include/hdi_connection.h
index 0adb853104d1af6dc48ca5b3b4380182c4bfca84..b3d6a052048f26038a5845ceb775b658078eab77 100644
--- a/services/hdi_connection/adapter/include/hdi_connection.h
+++ b/services/hdi_connection/adapter/include/hdi_connection.h
@@ -50,11 +50,10 @@ private:
void RegisterHdiDeathRecipient();
void UnregisterHdiDeathRecipient();
void Reconnect();
- void ReEnableSensor();
void UpdateSensorBasicInfo(const SensorDescription &sensorDesc, int64_t samplingPeriodNs, int64_t maxReportDelayNs);
void SetSensorBasicInfoState(const SensorDescription &sensorDesc, bool state);
void DeleteSensorBasicInfoState(const SensorDescription &sensorDesc);
};
-} // namespace Sensors
-} // namespace OHOS
-#endif // HDI_CONNECTION_H
\ No newline at end of file
+} // namespace Sensors
+} // namespace OHOS
+#endif // HDI_CONNECTION_H
\ 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 bead5ae9548e7d239bc6c44029924aacbe1a08b9..e587314823059a1268f19e5d38404df26ccb1838 100644
--- a/services/hdi_connection/adapter/src/hdi_connection.cpp
+++ b/services/hdi_connection/adapter/src/hdi_connection.cpp
@@ -61,7 +61,7 @@ int32_t HdiConnection::ConnectHdi()
CALL_LOG_ENTER;
int32_t retry = 0;
while (retry < GET_HDI_SERVICE_COUNT) {
- std::lock_guard sensorInterface(g_sensorInterfaceMutex);
+ std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex);
g_sensorInterface = ISensorInterface::Get();
if (g_sensorInterface != nullptr) {
SEN_HILOGI("Connect v3_0 hdi success");
@@ -80,14 +80,14 @@ 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 v3_0 hdi failed");
+ SEN_HILOGE("Connect V3_0 hdi failed");
return ERR_NO_INIT;
}
int32_t HdiConnection::GetSensorList(std::vector &sensorList)
{
CALL_LOG_ENTER;
- std::lock_guard sensorInterface(g_sensorInterfaceMutex);
+ std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex);
CHKPR(g_sensorInterface, ERR_NO_INIT);
std::vector sensorInfos;
SensorXcollie sensorXcollie("HdiConnection:GetSensorList", XCOLLIE_TIMEOUT_5S);
@@ -132,7 +132,7 @@ int32_t HdiConnection::EnableSensor(const SensorDescription &sensorDesc)
{
SEN_HILOGI("In, deviceIndex:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d",
sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId);
- std::lock_guard sensorInterface(g_sensorInterfaceMutex);
+ std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex);
CHKPR(g_sensorInterface, ERR_NO_INIT);
SensorXcollie sensorXcollie("HdiConnection:EnableSensor", XCOLLIE_TIMEOUT_5S);
int32_t ret = g_sensorInterface->Enable({sensorDesc.deviceId, sensorDesc.sensorType,
@@ -155,7 +155,7 @@ int32_t HdiConnection::DisableSensor(const SensorDescription &sensorDesc)
{
SEN_HILOGI("In, deviceIndex:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d",
sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId);
- std::lock_guard sensorInterface(g_sensorInterfaceMutex);
+ std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex);
CHKPR(g_sensorInterface, ERR_NO_INIT);
SensorXcollie sensorXcollie("HdiConnection:DisableSensor", XCOLLIE_TIMEOUT_5S);
int32_t ret = g_sensorInterface->Disable({sensorDesc.deviceId, sensorDesc.sensorType,
@@ -176,7 +176,7 @@ int32_t HdiConnection::DisableSensor(const SensorDescription &sensorDesc)
int32_t HdiConnection::SetBatch(const SensorDescription &sensorDesc, int64_t samplingInterval, int64_t reportInterval)
{
- std::lock_guard sensorInterface(g_sensorInterfaceMutex);
+ std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex);
CHKPR(g_sensorInterface, ERR_NO_INIT);
SensorXcollie sensorXcollie("HdiConnection:SetBatch", XCOLLIE_TIMEOUT_5S);
int32_t ret = g_sensorInterface->SetBatch({sensorDesc.deviceId, sensorDesc.sensorType,
@@ -196,7 +196,7 @@ int32_t HdiConnection::SetBatch(const SensorDescription &sensorDesc, int64_t sam
int32_t HdiConnection::SetMode(const SensorDescription &sensorDesc, int32_t mode)
{
CALL_LOG_ENTER;
- std::lock_guard sensorInterface(g_sensorInterfaceMutex);
+ std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex);
CHKPR(g_sensorInterface, ERR_NO_INIT);
SensorXcollie sensorXcollie("HdiConnection:SetMode", XCOLLIE_TIMEOUT_5S);
int32_t ret = g_sensorInterface->SetMode({sensorDesc.deviceId, sensorDesc.sensorType,
@@ -216,7 +216,7 @@ int32_t HdiConnection::RegisterDataReport(ReportDataCb cb, sptr sensorInterface(g_sensorInterfaceMutex);
+ std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex);
CHKPR(g_sensorInterface, ERR_NO_INIT);
SensorXcollie sensorXcollie("HdiConnection:RegisterDataReport", XCOLLIE_TIMEOUT_5S);
int32_t ret = g_sensorInterface->RegisterAsync(0, g_eventCallback);
@@ -237,17 +237,20 @@ int32_t HdiConnection::DestroyHdiConnection()
{
CALL_LOG_ENTER;
{
- std::lock_guard sensorInterface(g_sensorInterfaceMutex);
+ std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex);
CHKPR(g_sensorInterface, ERR_NO_INIT);
- SensorXcollie unregisterAsyncXcollie("HdiConnection:UnregisterAsync", XCOLLIE_TIMEOUT_5S);
- int32_t ret = g_sensorInterface->UnregisterAsync(DEFAULT_GROUP_ID, g_eventCallback);
- if (ret != ERR_OK) {
+ int32_t ret = 0;
+ {
+ SensorXcollie unregisterAsyncXcollie("HdiConnection:UnregisterAsync", XCOLLIE_TIMEOUT_5S);
+ ret = g_sensorInterface->UnregisterAsync(DEFAULT_GROUP_ID, g_eventCallback);
+ if (ret != ERR_OK) {
#ifdef HIVIEWDFX_HISYSEVENT_ENABLE
- HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "HDF_SERVICE_EXCEPTION",
- HiSysEvent::EventType::FAULT, "PKG_NAME", "DestroyHdiConnection", "ERROR_CODE", ret);
+ HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "HDF_SERVICE_EXCEPTION",
+ HiSysEvent::EventType::FAULT, "PKG_NAME", "DestroyHdiConnection", "ERROR_CODE", ret);
#endif // HIVIEWDFX_HISYSEVENT_ENABLE
- SEN_HILOGE("UnregisterAsync is failed");
- return ret;
+ SEN_HILOGE("UnregisterAsync is failed");
+ return ret;
+ }
}
SensorXcollie unRegSensorPlugCallBackXcollie("HdiConnection:UnRegSensorPlugCallBack", XCOLLIE_TIMEOUT_5S);
ret = g_sensorInterface->UnRegSensorPlugCallBack(g_plugCallback);
@@ -270,7 +273,7 @@ int32_t HdiConnection::RegSensorPlugCallback(DevicePlugCallback cb)
{
CALL_LOG_ENTER;
CHKPR(cb, ERR_NO_INIT);
- std::lock_guard sensorInterface(g_sensorInterfaceMutex);
+ std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex);
CHKPR(g_sensorInterface, ERR_NO_INIT);
reportPlugDataCb_ = cb;
SensorXcollie sensorXcollie("HdiConnection:RegSensorPlugCallback", XCOLLIE_TIMEOUT_5S);
@@ -369,7 +372,7 @@ void HdiConnection::RegisterHdiDeathRecipient()
void HdiConnection::UnregisterHdiDeathRecipient()
{
CALL_LOG_ENTER;
- std::lock_guard sensorInterface(g_sensorInterfaceMutex);
+ std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex);
CHKPV(g_sensorInterface);
CHKPV(hdiDeathObserver_);
SensorXcollie sensorXcollie("HdiConnection:UnregisterHdiDeathRecipient", XCOLLIE_TIMEOUT_5S);
@@ -383,7 +386,7 @@ void HdiConnection::ProcessDeathObserver(const wptr &object)
CHKPV(hdiService);
CHKPV(hdiDeathObserver_);
{
- std::lock_guard sensorInterface(g_sensorInterfaceMutex);
+ std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex);
hdiService->RemoveDeathRecipient(hdiDeathObserver_);
g_eventCallback = nullptr;
}
@@ -400,15 +403,18 @@ void HdiConnection::ReEnableSensor()
sensorInfo.first.deviceId, sensorInfo.first.sensorType, sensorInfo.first.sensorId);
continue;
}
- SensorXcollie setBatchXcollie("HdiConnection:Reconnect:SetBatch", XCOLLIE_TIMEOUT_5S);
- int32_t ret = g_sensorInterface->SetBatch({sensorInfo.first.deviceId, sensorInfo.first.sensorType,
- sensorInfo.first.sensorId, sensorInfo.first.location},
- info.GetSamplingPeriodNs(), info.GetMaxReportDelayNs());
- if (ret != ERR_OK) {
- SEN_HILOGE("deviceIndex:%{public}d, sensortype:%{public}d, sensorId:%{public}d set batch fail,"
- "err:%{public}d", sensorInfo.first.deviceId, sensorInfo.first.sensorType, sensorInfo.first.sensorId,
- ret);
- continue;
+ int32_t ret = 0;
+ {
+ SensorXcollie setBatchXcollie("HdiConnection:Reconnect:SetBatch", XCOLLIE_TIMEOUT_5S);
+ ret = g_sensorInterface->SetBatch({sensorInfo.first.deviceId, sensorInfo.first.sensorType,
+ sensorInfo.first.sensorId, sensorInfo.first.location},
+ info.GetSamplingPeriodNs(), info.GetMaxReportDelayNs());
+ if (ret != ERR_OK) {
+ SEN_HILOGE("deviceIndex:%{public}d, sensortype:%{public}d, sensorId:%{public}d set batch fail,"
+ "err:%{public}d", sensorInfo.first.deviceId, sensorInfo.first.sensorType, sensorInfo.first.sensorId,
+ ret);
+ continue;
+ }
}
SensorXcollie enableXcollie("HdiConnection:Reconnect:ReEnable", XCOLLIE_TIMEOUT_5S);
ret = g_sensorInterface->Enable({sensorInfo.first.deviceId, sensorInfo.first.sensorType,
@@ -430,12 +436,14 @@ void HdiConnection::Reconnect()
return;
}
{
- std::lock_guard sensorInterface(g_sensorInterfaceMutex);
- SensorXcollie registerXcollie("HdiConnection:Reconnect:RegisterAsync", XCOLLIE_TIMEOUT_5S);
- ret = g_sensorInterface->RegisterAsync(DEFAULT_GROUP_ID, g_eventCallback);
- if (ret != ERR_OK) {
- SEN_HILOGE("RegisterAsync callback fail");
- return;
+ std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex);
+ {
+ SensorXcollie registerXcollie("HdiConnection:Reconnect:RegisterAsync", XCOLLIE_TIMEOUT_5S);
+ ret = g_sensorInterface->RegisterAsync(DEFAULT_GROUP_ID, g_eventCallback);
+ if (ret != ERR_OK) {
+ SEN_HILOGE("RegisterAsync callback fail");
+ return;
+ }
}
SensorXcollie regSensorPlugCallBackXcollie("HdiConnection:Reconnect:RegSensorPlugCallBack", XCOLLIE_TIMEOUT_5S);
ret = g_sensorInterface->RegSensorPlugCallBack(g_plugCallback);
@@ -450,14 +458,14 @@ void HdiConnection::Reconnect()
SEN_HILOGE("Get sensor list fail");
return;
}
- std::lock_guard sensorInterface(g_sensorInterfaceMutex);
+ std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex);
ReEnableSensor();
}
int32_t HdiConnection::GetSensorListByDevice(int32_t deviceId, std::vector &singleDevSensors)
{
CALL_LOG_ENTER;
- std::lock_guard sensorInterface(g_sensorInterfaceMutex);
+ std::lock_guard sensorInterfaceLock(g_sensorInterfaceMutex);
CHKPR(g_sensorInterface, ERR_NO_INIT);
std::vector sensorInfos;
SensorXcollie sensorXcollie("HdiConnection:GetSensorListByDevice", XCOLLIE_TIMEOUT_5S);
diff --git a/services/hdi_connection/interface/src/sensor_hdi_connection.cpp b/services/hdi_connection/interface/src/sensor_hdi_connection.cpp
index f0ba3408bf246189a55dc04378fcddd63c13cbe6..8cd98e33d5213a8b53ed43d1d45038a5aeddec50 100644
--- a/services/hdi_connection/interface/src/sensor_hdi_connection.cpp
+++ b/services/hdi_connection/interface/src/sensor_hdi_connection.cpp
@@ -37,7 +37,7 @@ namespace {
#ifdef BUILD_VARIANT_ENG
constexpr float MAX_RANGE = 9999.0;
constexpr float POWER = 20.0;
-constexpr float RESOLUTION = 0.000001;
+constexpr float RESOLITION = 0.000001;
constexpr float MIN_SAMPLE_PERIOD_NS = 100000000;
constexpr float MAX_SAMPLE_PERIOD_NS = 1000000000;
const std::string VERSION_NAME = "1.0.1";
@@ -148,7 +148,7 @@ Sensor SensorHdiConnection::GenerateColorSensor()
sensorColor.SetMaxRange(MAX_RANGE);
sensorColor.SetSensorName("sensor_color");
sensorColor.SetVendorName("default_color");
- sensorColor.SetResolution(RESOLUTION);
+ sensorColor.SetResolution(RESOLITION);
sensorColor.SetPower(POWER);
sensorColor.SetMinSamplePeriodNs(MIN_SAMPLE_PERIOD_NS);
sensorColor.SetMaxSamplePeriodNs(MAX_SAMPLE_PERIOD_NS);
@@ -167,7 +167,7 @@ Sensor SensorHdiConnection::GenerateSarSensor()
sensorSar.SetMaxRange(MAX_RANGE);
sensorSar.SetSensorName("sensor_sar");
sensorSar.SetVendorName("default_sar");
- sensorSar.SetResolution(RESOLUTION);
+ sensorSar.SetResolution(RESOLITION);
sensorSar.SetPower(POWER);
sensorSar.SetMinSamplePeriodNs(MIN_SAMPLE_PERIOD_NS);
sensorSar.SetMaxSamplePeriodNs(MAX_SAMPLE_PERIOD_NS);
@@ -186,7 +186,7 @@ Sensor SensorHdiConnection::GenerateHeadPostureSensor()
sensorHeadPosture.SetMaxRange(MAX_RANGE);
sensorHeadPosture.SetSensorName("sensor_headPosture");
sensorHeadPosture.SetVendorName("default_headPosture");
- sensorHeadPosture.SetResolution(RESOLUTION);
+ sensorHeadPosture.SetResolution(RESOLITION);
sensorHeadPosture.SetPower(POWER);
sensorHeadPosture.SetMinSamplePeriodNs(MIN_SAMPLE_PERIOD_NS);
sensorHeadPosture.SetMaxSamplePeriodNs(MAX_SAMPLE_PERIOD_NS);
@@ -205,7 +205,7 @@ Sensor SensorHdiConnection::GenerateProximitySensor()
sensorProximity.SetMaxRange(MAX_RANGE);
sensorProximity.SetSensorName("sensor_proximity1");
sensorProximity.SetVendorName("default_proximity1");
- sensorProximity.SetResolution(RESOLUTION);
+ sensorProximity.SetResolution(RESOLITION);
sensorProximity.SetPower(POWER);
sensorProximity.SetMinSamplePeriodNs(MIN_SAMPLE_PERIOD_NS);
sensorProximity.SetMaxSamplePeriodNs(MAX_SAMPLE_PERIOD_NS);
diff --git a/services/include/client_info.h b/services/include/client_info.h
index 95c7457ba6a81c95b0d5ccfeef8623c212cbb6dc..d112935ffe379c781421e331b5a22ec46b46da42 100644
--- a/services/include/client_info.h
+++ b/services/include/client_info.h
@@ -83,7 +83,7 @@ public:
void SaveSensorClient(const sptr &sensorClient);
void DestroySensorClient(const sptr &sensorClient);
void SendMsgToClient(SensorPlugData info);
- bool IsClientSubscribe();
+ bool IsSubscribe();
private:
DISALLOW_COPY_AND_MOVE(ClientInfo);
@@ -109,6 +109,6 @@ private:
std::atomic deviceStatus_;
std::vector> sensorClients_;
};
-} // namespace Sensors
-} // namespace OHOS
-#endif // CLIENT_INFO_H
+} // namespace Sensors
+} // namespace OHOS
+#endif // CLIENT_INFO_H
diff --git a/services/src/client_info.cpp b/services/src/client_info.cpp
index 70a33c0159d14122990d1eea5f1395ae2d192e78..c8ff1c6abe8e6883ddeb72be0ae5d54d3412e0cd 100644
--- a/services/src/client_info.cpp
+++ b/services/src/client_info.cpp
@@ -37,7 +37,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;
-} // namespace
+} // namespace
std::unordered_map> ClientInfo::userGrantPermMap_ = {
{ ACTIVITY_MOTION_PERMISSION, { SENSOR_TYPE_ID_PEDOMETER_DETECTION, SENSOR_TYPE_ID_PEDOMETER } },
@@ -865,7 +865,7 @@ void ClientInfo::SendMsgToClient(SensorPlugData info)
}
}
-bool ClientInfo::IsClientSubscribe()
+bool ClientInfo::IsSubscribe()
{
std::lock_guard clientLock(clientMutex_);
return !clientMap_.empty();
diff --git a/services/src/sensor_data_processer.cpp b/services/src/sensor_data_processer.cpp
index cce914391223fe04294da6bdbfed6b9ed6ce1bc4..c3032135f715dfbe7ffb8c0d22d4b52fe3707072 100644
--- a/services/src/sensor_data_processer.cpp
+++ b/services/src/sensor_data_processer.cpp
@@ -357,5 +357,5 @@ int32_t SensorDataProcesser::DataThread(sptr dataProcesser,
}
} while (1);
}
-} // namespace Sensors
-} // namespace OHOS
+} // namespace Sensors
+} // namespace OHOS
diff --git a/services/src/sensor_service.cpp b/services/src/sensor_service.cpp
index 3cf324c4516690adc84c3df31a62d1a61d0605f1..40348801b038ef5627bd06d58aeafe83394654e2 100644
--- a/services/src/sensor_service.cpp
+++ b/services/src/sensor_service.cpp
@@ -24,6 +24,7 @@
#ifdef HIVIEWDFX_HISYSEVENT_ENABLE
#include "hisysevent.h"
#endif // HIVIEWDFX_HISYSEVENT_ENABLE
+#include "iservice_registry.h"
#ifdef MEMMGR_ENABLE
#include "mem_mgr_client.h"
#endif // MEMMGR_ENABLE
@@ -499,7 +500,7 @@ ErrCode SensorService::SensorReportEvent(const SensorDescription &sensorDesc, in
ErrCode SensorService::DisableSensor(const SensorDescription &sensorDesc, int32_t pid)
{
CALL_LOG_ENTER;
- if (!(CheckSensorId(sensorDesc) || ((!CheckSensorId(sensorDesc)) && clientInfo_.GetSensorState(sensorDesc)))) {
+ if ((!CheckSensorId(sensorDesc)) && (!clientInfo_.GetSensorState(sensorDesc))) {
SEN_HILOGE("sensorDesc is invalid");
return ERR_NO_INIT;
}
@@ -529,7 +530,7 @@ ErrCode SensorService::DisableSensor(const SensorDescription &sensorDesc, int32_
clientInfo_.ClearDataQueue(sensorDesc);
int32_t ret = sensorManager_.AfterDisableSensor(sensorDesc);
#ifdef MEMMGR_ENABLE
- if (isMemoryMgrServiceActive_ && !clientInfo_.IsClientSubscribe() && isCritical_) {
+ if (isMemoryMgrServiceActive_ && !clientInfo_.IsSubscribe() && isCritical_) {
if (Memory::MemMgrClient::GetInstance().SetCritical(getpid(), false, SENSOR_SERVICE_ABILITY_ID) != ERR_OK) {
SEN_HILOGE("SetCritical failed");
return ret;
diff --git a/services/src/stream_server.cpp b/services/src/stream_server.cpp
index c6d6e06b391e42b8cb824f2d25aa95194b4d7279..d8edc6d3ff41067b89b865466bd1e7f868b23f7f 100644
--- a/services/src/stream_server.cpp
+++ b/services/src/stream_server.cpp
@@ -29,7 +29,7 @@ namespace Sensors {
namespace {
constexpr int32_t INVALID_PID = -1;
constexpr int32_t INVALID_FD = -1;
-} // namespace
+} // namespace
StreamServer::~StreamServer()
{
@@ -37,10 +37,6 @@ StreamServer::~StreamServer()
std::lock_guard sessionLock(sessionMutex_);
idxPidMap_.clear();
for (const auto &item : sessionsMap_) {
- if (item.second == nullptr) {
- SEN_HILOGE("SessionPtr is null");
- continue;
- }
item.second->Close();
}
sessionsMap_.clear();
@@ -179,5 +175,5 @@ void StreamServer::DelSession(int32_t pid)
}
}
}
-} // namespace Sensors
-} // namespace OHOS
\ No newline at end of file
+} // namespace Sensors
+} // namespace OHOS
\ No newline at end of file
diff --git a/test/fuzztest/interfaces/sensoragent_fuzzer/BUILD.gn b/test/fuzztest/interfaces/sensoragent_fuzzer/BUILD.gn
index e056db82661cc3c423c93858ceac842051c8d6d5..b888d5970138305b662b0181a4bd3cb68c6dd118 100644
--- a/test/fuzztest/interfaces/sensoragent_fuzzer/BUILD.gn
+++ b/test/fuzztest/interfaces/sensoragent_fuzzer/BUILD.gn
@@ -47,8 +47,6 @@ ohos_fuzztest("SensorAgentFuzzTest") {
"c_utils:utils",
"drivers_interface_sensor:libsensor_proxy_3.0",
"hilog:libhilog",
- "selinux_adapter:librestorecon",
- "cJSON:cjson_static",
]
}
diff --git a/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/BUILD.gn b/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/BUILD.gn
index 28dfc25ae8d3068155714a257e11c8c96e864534..2722a964ae7d874705cf3fecd49111475cf896a3 100644
--- a/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/BUILD.gn
+++ b/test/fuzztest/interfaces/sensoragentenhanced_fuzzer/BUILD.gn
@@ -44,11 +44,9 @@ ohos_fuzztest("SensorAgentEnhancedFuzzTest") {
"access_token:libaccesstoken_sdk",
"access_token:libnativetoken",
"access_token:libtoken_setproc",
- "cJSON:cjson_static",
"c_utils:utils",
"drivers_interface_sensor:libsensor_proxy_3.0",
"hilog:libhilog",
- "selinux_adapter:librestorecon",
]
}
diff --git a/test/fuzztest/services/service/createsocketchannel_fuzzer/BUILD.gn b/test/fuzztest/services/service/createsocketchannel_fuzzer/BUILD.gn
index 185af1011d88f841fcf7313e391a09400e9a0fc6..91d845d8bfd9d5fee3e8dc1bfaaf8e90613c1c36 100644
--- a/test/fuzztest/services/service/createsocketchannel_fuzzer/BUILD.gn
+++ b/test/fuzztest/services/service/createsocketchannel_fuzzer/BUILD.gn
@@ -59,14 +59,12 @@ ohos_fuzztest("CreateSocketChannelFuzzTest") {
"access_token:libaccesstoken_sdk",
"access_token:libnativetoken",
"access_token:libtoken_setproc",
- "cJSON:cjson_static",
"c_utils:utils",
"drivers_interface_sensor:libsensor_proxy_3.0",
"hilog:libhilog",
"ipc:ipc_single",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
- "selinux_adapter:librestorecon",
]
}
diff --git a/test/fuzztest/services/service/getactiveinfolist_fuzzer/BUILD.gn b/test/fuzztest/services/service/getactiveinfolist_fuzzer/BUILD.gn
index e5414610c6036881c45614b2c2930e7aabbd02ae..58e75a36dc98da0804805482dfcbce710e41c9ec 100644
--- a/test/fuzztest/services/service/getactiveinfolist_fuzzer/BUILD.gn
+++ b/test/fuzztest/services/service/getactiveinfolist_fuzzer/BUILD.gn
@@ -59,14 +59,12 @@ ohos_fuzztest("GetActiveInfoListFuzzTest") {
"access_token:libaccesstoken_sdk",
"access_token:libnativetoken",
"access_token:libtoken_setproc",
- "cJSON:cjson_static",
"c_utils:utils",
"drivers_interface_sensor:libsensor_proxy_3.0",
"hilog:libhilog",
"ipc:ipc_single",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
- "selinux_adapter:librestorecon",
]
}
diff --git a/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/BUILD.gn b/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/BUILD.gn
index ca1cc4cbdaa693318bd5b232616890adc22b851a..e1bda17589b35dd1c42a296f1ef2481ea7baa553 100644
--- a/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/BUILD.gn
+++ b/test/fuzztest/services/service/getsensorlistbydevice_fuzzer/BUILD.gn
@@ -58,14 +58,12 @@ ohos_fuzztest("GetSensorListByDeviceFuzzTest") {
"access_token:libaccesstoken_sdk",
"access_token:libnativetoken",
"access_token:libtoken_setproc",
- "cJSON:cjson_static",
"c_utils:utils",
- "drivers_interface_sensor:libsensor_proxy_3.0",
"hilog:libhilog",
"ipc:ipc_single",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
- "selinux_adapter:librestorecon",
+ "drivers_interface_sensor:libsensor_proxy_3.0",
]
}
diff --git a/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/BUILD.gn b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/BUILD.gn
index 65ce4de3eb7981293e36bae5d437290306c49368..fcab3c3c86be5c705fd9931df3cba9f15be956b2 100644
--- a/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/BUILD.gn
+++ b/test/fuzztest/services/service/registerclientdeathrecipient_fuzzer/BUILD.gn
@@ -58,14 +58,12 @@ ohos_fuzztest("RegisterClientDeathRecipientFuzzTest") {
"access_token:libaccesstoken_sdk",
"access_token:libnativetoken",
"access_token:libtoken_setproc",
- "cJSON:cjson_static",
"c_utils:utils",
"drivers_interface_sensor:libsensor_proxy_3.0",
"hilog:libhilog",
"ipc:ipc_single",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
- "selinux_adapter:librestorecon",
]
}
diff --git a/test/fuzztest/services/service/registerpermcallback_fuzzer/BUILD.gn b/test/fuzztest/services/service/registerpermcallback_fuzzer/BUILD.gn
index f3440875c14e9c8b9382347589307dbd6807f735..360c5e0579545c61cf5cd9de922ca9fd2270ccd4 100644
--- a/test/fuzztest/services/service/registerpermcallback_fuzzer/BUILD.gn
+++ b/test/fuzztest/services/service/registerpermcallback_fuzzer/BUILD.gn
@@ -58,14 +58,12 @@ ohos_fuzztest("RegisterPermCallbackFuzzTest") {
"access_token:libaccesstoken_sdk",
"access_token:libnativetoken",
"access_token:libtoken_setproc",
- "cJSON:cjson_static",
"c_utils:utils",
"drivers_interface_sensor:libsensor_proxy_3.0",
"hilog:libhilog",
"ipc:ipc_single",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
- "selinux_adapter:librestorecon",
]
}
diff --git a/test/fuzztest/services/service/reportactiveinfo_fuzzer/BUILD.gn b/test/fuzztest/services/service/reportactiveinfo_fuzzer/BUILD.gn
index f73b02ad3ca54686270c461f1f6aca18f0a78a66..4d48ac6f2c192795606f22152014358e434ef825 100644
--- a/test/fuzztest/services/service/reportactiveinfo_fuzzer/BUILD.gn
+++ b/test/fuzztest/services/service/reportactiveinfo_fuzzer/BUILD.gn
@@ -59,14 +59,12 @@ ohos_fuzztest("ReportActiveInfoFuzzTest") {
"access_token:libaccesstoken_sdk",
"access_token:libnativetoken",
"access_token:libtoken_setproc",
- "cJSON:cjson_static",
"c_utils:utils",
"drivers_interface_sensor:libsensor_proxy_3.0",
"hilog:libhilog",
"ipc:ipc_single",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
- "selinux_adapter:librestorecon",
]
}
diff --git a/test/fuzztest/services/service/reportonchangedata_fuzzer/BUILD.gn b/test/fuzztest/services/service/reportonchangedata_fuzzer/BUILD.gn
index e49c4f5afd6b84bf61e4f847cc75775fd822e250..8016a14f13b2685b7173360c3bf09ad7920041c1 100644
--- a/test/fuzztest/services/service/reportonchangedata_fuzzer/BUILD.gn
+++ b/test/fuzztest/services/service/reportonchangedata_fuzzer/BUILD.gn
@@ -59,14 +59,12 @@ ohos_fuzztest("ReportOnChangeDataFuzzTest") {
"access_token:libaccesstoken_sdk",
"access_token:libnativetoken",
"access_token:libtoken_setproc",
- "cJSON:cjson_static",
"c_utils:utils",
"drivers_interface_sensor:libsensor_proxy_3.0",
"hilog:libhilog",
"ipc:ipc_single",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
- "selinux_adapter:librestorecon",
]
}
diff --git a/test/fuzztest/services/service/reportsensorsysevent_fuzzer/BUILD.gn b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/BUILD.gn
index d26d91ec5e35b3e4c8adedf80beb058332ee988c..cae1bf0bcbdeabfa6fc857016d6b19d85d42ba38 100644
--- a/test/fuzztest/services/service/reportsensorsysevent_fuzzer/BUILD.gn
+++ b/test/fuzztest/services/service/reportsensorsysevent_fuzzer/BUILD.gn
@@ -58,14 +58,12 @@ ohos_fuzztest("ReportSensorSysEventFuzzTest") {
"access_token:libaccesstoken_sdk",
"access_token:libnativetoken",
"access_token:libtoken_setproc",
- "cJSON:cjson_static",
"c_utils:utils",
"drivers_interface_sensor:libsensor_proxy_3.0",
"hilog:libhilog",
"ipc:ipc_single",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
- "selinux_adapter:librestorecon",
]
}
diff --git a/test/fuzztest/services/service/setdevicestatusservice_fuzzer/BUILD.gn b/test/fuzztest/services/service/setdevicestatusservice_fuzzer/BUILD.gn
index 690a4b2d9b139c7df7d4d953d08b498d7855aacc..08755b6e4b7c19ce6ac1b7fee4da7eeb92c4fcc6 100644
--- a/test/fuzztest/services/service/setdevicestatusservice_fuzzer/BUILD.gn
+++ b/test/fuzztest/services/service/setdevicestatusservice_fuzzer/BUILD.gn
@@ -58,14 +58,12 @@ ohos_fuzztest("SetDeviceStatusServiceFuzzTest") {
"access_token:libaccesstoken_sdk",
"access_token:libnativetoken",
"access_token:libtoken_setproc",
- "cJSON:cjson_static",
"c_utils:utils",
"drivers_interface_sensor:libsensor_proxy_3.0",
"hilog:libhilog",
"ipc:ipc_single",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
- "selinux_adapter:librestorecon",
]
}
diff --git a/test/unittest/interfaces/inner_api/drop_detection_test.cpp b/test/unittest/interfaces/inner_api/drop_detection_test.cpp
index 255c8c3f6dbb2b75e9dd6b01576604562b6faae8..a1bd4f3dff75e47887e01219c4d8e927ec950769 100644
--- a/test/unittest/interfaces/inner_api/drop_detection_test.cpp
+++ b/test/unittest/interfaces/inner_api/drop_detection_test.cpp
@@ -31,7 +31,7 @@ using namespace testing::ext;
using namespace OHOS::HiviewDFX;
namespace {
-std::atomic_bool g_existDropDetection = false;
+std::atomic_bool g_hasDropDetection = false;
} // namespace
class DropDetectionTest : public testing::Test {
@@ -54,7 +54,7 @@ void DropDetectionTest::SetUpTestCase()
}
for (int32_t i = 0; i < count; ++i) {
if (sensorInfo[i].sensorId == SENSOR_TYPE_ID_DROP_DETECTION) {
- g_existDropDetection = true;
+ g_hasDropDetection = true;
SEN_HILOGD("Exist drop detection sensor");
break;
}
@@ -83,10 +83,6 @@ void DropDetectionDataCallbackImpl(SensorEvent *event)
return;
}
DropDetectionData *dropDetectionData = reinterpret_cast(event[0].data);
- if (dropDetectionData == nullptr) {
- SEN_HILOGE("dropDetectionData is nullptr");
- return;
- }
SEN_HILOGD("sensorId:%{public}d, version:%{public}d, dataLen:%{public}u, status:%{public}f", event[0].sensorTypeId,
event[0].version, event[0].dataLen, dropDetectionData->status);
}
@@ -106,10 +102,6 @@ void DropDetectionDataCallbackImpl2(SensorEvent *event)
return;
}
DropDetectionData *dropDetectionData = reinterpret_cast(event[0].data);
- if (dropDetectionData == nullptr) {
- SEN_HILOGE("dropDetectionData is nullptr");
- return;
- }
SEN_HILOGD("sensorId:%{public}d, version:%{public}d, dataLen:%{public}u, status:%{public}f", event[0].sensorTypeId,
event[0].version, event[0].dataLen, dropDetectionData->status);
}
@@ -117,7 +109,7 @@ void DropDetectionDataCallbackImpl2(SensorEvent *event)
HWTEST_F(DropDetectionTest, DropDetectionTest_001, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_001 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
ASSERT_NE(ActivateSensor(SENSOR_TYPE_ID_DROP_DETECTION, nullptr), OHOS::Sensors::SUCCESS);
}
}
@@ -125,7 +117,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_001, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_002, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_002 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
SensorUser user;
user.callback = DropDetectionDataCallbackImpl;
ASSERT_NE(ActivateSensor(-1, &user), OHOS::Sensors::SUCCESS);
@@ -135,7 +127,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_002, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_003, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_003 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
SensorUser user;
user.callback = nullptr;
ASSERT_NE(ActivateSensor(SENSOR_TYPE_ID_DROP_DETECTION, &user), OHOS::Sensors::SUCCESS);
@@ -145,7 +137,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_003, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_004, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_004 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
ASSERT_NE(DeactivateSensor(SENSOR_TYPE_ID_DROP_DETECTION, nullptr), OHOS::Sensors::SUCCESS);
}
}
@@ -153,7 +145,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_004, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_005, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_005 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
SensorUser user;
user.callback = DropDetectionDataCallbackImpl;
ASSERT_NE(DeactivateSensor(-1, &user), OHOS::Sensors::SUCCESS);
@@ -163,7 +155,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_005, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_006, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_006 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
SensorUser user;
user.callback = nullptr;
ASSERT_NE(DeactivateSensor(SENSOR_TYPE_ID_DROP_DETECTION, &user), OHOS::Sensors::SUCCESS);
@@ -173,7 +165,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_006, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_007, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_007 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
ASSERT_NE(SetBatch(SENSOR_TYPE_ID_DROP_DETECTION, nullptr, 10000000, 10000000), OHOS::Sensors::SUCCESS);
}
}
@@ -181,7 +173,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_007, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_008, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_008 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
SensorUser user;
user.callback = DropDetectionDataCallbackImpl;
ASSERT_NE(SetBatch(-1, &user, 10000000, 10000000), OHOS::Sensors::SUCCESS);
@@ -191,7 +183,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_008, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_009, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_009 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
SensorUser user;
user.callback = nullptr;
ASSERT_NE(SetBatch(SENSOR_TYPE_ID_DROP_DETECTION, &user, 10000000, 10000000), OHOS::Sensors::SUCCESS);
@@ -201,7 +193,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_009, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_010, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_010 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
SensorUser user;
user.callback = DropDetectionDataCallbackImpl;
ASSERT_NE(SetBatch(SENSOR_TYPE_ID_DROP_DETECTION, &user, -1, -1), OHOS::Sensors::SUCCESS);
@@ -211,7 +203,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_010, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_011, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_011 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
ASSERT_NE(SubscribeSensor(SENSOR_TYPE_ID_DROP_DETECTION, nullptr), OHOS::Sensors::SUCCESS);
}
}
@@ -219,7 +211,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_011, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_012, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_012 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
SensorUser user;
user.callback = DropDetectionDataCallbackImpl;
ASSERT_NE(SubscribeSensor(-1, &user), OHOS::Sensors::SUCCESS);
@@ -229,7 +221,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_012, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_013, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_013 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
SensorUser user;
user.callback = nullptr;
ASSERT_NE(SubscribeSensor(SENSOR_TYPE_ID_DROP_DETECTION, &user), OHOS::Sensors::SUCCESS);
@@ -239,7 +231,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_013, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_014, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_014 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
ASSERT_NE(UnsubscribeSensor(SENSOR_TYPE_ID_DROP_DETECTION, nullptr), OHOS::Sensors::SUCCESS);
}
}
@@ -247,7 +239,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_014, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_015, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_015 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
SensorUser user;
user.callback = DropDetectionDataCallbackImpl;
ASSERT_NE(UnsubscribeSensor(-1, &user), OHOS::Sensors::SUCCESS);
@@ -257,7 +249,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_015, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_016, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_016 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
SensorUser user;
user.callback = nullptr;
ASSERT_NE(UnsubscribeSensor(SENSOR_TYPE_ID_DROP_DETECTION, &user), OHOS::Sensors::SUCCESS);
@@ -267,7 +259,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_016, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_017, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_017 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
SensorUser user;
user.callback = DropDetectionDataCallbackImpl;
ASSERT_EQ(SubscribeSensor(SENSOR_TYPE_ID_DROP_DETECTION, &user), OHOS::Sensors::SUCCESS);
@@ -282,7 +274,7 @@ HWTEST_F(DropDetectionTest, DropDetectionTest_017, TestSize.Level1)
HWTEST_F(DropDetectionTest, DropDetectionTest_018, TestSize.Level1)
{
SEN_HILOGI("DropDetectionTest_018 enter");
- if (g_existDropDetection) {
+ if (g_hasDropDetection) {
SensorUser user;
user.callback = DropDetectionDataCallbackImpl;
ASSERT_EQ(SubscribeSensor(SENSOR_TYPE_ID_DROP_DETECTION, &user), OHOS::Sensors::SUCCESS);
diff --git a/test/unittest/interfaces/js/sensor/AmbientLightJsunit.test.js b/test/unittest/interfaces/js/sensor/AmbientLightJsunit.test.js
deleted file mode 100644
index 5e32174730d796d162d1b6d5f9750f84fde38e39..0000000000000000000000000000000000000000
--- a/test/unittest/interfaces/js/sensor/AmbientLightJsunit.test.js
+++ /dev/null
@@ -1,575 +0,0 @@
-/*
- * 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 CommonConstants from './CommonConstants';
-import sensor from '@ohos.sensor'
-
-import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index'
-
-describe("AmbientLightJsTest", function () {
- function callback(data) {
- console.info("callback" + JSON.stringify(data));
- expect(typeof(data.intensity)).assertEqual("number");
- expect(typeof(data.colorTemperature)).assertEqual("number");
- expect(typeof(data.infraredLuminance)).assertEqual("number");
- }
-
- function callback2(data) {
- console.info("callback2" + JSON.stringify(data));
- expect(typeof(data.intensity)).assertEqual("number");
- expect(typeof(data.colorTemperature)).assertEqual("number");
- expect(typeof(data.infraredLuminance)).assertEqual("number");
- }
-
- beforeAll(function() {
- /*
- * @tc.setup: setup invoked before all testcases
- */
- console.info('beforeAll called')
- })
-
- afterAll(function() {
- /*
- * @tc.teardown: teardown invoked after all testcases
- */
- console.info('afterAll called')
- })
-
- beforeEach(function() {
- /*
- * @tc.setup: setup invoked before each testcases
- */
- console.info('beforeEach called')
- })
-
- afterEach(function() {
- /*
- * @tc.teardown: teardown invoked after each testcases
- */
- console.info('afterEach called')
- })
-
- /*
- * @tc.number: AmbientLightJsTest_001
- * @tc.name: AmbientLightJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("AmbientLightJsTest_001", 0, async function (done) {
- console.info('----------------------AmbientLightJsTest_001---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback);
- setTimeout(() => {
- sensor.off(sensor.SensorId.AMBIENT_LIGHT);
- done();
- }, 500);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: AmbientLightJsTest_002
- * @tc.name: AmbientLightJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("AmbientLightJsTest_002", 0, async function (done) {
- console.info('----------------------AmbientLightJsTest_002---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback, {'interval': 100000000});
- setTimeout(() => {
- sensor.off(sensor.SensorId.AMBIENT_LIGHT);
- done();
- }, 500);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: AmbientLightJsTest_003
- * @tc.name: AmbientLightJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("AmbientLightJsTest_003", 0, async function (done) {
- console.info('----------------------AmbientLightJsTest_003---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- function onSensorCallback(data) {
- console.error('AmbientLightJsTest_003 callback in');
- expect(true).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.AMBIENT_LIGHT, onSensorCallback, {'interval': 100000000}, 5);
- setTimeout(() => {
- sensor.off(sensor.SensorId.AMBIENT_LIGHT);
- done();
- }, 500);
- } catch (error) {
- console.info('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: AmbientLightJsTest_004
- * @tc.name: AmbientLightJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("AmbientLightJsTest_004", 0, async function (done) {
- console.info('----------------------AmbientLightJsTest_004---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback, {'interval': -100000000});
- sensor.off(sensor.SensorId.AMBIENT_LIGHT);
- done();
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SERVICE_EXCEPTION_CODE);
- expect(error.message).assertEqual(CommonConstants.SERVICE_EXCEPTION_MSG);
- done();
- }
- });
- } catch (error) {
- console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: AmbientLightJsTest_005
- * @tc.name: AmbientLightJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("AmbientLightJsTest_005", 0, async function (done) {
- console.info('----------------------AmbientLightJsTest_005---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.once(sensor.SensorId.AMBIENT_LIGHT, callback);
- setTimeout(() => {
- expect(true).assertTrue();
- done();
- }, 500);
- } catch (error) {
- console.error('Once fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: AmbientLightJsTest_006
- * @tc.name: AmbientLightJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("AmbientLightJsTest_006", 0, async function (done) {
- console.info('----------------------AmbientLightJsTest_006---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try{
- sensor.once(sensor.SensorId.AMBIENT_LIGHT, callback, 5);
- setTimeout(() => {
- expect(true).assertTrue();
- done();
- }, 500);
- } catch (error) {
- console.error('Once fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: AmbientLightJsTest_007
- * @tc.name: AmbientLightJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("AmbientLightJsTest_007", 0, async function (done) {
- console.info('----------------------AmbientLightJsTest_007---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try{
- sensor.once(sensor.SensorId.AMBIENT_LIGHT, 5);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.PARAMETER_ERROR_CODE);
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: AmbientLightJsTest_008
- * @tc.name: AmbientLightJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("AmbientLightJsTest_008", 0, async function (done) {
- console.info('----------------------AmbientLightJsTest_008---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.off(-1, callback);
- } catch (error) {
- expect(error.code).assertEqual(CommonConstants.PARAMETER_ERROR_CODE);
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: AmbientLightJsTest_009
- * @tc.name: AmbientLightJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("AmbientLightJsTest_009", 0, async function (done) {
- console.info('----------------------AmbientLightJsTest_009---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback);
- sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback2);
- setTimeout(() => {
- sensor.off(sensor.SensorId.AMBIENT_LIGHT);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: AmbientLightJsTest_010
- * @tc.name: AmbientLightJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("AmbientLightJsTest_010", 0, async function (done) {
- console.info('----------------------AmbientLightJsTest_010---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback);
- sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback2);
- setTimeout(() => {
- sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback);
- }, 500);
- setTimeout(() => {
- sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback2);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: AmbientLightJsTest_011
- * @tc.name: AmbientLightJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("AmbientLightJsTest_011", 0, async function (done) {
- console.info('----------------------AmbientLightJsTest_011---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback, {'interval': 100000000});
- sensor.once(sensor.SensorId.AMBIENT_LIGHT, callback2);
- setTimeout(() => {
- sensor.off(sensor.SensorId.AMBIENT_LIGHT);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: AmbientLightJsTest_012
- * @tc.name: AmbientLightJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("AmbientLightJsTest_012", 0, async function (done) {
- console.info('----------------------AmbientLightJsTest_012---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback, {'interval': 100000000});
- sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback2, {'interval': 100000000});
- setTimeout(() => {
- sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback);
- }, 500);
- setTimeout(() => {
- sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback2);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: AmbientLightJsTest_013
- * @tc.name: AmbientLightJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("AmbientLightJsTest_013", 0, async function (done) {
- console.info('----------------------AmbientLightJsTest_013---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.AMBIENT_LIGHT, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback, {'interval': 100000000});
- sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback2, {'interval': 100000000});
- setTimeout(() => {
- sensor.off(sensor.SensorId.AMBIENT_LIGHT);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-})
diff --git a/test/unittest/interfaces/js/sensor/GravityJsTest.test.js b/test/unittest/interfaces/js/sensor/GravityJsTest.test.js
deleted file mode 100644
index 07a5b46a2e9bab44983f0ae68eb6fa4709414153..0000000000000000000000000000000000000000
--- a/test/unittest/interfaces/js/sensor/GravityJsTest.test.js
+++ /dev/null
@@ -1,575 +0,0 @@
-/*
- * 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 CommonConstants from './CommonConstants';
-import sensor from '@ohos.sensor'
-
-import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index'
-
-describe("GravityJsTest", function () {
- function callback(data) {
- console.info("callback" + JSON.stringify(data));
- expect(typeof(data.x)).assertEqual("number");
- expect(typeof(data.y)).assertEqual("number");
- expect(typeof(data.z)).assertEqual("number");
- }
-
- function callback2(data) {
- console.info("callback2" + JSON.stringify(data));
- expect(typeof(data.x)).assertEqual("number");
- expect(typeof(data.y)).assertEqual("number");
- expect(typeof(data.z)).assertEqual("number");
- }
-
- beforeAll(function() {
- /*
- * @tc.setup: setup invoked before all testcases
- */
- console.info('beforeAll called')
- })
-
- afterAll(function() {
- /*
- * @tc.teardown: teardown invoked after all testcases
- */
- console.info('afterAll called')
- })
-
- beforeEach(function() {
- /*
- * @tc.setup: setup invoked before each testcases
- */
- console.info('beforeEach called')
- })
-
- afterEach(function() {
- /*
- * @tc.teardown: teardown invoked after each testcases
- */
- console.info('afterEach called')
- })
-
- /*
- * @tc.number: GravityJsTest_001
- * @tc.name: GravityJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("GravityJsTest_001", 0, async function (done) {
- console.info('----------------------GravityJsTest_001---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.GRAVITY, callback);
- setTimeout(() => {
- sensor.off(sensor.SensorId.GRAVITY);
- done();
- }, 500);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: GravityJsTest_002
- * @tc.name: GravityJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("GravityJsTest_002", 0, async function (done) {
- console.info('----------------------GravityJsTest_002---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.GRAVITY, callback, {'interval': 100000000});
- setTimeout(() => {
- sensor.off(sensor.SensorId.GRAVITY);
- done();
- }, 500);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: GravityJsTest_003
- * @tc.name: GravityJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("GravityJsTest_003", 0, async function (done) {
- console.info('----------------------GravityJsTest_003---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- function onSensorCallback(data) {
- console.error('GravityJsTest_003 callback in');
- expect(true).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.GRAVITY, onSensorCallback, {'interval': 100000000}, 5);
- setTimeout(() => {
- sensor.off(sensor.SensorId.GRAVITY);
- done();
- }, 500);
- } catch (error) {
- console.info('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: GravityJsTest_004
- * @tc.name: GravityJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("GravityJsTest_004", 0, async function (done) {
- console.info('----------------------GravityJsTest_004---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.GRAVITY, callback, {'interval': -100000000});
- sensor.off(sensor.SensorId.GRAVITY);
- done();
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SERVICE_EXCEPTION_CODE);
- expect(error.message).assertEqual(CommonConstants.SERVICE_EXCEPTION_MSG);
- done();
- }
- });
- } catch (error) {
- console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: GravityJsTest_005
- * @tc.name: GravityJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("GravityJsTest_005", 0, async function (done) {
- console.info('----------------------GravityJsTest_005---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.once(sensor.SensorId.GRAVITY, callback);
- setTimeout(() => {
- expect(true).assertTrue();
- done();
- }, 500);
- } catch (error) {
- console.error('Once fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: GravityJsTest_006
- * @tc.name: GravityJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("GravityJsTest_006", 0, async function (done) {
- console.info('----------------------GravityJsTest_006---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try{
- sensor.once(sensor.SensorId.GRAVITY, callback, 5);
- setTimeout(() => {
- expect(true).assertTrue();
- done();
- }, 500);
- } catch (error) {
- console.error('Once fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: GravityJsTest_007
- * @tc.name: GravityJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("GravityJsTest_007", 0, async function (done) {
- console.info('----------------------GravityJsTest_007---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try{
- sensor.once(sensor.SensorId.GRAVITY, 5);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.PARAMETER_ERROR_CODE);
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: GravityJsTest_008
- * @tc.name: GravityJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("GravityJsTest_008", 0, async function (done) {
- console.info('----------------------GravityJsTest_008---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.off(-1, callback);
- } catch (error) {
- expect(error.code).assertEqual(CommonConstants.PARAMETER_ERROR_CODE);
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: GravityJsTest_009
- * @tc.name: GravityJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("GravityJsTest_009", 0, async function (done) {
- console.info('----------------------GravityJsTest_009---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.GRAVITY, callback);
- sensor.on(sensor.SensorId.GRAVITY, callback2);
- setTimeout(() => {
- sensor.off(sensor.SensorId.GRAVITY);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: GravityJsTest_010
- * @tc.name: GravityJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("GravityJsTest_010", 0, async function (done) {
- console.info('----------------------GravityJsTest_010---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.GRAVITY, callback);
- sensor.on(sensor.SensorId.GRAVITY, callback2);
- setTimeout(() => {
- sensor.off(sensor.SensorId.GRAVITY, callback);
- }, 500);
- setTimeout(() => {
- sensor.off(sensor.SensorId.GRAVITY, callback2);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: GravityJsTest_011
- * @tc.name: GravityJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("GravityJsTest_011", 0, async function (done) {
- console.info('----------------------GravityJsTest_011---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.GRAVITY, callback, {'interval': 100000000});
- sensor.once(sensor.SensorId.GRAVITY, callback2);
- setTimeout(() => {
- sensor.off(sensor.SensorId.GRAVITY);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: GravityJsTest_012
- * @tc.name: GravityJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("GravityJsTest_012", 0, async function (done) {
- console.info('----------------------GravityJsTest_012---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.GRAVITY, callback, {'interval': 100000000});
- sensor.on(sensor.SensorId.GRAVITY, callback2, {'interval': 100000000});
- setTimeout(() => {
- sensor.off(sensor.SensorId.GRAVITY, callback);
- }, 500);
- setTimeout(() => {
- sensor.off(sensor.SensorId.GRAVITY, callback2);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: GravityJsTest_013
- * @tc.name: GravityJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("GravityJsTest_013", 0, async function (done) {
- console.info('----------------------GravityJsTest_013---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.GRAVITY, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.GRAVITY, callback, {'interval': 100000000});
- sensor.on(sensor.SensorId.GRAVITY, callback2, {'interval': 100000000});
- setTimeout(() => {
- sensor.off(sensor.SensorId.GRAVITY);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-})
diff --git a/test/unittest/interfaces/js/sensor/OrientationJs.test.js b/test/unittest/interfaces/js/sensor/OrientationJs.test.js
deleted file mode 100644
index b9c4a9dd471e2533d773f91fe63805cd42fbee2a..0000000000000000000000000000000000000000
--- a/test/unittest/interfaces/js/sensor/OrientationJs.test.js
+++ /dev/null
@@ -1,575 +0,0 @@
-/*
- * 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 CommonConstants from './CommonConstants';
-import sensor from '@ohos.sensor'
-
-import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index'
-
-describe("OrientationJsTest", function () {
- function callback(data) {
- console.info("callback" + JSON.stringify(data));
- expect(typeof(data.intensity)).assertEqual("number");
- expect(typeof(data.colorTemperature)).assertEqual("number");
- expect(typeof(data.infraredLuminance)).assertEqual("number");
- }
-
- function callback2(data) {
- console.info("callback2" + JSON.stringify(data));
- expect(typeof(data.intensity)).assertEqual("number");
- expect(typeof(data.colorTemperature)).assertEqual("number");
- expect(typeof(data.infraredLuminance)).assertEqual("number");
- }
-
- beforeAll(function() {
- /*
- * @tc.setup: setup invoked before all testcases
- */
- console.info('beforeAll called')
- })
-
- afterAll(function() {
- /*
- * @tc.teardown: teardown invoked after all testcases
- */
- console.info('afterAll called')
- })
-
- beforeEach(function() {
- /*
- * @tc.setup: setup invoked before each testcases
- */
- console.info('beforeEach called')
- })
-
- afterEach(function() {
- /*
- * @tc.teardown: teardown invoked after each testcases
- */
- console.info('afterEach called')
- })
-
- /*
- * @tc.number: OrientationJsTest_001
- * @tc.name: OrientationJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("OrientationJsTest_001", 0, async function (done) {
- console.info('----------------------OrientationJsTest_001---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.ORIENTATION, callback);
- setTimeout(() => {
- sensor.off(sensor.SensorId.ORIENTATION);
- done();
- }, 500);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: OrientationJsTest_002
- * @tc.name: OrientationJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("OrientationJsTest_002", 0, async function (done) {
- console.info('----------------------OrientationJsTest_002---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.ORIENTATION, callback, {'interval': 100000000});
- setTimeout(() => {
- sensor.off(sensor.SensorId.ORIENTATION);
- done();
- }, 500);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: OrientationJsTest_003
- * @tc.name: OrientationJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("OrientationJsTest_003", 0, async function (done) {
- console.info('----------------------OrientationJsTest_003---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- function onSensorCallback(data) {
- console.error('OrientationJsTest_003 callback in');
- expect(true).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.ORIENTATION, onSensorCallback, {'interval': 100000000}, 5);
- setTimeout(() => {
- sensor.off(sensor.SensorId.ORIENTATION);
- done();
- }, 500);
- } catch (error) {
- console.info('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: OrientationJsTest_004
- * @tc.name: OrientationJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("OrientationJsTest_004", 0, async function (done) {
- console.info('----------------------OrientationJsTest_004---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.ORIENTATION, callback, {'interval': -100000000});
- sensor.off(sensor.SensorId.ORIENTATION);
- done();
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SERVICE_EXCEPTION_CODE);
- expect(error.message).assertEqual(CommonConstants.SERVICE_EXCEPTION_MSG);
- done();
- }
- });
- } catch (error) {
- console.info('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: OrientationJsTest_005
- * @tc.name: OrientationJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("OrientationJsTest_005", 0, async function (done) {
- console.info('----------------------OrientationJsTest_005---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.once(sensor.SensorId.ORIENTATION, callback);
- setTimeout(() => {
- expect(true).assertTrue();
- done();
- }, 500);
- } catch (error) {
- console.error('Once fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: OrientationJsTest_006
- * @tc.name: OrientationJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("OrientationJsTest_006", 0, async function (done) {
- console.info('----------------------OrientationJsTest_006---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try{
- sensor.once(sensor.SensorId.ORIENTATION, callback, 5);
- setTimeout(() => {
- expect(true).assertTrue();
- done();
- }, 500);
- } catch (error) {
- console.error('Once fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: OrientationJsTest_007
- * @tc.name: OrientationJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("OrientationJsTest_007", 0, async function (done) {
- console.info('----------------------OrientationJsTest_007---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try{
- sensor.once(sensor.SensorId.ORIENTATION, 5);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.PARAMETER_ERROR_CODE);
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: OrientationJsTest_008
- * @tc.name: OrientationJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("OrientationJsTest_008", 0, async function (done) {
- console.info('----------------------OrientationJsTest_008---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.off(-1, callback);
- } catch (error) {
- expect(error.code).assertEqual(CommonConstants.PARAMETER_ERROR_CODE);
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: OrientationJsTest_009
- * @tc.name: OrientationJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("OrientationJsTest_009", 0, async function (done) {
- console.info('----------------------OrientationJsTest_009---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.ORIENTATION, callback);
- sensor.on(sensor.SensorId.ORIENTATION, callback2);
- setTimeout(() => {
- sensor.off(sensor.SensorId.ORIENTATION);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: OrientationJsTest_010
- * @tc.name: OrientationJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("OrientationJsTest_010", 0, async function (done) {
- console.info('----------------------OrientationJsTest_010---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.ORIENTATION, callback);
- sensor.on(sensor.SensorId.ORIENTATION, callback2);
- setTimeout(() => {
- sensor.off(sensor.SensorId.ORIENTATION, callback);
- }, 500);
- setTimeout(() => {
- sensor.off(sensor.SensorId.ORIENTATION, callback2);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: OrientationJsTest_011
- * @tc.name: OrientationJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("OrientationJsTest_011", 0, async function (done) {
- console.info('----------------------OrientationJsTest_011---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.ORIENTATION, callback, {'interval': 100000000});
- sensor.once(sensor.SensorId.ORIENTATION, callback2);
- setTimeout(() => {
- sensor.off(sensor.SensorId.ORIENTATION);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: OrientationJsTest_012
- * @tc.name: OrientationJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("OrientationJsTest_012", 0, async function (done) {
- console.info('----------------------OrientationJsTest_012---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.ORIENTATION, callback, {'interval': 100000000});
- sensor.on(sensor.SensorId.ORIENTATION, callback2, {'interval': 100000000});
- setTimeout(() => {
- sensor.off(sensor.SensorId.ORIENTATION, callback);
- }, 500);
- setTimeout(() => {
- sensor.off(sensor.SensorId.ORIENTATION, callback2);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-
- /*
- * @tc.number: OrientationJsTest_013
- * @tc.name: OrientationJsTest
- * @tc.desc: verify app info is not null
- * @tc.type: FUNC
- * @tc.require: Issue Number
- * @tc.size: MediumTest
- * @tc.type: Function
- * @tc.level: Level 1
- */
- it("OrientationJsTest_013", 0, async function (done) {
- console.info('----------------------OrientationJsTest_013---------------------------');
- try {
- sensor.getSingleSensor(sensor.SensorId.ORIENTATION, (error, data) => {
- if (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- try {
- sensor.on(sensor.SensorId.ORIENTATION, callback, {'interval': 100000000});
- sensor.on(sensor.SensorId.ORIENTATION, callback2, {'interval': 100000000});
- setTimeout(() => {
- sensor.off(sensor.SensorId.ORIENTATION);
- done();
- }, 1000);
- } catch (error) {
- console.error('On fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(false).assertTrue();
- done();
- }
- });
- } catch (error) {
- console.error('getSingleSensor fail, errCode:' + error.code + ' ,msg:' + error.message);
- expect(error.code).assertEqual(CommonConstants.SENSOR_NO_SUPPORT_CODE);
- expect(error.message).assertEqual(CommonConstants.SENSOR_NO_SUPPOR_MSG);
- done();
- }
- })
-})
diff --git a/test/unittest/interfaces/js/sensor/PedometerDetectionJsunit.test.js b/test/unittest/interfaces/js/sensor/PedometerDetectionJsunit.test.js
index 37bc1313517ced30d86a0d7fa4ae1842502c4def..ca9326f94b89a13f1fd991f857c3f3a876ef056b 100644
--- a/test/unittest/interfaces/js/sensor/PedometerDetectionJsunit.test.js
+++ b/test/unittest/interfaces/js/sensor/PedometerDetectionJsunit.test.js
@@ -81,7 +81,7 @@ describe("PedometerDetectionJsTest", function () {
* @tc.name: PedometerDetectionJsTest
* @tc.desc: verify app info is not null
* @tc.type: FUNC
- * @tc.require: Issue Number
+ * @tc.require: AR000HPEMR
* @tc.size: MediumTest
* @tc.type: Function
* @tc.level: Level 1
@@ -129,7 +129,7 @@ describe("PedometerDetectionJsTest", function () {
* @tc.name: PedometerDetectionJsTest
* @tc.desc: verify app info is not null
* @tc.type: FUNC
- * @tc.require: Issue Number
+ * @tc.require: AR000HPEMR
* @tc.size: MediumTest
* @tc.type: Function
* @tc.level: Level 1
@@ -173,7 +173,7 @@ describe("PedometerDetectionJsTest", function () {
* @tc.name: PedometerDetectionJsTest
* @tc.desc: verify app info is not null
* @tc.type: FUNC
- * @tc.require: Issue Number
+ * @tc.require: AR000HPEMR
* @tc.size: MediumTest
* @tc.type: Function
* @tc.level: Level 1
@@ -221,7 +221,7 @@ describe("PedometerDetectionJsTest", function () {
* @tc.name: PedometerDetectionJsTest
* @tc.desc: verify app info is not null
* @tc.type: FUNC
- * @tc.require: Issue Number
+ * @tc.require: AR000HPEMR
* @tc.size: MediumTest
* @tc.type: Function
* @tc.level: Level 1
@@ -269,7 +269,7 @@ describe("PedometerDetectionJsTest", function () {
* @tc.name: PedometerDetectionJsTest
* @tc.desc: verify app info is not null
* @tc.type: FUNC
- * @tc.require: Issue Number
+ * @tc.require: AR000HPEMR
* @tc.size: MediumTest
* @tc.type: Function
* @tc.level: Level 1
@@ -313,7 +313,7 @@ describe("PedometerDetectionJsTest", function () {
* @tc.name: PedometerDetectionJsTest
* @tc.desc: verify app info is not null
* @tc.type: FUNC
- * @tc.require: Issue Number
+ * @tc.require: AR000HPEMR
* @tc.size: MediumTest
* @tc.type: Function
* @tc.level: Level 1
@@ -356,7 +356,7 @@ describe("PedometerDetectionJsTest", function () {
* @tc.name: PedometerDetectionJsTest
* @tc.desc: verify app info is not null
* @tc.type: FUNC
- * @tc.require: Issue Number
+ * @tc.require: AR000HPEMR
* @tc.size: MediumTest
* @tc.type: Function
* @tc.level: Level 1
@@ -405,7 +405,7 @@ describe("PedometerDetectionJsTest", function () {
* @tc.name: PedometerDetectionJsTest
* @tc.desc: verify app info is not null
* @tc.type: FUNC
- * @tc.require: Issue Number
+ * @tc.require: AR000HPEMR
* @tc.size: MediumTest
* @tc.type: Function
* @tc.level: Level 1
@@ -457,7 +457,7 @@ describe("PedometerDetectionJsTest", function () {
* @tc.name: PedometerDetectionJsTest
* @tc.desc: verify app info is not null
* @tc.type: FUNC
- * @tc.require: Issue Number
+ * @tc.require: AR000HPEMR
* @tc.size: MediumTest
* @tc.type: Function
* @tc.level: Level 1
@@ -506,7 +506,7 @@ describe("PedometerDetectionJsTest", function () {
* @tc.name: PedometerDetectionJsTest
* @tc.desc: verify app info is not null
* @tc.type: FUNC
- * @tc.require: Issue Number
+ * @tc.require: AR000HPEMR
* @tc.size: MediumTest
* @tc.type: Function
* @tc.level: Level 1
diff --git a/test/unittest/interfaces/js/sensor/SensorJsSync.test.js b/test/unittest/interfaces/js/sensor/SensorJsSync.test.js
index 74a7cd4aaffab760c3d79f1df6272dbb46758826..038e900f47b11f61ea47997c64d1842dd4ad0c7a 100644
--- a/test/unittest/interfaces/js/sensor/SensorJsSync.test.js
+++ b/test/unittest/interfaces/js/sensor/SensorJsSync.test.js
@@ -125,26 +125,27 @@ describe("SensorSyncTest", function () {
try {
let ret = sensor.getSingleSensorByDeviceSync(sensor.SensorId.ACCELEROMETER);
console.info('getSingleSensorByDeviceSync: ' + JSON.stringify(ret));
- if (Array.isArray(ret) && ret.length > 0) {
- const sensorInfo = ret[0];
- const callback = (data) => {
- console.info('Accelerometer data received: ' + JSON.stringify(data));
- };
- const sensorInfoParam = {
- deviceId: sensorInfo.deviceId,
- sensorIndex: sensorInfo.sensorIndex
- };
- const options = {
- interval: 10000000,
- sensorInfoParam: sensorInfoParam
- };
- sensor.on(sensorInfo.sensorId, callback, options);
- sensor.off(sensorInfo.sensorId, sensorInfoParam, callback);
- expect(true).assertTrue();
- } else {
- console.info('No local accelerometer sensor found. Test case will return true.');
+ if (!Array.isArray(ret) || ret.length === 0) {
+ console.info('No local sensors found. Test case will return true.');
expect(true).assertTrue();
+ done();
+ return;
}
+ const sensorInfo = ret[0];
+ const callback = (data) => {
+ console.info('Accelerometer data received: ' + JSON.stringify(data));
+ };
+ const sensorInfoParam = {
+ deviceId: sensorInfo.deviceId,
+ sensorIndex: sensorInfo.sensorIndex
+ };
+ const options = {
+ interval: 10000000,
+ sensorInfoParam: sensorInfoParam
+ };
+ sensor.on(sensorInfo.sensorId, callback, options);
+ sensor.off(sensorInfo.sensorId, sensorInfoParam, callback);
+ expect(true).assertTrue();
done();
} catch (err) {
console.error('getSingleSensorByDeviceSync err: ' + JSON.stringify(err));
@@ -168,26 +169,27 @@ describe("SensorSyncTest", function () {
try {
let ret = sensor.getSingleSensorByDeviceSync(sensor.SensorId.ACCELEROMETER, validDeviceId);
console.info(`getSingleSensorByDeviceSync deviceId=${validDeviceId}: ` + JSON.stringify(ret));
- if (Array.isArray(ret) && ret.length > 0) {
- const sensorInfo = ret[0];
- const callback = (data) => {
- console.info('Accelerometer data received: ' + JSON.stringify(data));
- };
- const sensorInfoParam = {
- deviceId: sensorInfo.deviceId,
- sensorIndex: sensorInfo.sensorIndex
- };
- const options = {
- interval: 10000000,
- sensorInfoParam: sensorInfoParam
- };
- sensor.on(sensorInfo.sensorId, callback, options);
- sensor.off(sensorInfo.sensorId, sensorInfoParam, callback);
- expect(true).assertTrue();
- } else {
- console.info('No local accelerometer sensor found with the given deviceId. Test case will return true.');
+ if (!Array.isArray(ret) || ret.length === 0) {
+ console.info('No local sensors found. Test case will return true.');
expect(true).assertTrue();
+ done();
+ return;
}
+ const sensorInfo = ret[0];
+ const callback = (data) => {
+ console.info('Accelerometer data received: ' + JSON.stringify(data));
+ };
+ const sensorInfoParam = {
+ deviceId: sensorInfo.deviceId,
+ sensorIndex: sensorInfo.sensorIndex
+ };
+ const options = {
+ interval: 10000000,
+ sensorInfoParam: sensorInfoParam
+ };
+ sensor.on(sensorInfo.sensorId, callback, options);
+ sensor.off(sensorInfo.sensorId, sensorInfoParam, callback);
+ expect(true).assertTrue();
done();
} catch (err) {
console.error(`getSingleSensorByDeviceSync deviceId=${validDeviceId} err: ` + JSON.stringify(err));
@@ -258,26 +260,27 @@ describe("SensorSyncTest", function () {
try {
let ret = sensor.getSensorListByDeviceSync();
console.info('getSensorListByDeviceSync default device: ' + JSON.stringify(ret));
- if (Array.isArray(ret) && ret.length > 0) {
- const sensorInfo = ret[0];
- const callback = (data) => {
- console.info('Sensor data received: ' + JSON.stringify(data));
- };
- const sensorInfoParam = {
- deviceId: sensorInfo.deviceId,
- sensorIndex: sensorInfo.sensorIndex
- };
- const options = {
- interval: 10000000,
- sensorInfoParam: sensorInfoParam
- };
- sensor.on(sensorInfo.sensorId, callback, options);
- sensor.off(sensorInfo.sensorId, sensorInfoParam, callback);
- expect(true).assertTrue();
- } else {
+ if (!Array.isArray(ret) || ret.length === 0) {
console.info('No local sensors found. Test case will return true.');
expect(true).assertTrue();
+ done();
+ return;
}
+ const sensorInfo = ret[0];
+ const callback = (data) => {
+ console.info('Sensor data received: ' + JSON.stringify(data));
+ };
+ const sensorInfoParam = {
+ deviceId: sensorInfo.deviceId,
+ sensorIndex: sensorInfo.sensorIndex
+ };
+ const options = {
+ interval: 10000000,
+ sensorInfoParam: sensorInfoParam
+ };
+ sensor.on(sensorInfo.sensorId, callback, options);
+ sensor.off(sensorInfo.sensorId, sensorInfoParam, callback);
+ expect(true).assertTrue();
done();
} catch (err) {
console.error('getSensorListByDeviceSync default device err: ' + JSON.stringify(err));
@@ -301,26 +304,27 @@ describe("SensorSyncTest", function () {
try {
let ret = sensor.getSensorListByDeviceSync(validDeviceId);
console.info(`getSensorListByDeviceSync deviceId=${validDeviceId}: ` + JSON.stringify(ret));
- if (Array.isArray(ret) && ret.length > 0) {
- const sensorInfo = ret[0];
- const callback = (data) => {
- console.info(`Sensor ${sensorInfo.type} data received: ` + JSON.stringify(data));
- };
- const sensorInfoParam = {
- deviceId: sensorInfo.deviceId,
- sensorIndex: sensorInfo.sensorIndex
- };
- const options = {
- interval: 10000000,
- sensorInfoParam: sensorInfoParam
- };
- sensor.on(sensorInfo.sensorId, callback, options);
- sensor.off(sensorInfo.sensorId, sensorInfoParam, callback);
- expect(true).assertTrue();
- } else {
- console.info(`No local sensors found with deviceId=${validDeviceId}. Test case will return true.`);
+ if (!Array.isArray(ret) || ret.length === 0) {
+ console.info('No local sensors found. Test case will return true.');
expect(true).assertTrue();
+ done();
+ return;
}
+ const sensorInfo = ret[0];
+ const callback = (data) => {
+ console.info(`Sensor ${sensorInfo.type} data received: ` + JSON.stringify(data));
+ };
+ const sensorInfoParam = {
+ deviceId: sensorInfo.deviceId,
+ sensorIndex: sensorInfo.sensorIndex
+ };
+ const options = {
+ interval: 10000000,
+ sensorInfoParam: sensorInfoParam
+ };
+ sensor.on(sensorInfo.sensorId, callback, options);
+ sensor.off(sensorInfo.sensorId, sensorInfoParam, callback);
+ expect(true).assertTrue();
done();
} catch (err) {
console.error(`getSensorListByDeviceSync deviceId=${validDeviceId} err: ` + JSON.stringify(err));
diff --git a/test/unittest/interfaces/js/sensor/common/CommonConstants.js b/test/unittest/interfaces/js/sensor/common/CommonConstants.js
index c1aba095e52e08060eb0fcbef1a3f8c22cb429b7..abc4a087105ae189b34e200bfd7427cd537b8806 100755
--- a/test/unittest/interfaces/js/sensor/common/CommonConstants.js
+++ b/test/unittest/interfaces/js/sensor/common/CommonConstants.js
@@ -43,15 +43,35 @@ export default class CommonConstants {
static SERVICE_EXCEPTION_CODE = 14500101;
/**
- * Exception code of sensorId no support
+ * Exception code of sensor not supported
*/
- static SENSOR_NO_SUPPORT_CODE = 14500102
+ static SENSOR_NO_SUPPORT_CODE = 14500102;
/**
- * eps
+ * Eps
*/
static EPS = 0.01;
+ /**
+ * Delay time
+ */
+ static DELAY_TIME = 1000;
+
+ /**
+ * Sensor interval
+ */
+ static SENSOR_INTERVAL = 100000000;
+
+ /**
+ * Invalid sensor interval
+ */
+ static INVALID_SENSOR_INTERVAL = -1;
+
+ /**
+ * Invalid sensor id
+ */
+ static INVALID_SENSOR_ID = -1;
+
/**
* token id
*/
diff --git a/test/unittest/interfaces/js/sensor/config.json b/test/unittest/interfaces/js/sensor/config.json
index aabb3f4b8a5544b29581e64aedf217387cef1dfd..675fc7e8d6bab860cd9cd9a2635f6b160b8ec796 100644
--- a/test/unittest/interfaces/js/sensor/config.json
+++ b/test/unittest/interfaces/js/sensor/config.json
@@ -57,7 +57,8 @@
"name": ".MyApplication",
"deviceType": [
"default",
- "tablet"
+ "tablet",
+ "2in1"
],
"distro": {
"deliveryWithInstall": true,
diff --git a/utils/common/BUILD.gn b/utils/common/BUILD.gn
index 3fb0e5377317139f2120b2ca926816b0b6b3b89d..3c9688847c8281b022ac587957d1f32e8a2a11b8 100644
--- a/utils/common/BUILD.gn
+++ b/utils/common/BUILD.gn
@@ -59,14 +59,10 @@ ohos_shared_library("libsensor_utils") {
"c_utils:utils",
"hicollie:libhicollie",
"hilog:libhilog",
+ "hisysevent:libhisysevent",
"ipc:ipc_single",
]
- defines = sensor_default_defines
- if (hiviewdfx_hisysevent_enable) {
- external_deps += [ "hisysevent:libhisysevent" ]
- }
-
innerapi_tags = [ "platformsdk_indirect" ]
part_name = "sensor"
subsystem_name = "sensors"
diff --git a/utils/common/include/permission_util.h b/utils/common/include/permission_util.h
index 49223da52f8b2543dfcf645b173386b35998017d..1fef8a2f8d67b89c8b0a4980a16d50ce0cc52b4c 100644
--- a/utils/common/include/permission_util.h
+++ b/utils/common/include/permission_util.h
@@ -16,6 +16,9 @@
#ifndef PERMISSION_UTIL_H
#define PERMISSION_UTIL_H
+#include
+#include
+
#include "access_token.h"
#include "singleton.h"
@@ -40,6 +43,6 @@ private:
void AddPermissionRecord(AccessTokenID tokenID, const std::string &permissionName, bool status);
static std::unordered_map sensorPermissions_;
};
-} // namespace Sensors
-} // namespace OHOS
-#endif // PERMISSION_UTIL_H
+} // namespace Sensors
+} // namespace OHOS
+#endif // PERMISSION_UTIL_H
diff --git a/utils/common/include/sensor_channel_info.h b/utils/common/include/sensor_channel_info.h
index 26a715d5c1273f33b2bd8bcb30b671703454f123..d5416b71f0ecce75ea4b92534f5c0ae34240ab2c 100644
--- a/utils/common/include/sensor_channel_info.h
+++ b/utils/common/include/sensor_channel_info.h
@@ -16,7 +16,9 @@
#ifndef SENSOR_CHANNEL_INFO_H
#define SENSOR_CHANNEL_INFO_H
+#include
#include
+#include
namespace OHOS {
namespace Sensors {
@@ -51,6 +53,6 @@ private:
uint32_t fifoCount_;
std::vector cmdType_;
};
-} // namespace Sensors
-} // namespace OHOS
-#endif // SENSOR_CHANNEL_INFO_H
+} // namespace Sensors
+} // namespace OHOS
+#endif // SENSOR_CHANNEL_INFO_H
diff --git a/utils/common/include/sensor_data_event.h b/utils/common/include/sensor_data_event.h
index 7eea424f070ee0fc20770ac68feed6fecd2e5e96..db865edd40ad6b64dfcf58377487cdb69facc72e 100755
--- a/utils/common/include/sensor_data_event.h
+++ b/utils/common/include/sensor_data_event.h
@@ -59,15 +59,15 @@ struct ExtraSensorInfo {
};
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 */
+ int32_t deviceId = -1; /**< Device ID */
+ int32_t sensorTypeId = -1; /**< Sensor type ID */
+ int32_t sensorId = -1; /**< Sensor ID */
+ int32_t location = -1; /**< Is the device a local device or an external device */
+ std::string deviceName = ""; /**< Device name */
+ int32_t status = -1; /**< Device on or out status */
+ int32_t reserved = -1; /**< Reserved */
+ int64_t timestamp = -1; /**< Time when sensor plug data was reported */
};
-} // namespace Sensors
-} // namespace OHOS
+} // namespace Sensors
+} // namespace OHOS
#endif // SENSOR_DATA_EVENT_H
diff --git a/utils/common/include/sensor_xcollie.h b/utils/common/include/sensor_xcollie.h
index 34f540559e3ce132ea171b36079a00eb1c0e689c..c0a4dd7bf4a07618d7a759ee06d313364da36d35 100644
--- a/utils/common/include/sensor_xcollie.h
+++ b/utils/common/include/sensor_xcollie.h
@@ -24,16 +24,17 @@
namespace OHOS {
namespace Sensors {
const unsigned int XCOLLIE_TIMEOUT_15S = 15;
+const unsigned int XCOLLIE_TIMEOUT_10S = 10;
const unsigned int XCOLLIE_TIMEOUT_5S = 5;
class SensorXcollie {
public:
- SensorXcollie(const std::string& tag, unsigned int timeoutSeconds = 10,
+ SensorXcollie(const std::string& tag, unsigned int timeoutSeconds = XCOLLIE_TIMEOUT_10S,
std::function func = nullptr, void *arg = nullptr,
unsigned int flag = HiviewDFX::XCOLLIE_FLAG_LOG);
~SensorXcollie();
private:
- int id_;
+ std::atomic_int32_t id_;
std::string tag_;
};
} // namespace Sensors
diff --git a/utils/common/src/motion_plugin.cpp b/utils/common/src/motion_plugin.cpp
index 4c0806855ca93eec1d367789f9cbcc156db89caf..a440ab272f9bcc822388d7b6c7fb641ccfb0b7d7 100644
--- a/utils/common/src/motion_plugin.cpp
+++ b/utils/common/src/motion_plugin.cpp
@@ -59,7 +59,6 @@ __attribute__((no_sanitize("cfi"))) void MotionTransformIfRequired(const std::st
uint32_t state, SensorData* sensorData)
{
if (g_handle == nullptr) {
- SEN_HILOGD("g_handle is nullptr");
return;
}
MotionTransformIfRequiredPtr func = (MotionTransformIfRequiredPtr)(dlsym(g_handle, "TransformIfRequired"));
diff --git a/utils/common/src/permission_util.cpp b/utils/common/src/permission_util.cpp
index c5f58f2274777064b81e3507ad236372de178ce6..b8424a247a3c4679d835b2b9977c6505f12ad113 100644
--- a/utils/common/src/permission_util.cpp
+++ b/utils/common/src/permission_util.cpp
@@ -40,11 +40,10 @@ std::unordered_map PermissionUtil::sensorPermissions_ = {
int32_t PermissionUtil::CheckSensorPermission(AccessTokenID callerToken, int32_t sensorTypeId)
{
- auto iter = sensorPermissions_.find(sensorTypeId);
- if (iter == sensorPermissions_.end()) {
+ if (sensorPermissions_.find(sensorTypeId) == sensorPermissions_.end()) {
return PERMISSION_GRANTED;
}
- std::string permissionName = iter->second;
+ std::string permissionName = sensorPermissions_[sensorTypeId];
int32_t ret = AccessTokenKit::VerifyAccessToken(callerToken, permissionName);
if ((permissionName == ACTIVITY_MOTION_PERMISSION)
|| (permissionName == READ_HEALTH_DATA_PERMISSION)) {
@@ -82,5 +81,5 @@ int32_t PermissionUtil::CheckManageSensorPermission(AccessTokenID callerToken)
}
return ret;
}
-} // namespace Sensors
-} // namespace OHOS
+} // namespace Sensors
+} // namespace OHOS
diff --git a/utils/ipc/src/stream_buffer.cpp b/utils/ipc/src/stream_buffer.cpp
index 0b57bf85a3e5a80a0e15f45b6ebae62e42d6e626..f9215b811c686b3e42f8fbd133c6aec84ca88e54 100644
--- a/utils/ipc/src/stream_buffer.cpp
+++ b/utils/ipc/src/stream_buffer.cpp
@@ -24,9 +24,7 @@ StreamBuffer::StreamBuffer(const StreamBuffer &buf)
StreamBuffer &StreamBuffer::operator=(const StreamBuffer &other)
{
- if (this != &other) {
- Clone(other);
- }
+ Clone(other);
return *this;
}
@@ -268,5 +266,5 @@ const char *StreamBuffer::WriteBuf() const
return &szBuff_[wPos_];
}
#endif // OHOS_BUILD_ENABLE_RUST
-} // namespace Sensors
-} // namespace OHOS
+} // namespace Sensors
+} // namespace OHOS
diff --git a/vibration_convert/core/algorithm/conversion/include/fft.h b/vibration_convert/core/algorithm/conversion/include/fft.h
index a10afe7aba30a56ab1bcaabc28bad5059737d974..4043deee468101828d1f2425f5a22f9074065df2 100644
--- a/vibration_convert/core/algorithm/conversion/include/fft.h
+++ b/vibration_convert/core/algorithm/conversion/include/fft.h
@@ -103,8 +103,6 @@ private:
*/
int32_t AlgRealFFT(FftParaAndResult ¶Res);
int32_t AlgFFT(bool inverseTransform, FftParaAndResult ¶Res);
- void Normalize(FftParaAndResult ¶Res);
- int32_t PreprocessData(uint32_t numSamples, FftParaAndResult ¶Res);
int32_t AlgInitFFT();
private:
@@ -121,6 +119,6 @@ private:
FftParaAndResult para_;
uint32_t** fftBitTable_ { nullptr };
};
-} // namespace Sensors
-} // namespace OHOS
-#endif // FFT_H
\ No newline at end of file
+} // namespace Sensors
+} // namespace OHOS
+#endif // FFT_H
\ No newline at end of file
diff --git a/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp b/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp
index e2e135bed8a4b476fb30e4d6fb3fe88537572f03..2abedb2ff93a8f09597244ab74f91e3544647cc8 100644
--- a/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp
+++ b/vibration_convert/core/algorithm/conversion/src/conversion_fft.cpp
@@ -27,7 +27,7 @@ namespace Sensors {
namespace {
constexpr int32_t SPECTRUM_COUNT_MAX { 8192 };
constexpr int32_t MAX_FFT_SIZE { 10240 };
-} // namespace
+} // namespace
int32_t ConversionFFT::Init(const FFTInputPara &fftPara)
{
@@ -96,7 +96,7 @@ int32_t ConversionFFT::Process(const std::vector &values, int32_t &frame
frameCount = 0;
bool isFrameFull = false;
size_t valuesSize = values.size();
- for (size_t j = 0; j < valuesSize; ++j) {
+ for (size_t j = 0; j < valuesSize; j++) {
// add value to buffer at current pos
if (pos_ < static_cast(fftResult_.buffer.size())) {
fftResult_.buffer[pos_++] = static_cast(values[j]);
@@ -115,7 +115,7 @@ int32_t ConversionFFT::Process(const std::vector &values, int32_t &frame
// reset pos to start of hop
pos_ = para_.windowSize - para_.hopSize;
/** shift buffer back by one hop size. */
- for (int32_t i = 0; i < pos_; ++i) {
+ for (int32_t i = 0; i < pos_; i++) {
fftResult_.buffer[i] = fftResult_.buffer[i + para_.hopSize];
}
isFftCalcFinish_ = true;
@@ -142,7 +142,7 @@ float ConversionFFT::GetSpectralFlatness() const
}
float geometricMean = 0.0F;
float arithmaticMean = 0.0F;
- for (int32_t i = 0; i < bins_; ++i) {
+ for (int32_t i = 0; i < bins_; i++) {
if (fftResult_.magnitudes[i] != 0) {
geometricMean += logf(fftResult_.magnitudes[i]);
}
@@ -158,7 +158,7 @@ float ConversionFFT::GetSpectralCentroid() const
{
float x = 0.0F;
float y = 0.0F;
- for (int32_t i = 0; i < bins_; ++i) {
+ for (int32_t i = 0; i < bins_; i++) {
x += fabs(fftResult_.magnitudes[i]) * i;
y += fabs(fftResult_.magnitudes[i]);
}
@@ -199,15 +199,15 @@ float ConversionIFFT::Process(const std::vector &mags, const std::vector<
}
// add to output
// shift back by one hop
- for (int32_t i = 0; i < (para_.fftSize - para_.hopSize); ++i) {
+ for (int32_t i = 0; i < (para_.fftSize - para_.hopSize); i++) {
fftResult_.buffer[i] = fftResult_.buffer[i + para_.hopSize];
}
// clear the end chunk
- for (int32_t i = 0; i < para_.hopSize; ++i) {
+ for (int32_t i = 0; i < para_.hopSize; i++) {
fftResult_.buffer[i + para_.fftSize - para_.hopSize] = 0.0F;
}
// merge new output
- for (int32_t i = 0; i < para_.fftSize; ++i) {
+ for (int32_t i = 0; i < para_.fftSize; i++) {
fftResult_.buffer[i] += ifftOut_[i];
}
}
@@ -238,14 +238,17 @@ int32_t ConversionOctave::Init(float samplingRate, int32_t nBandsInTheFFT, int32
// this isn't currently configurable (used once here then no effect), but here's some reasoning
firstOctaveFrequency_ = 55.0F;
// for each spectrum[] bin, calculate the mapping into the appropriate average[] bin.
- spe2avg_ = MakeSharedArray(static_cast(nSpectrum_));
+ auto spe2avg = new (std::nothrow) int32_t[nSpectrum_];
+ CHKPR(spe2avg, Sensors::ERROR);
+ std::shared_ptr spe2avgShared(spe2avg, std::default_delete());
+ spe2avg_ = std::move(spe2avgShared);
int32_t avgIdx = 0;
float averageFreq = firstOctaveFrequency_; // the "top" of the first averaging bin
// we're looking for the "top" of the first spectrum bin, and i'm just sort of
// guessing that this is where it is (or possibly spectrumFrequencySpan/2?)
// ... either way it's probably close enough for these purposes
float spectrumFreq = spectrumFrequencySpan_;
- for (int32_t speIdx = 0; speIdx < nSpectrum_; ++speIdx) {
+ for (int32_t speIdx = 0; speIdx < nSpectrum_; speIdx++) {
while (spectrumFreq > averageFreq) {
++avgIdx;
averageFreq *= averageFrequencyIncrement_;
@@ -254,9 +257,19 @@ int32_t ConversionOctave::Init(float samplingRate, int32_t nBandsInTheFFT, int32
spectrumFreq += spectrumFrequencySpan_;
}
nAverages_ = avgIdx;
- averages_ = MakeSharedArray(static_cast(nAverages_));
- peaks_ = MakeSharedArray(static_cast(nAverages_));
- peakHoldTimes_ = MakeSharedArray(static_cast(nAverages_));
+ auto averages = new (std::nothrow) float[nAverages_];
+ CHKPR(averages, Sensors::ERROR);
+ std::shared_ptr averagesShared(averages, std::default_delete());
+ averages_ = std::move(averagesShared);
+ auto peaks = new (std::nothrow) float[nAverages_];
+ CHKPR(peaks, Sensors::ERROR);
+ std::shared_ptr peaksShared(peaks, std::default_delete());
+ peaks_ = std::move(peaksShared);
+ auto peakHoldTimes = new (std::nothrow) int32_t[nAverages_];
+ CHKPR(peakHoldTimes, Sensors::ERROR);
+ std::shared_ptr peakHoldTimesShared(peakHoldTimes, std::default_delete());
+ peakHoldTimes_ = std::move(peakHoldTimesShared);
+
peakHoldTime_ = 0;
peakDecayRate_ = 0.9F;
linearEQIntercept_ = 1.0F;
@@ -277,12 +290,12 @@ int32_t ConversionOctave::Calculate(const std::vector &fftData)
int32_t lastAvgIdx = 0; // tracks when we've crossed into a new averaging bin, so store current average
float sum = 0.0F; // running total of spectrum data
int32_t count = 0; // count of spectrums accumulated (for averaging)
- for (int32_t speIdx = 0; speIdx < nSpectrum_; ++speIdx) {
+ for (int32_t speIdx = 0; speIdx < nSpectrum_; speIdx++) {
++count;
sum += (fftData[speIdx] * (linearEQIntercept_ + speIdx * linearEQSlope_));
int32_t avgIdx = *(spe2avg_.get() + speIdx);
if (avgIdx != lastAvgIdx) {
- for (int32_t j = lastAvgIdx; j < avgIdx; ++j) {
+ for (int32_t j = lastAvgIdx; j < avgIdx; j++) {
*(averages_.get() + j) = sum / static_cast(count);
}
count = 0;
@@ -295,7 +308,7 @@ int32_t ConversionOctave::Calculate(const std::vector &fftData)
*(averages_.get() + lastAvgIdx) = sum / count;
}
// update the peaks separately
- for (int32_t i = 0; i < nAverages_; ++i) {
+ for (int32_t i = 0; i < nAverages_; i++) {
if (IsGreatOrEqual(*(averages_.get() + i), *(peaks_.get() + i))) {
// save new peak level, also reset the hold timer
*(peaks_.get() + i) = *(averages_.get() + i);
@@ -311,5 +324,5 @@ int32_t ConversionOctave::Calculate(const std::vector &fftData)
}
return Sensors::SUCCESS;
}
-} // namespace Sensors
-} // namespace OHOS
\ No newline at end of file
+} // namespace Sensors
+} // namespace OHOS
\ No newline at end of file
diff --git a/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp b/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp
index 126329b81c9a86b2306334886037535325c6f29d..7f0bbcf74f0009e5332e3269ebc3c5436a04fe47 100644
--- a/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp
+++ b/vibration_convert/core/algorithm/conversion/src/conversion_mfcc.cpp
@@ -28,7 +28,7 @@ namespace Sensors {
namespace {
constexpr double BANDS_MIN_THRESHOLD { 0.000001 };
constexpr uint32_t MEL_FILTERS_OR_COEFFS_MAX { 4096 * 4096 };
-} // namespace
+} // namespace
int32_t ConversionMfcc::HandleMelFilterAndLogSquare(const std::vector &powerSpectrum)
{
@@ -101,9 +101,9 @@ int32_t ConversionMfcc::HandleDiscreteCosineTransform()
SEN_HILOGE("numCoeffs_ should not be 0");
return Sensors::ERROR;
}
- for (uint32_t i = 0; i < numCoeffs_; i++) {
+ for (uint32_t i = 0; i < numCoeffs_; ++i) {
coeffs_[i] = 0;
- for (uint32_t j = 0; j < numFilters_; j++) {
+ for (uint32_t j = 0; j < numFilters_; ++j) {
uint32_t idx = i + (j * numCoeffs_);
coeffs_[i] += (dctMatrix_[idx] * melBands_[j]);
}
@@ -181,7 +181,7 @@ std::vector ConversionMfcc::GetMelFilterBank() const
{
std::vector melFilters;
uint32_t num = numFilters_ * numBins_;
- for (uint32_t i = 0; i < num; i++) {
+ for (uint32_t i = 0; i < num; ++i) {
melFilters.emplace_back(melFilters_[i]);
}
return melFilters;
@@ -197,8 +197,8 @@ int32_t ConversionMfcc::CreateDCTCoeffs()
double w1 = 1.0 / (sqrt(numFilters_));
double w2 = sqrt(2.0 / numFilters_);
// generate dct matrix
- for (uint32_t i = 0; i < numCoeffs_; i++) {
- for (uint32_t j = 0; j < numFilters_; j++) {
+ for (uint32_t i = 0; i < numCoeffs_; ++i) {
+ for (uint32_t j = 0; j < numFilters_; ++j) {
uint32_t idx = i + (j * numCoeffs_);
if (i == 0) {
dctMatrix_[idx] = w1 * cos(k * (i + 1) * (j + F_HALF));
@@ -223,27 +223,26 @@ int32_t ConversionMfcc::FiltersMel(int32_t nFft, MfccInputPara para,
fMax = sr / 2.0;
}
size_t nMels = static_cast(para.nMels);
- double fMin = para.minFreq;
frmCount = nFft / 2;
std::vector basis(nMels * frmCount, 0.0);
// generate mel frequencies.
+ double fMin = para.minFreq;
double minMel = OHOS::Sensors::ConvertHtkMel(fMin);
double maxMel = OHOS::Sensors::ConvertHtkMel(fMax);
std::vector filterHzPos(nMels + 2);
double stepMel = (maxMel - minMel) / (nMels + 1);
double stepHz = static_cast(sr) / nFft;
-
double nextMel = minMel;
- for (size_t i = 0; i < (nMels + 2); i++) {
+ for (size_t i = 0; i < (nMels + 2); ++i) {
filterHzPos[i] = OHOS::Sensors::ConvertHtkHz(nextMel);
nextMel += stepMel;
}
std::vector binFs(frmCount);
- for (int32_t j = 0; j < frmCount; j++) {
+ for (int32_t j = 0; j < frmCount; ++j) {
binFs[j] = stepHz * j;
}
int32_t index = 0;
- for (size_t i = 2; i < filterHzPos.size(); i++) {
+ for (size_t i = 2; i < filterHzPos.size(); ++i) {
double prevFreq = filterHzPos[i - 2];
double thisFreq = filterHzPos[i - 1];
double nextFreq = filterHzPos[i];
@@ -251,7 +250,7 @@ int32_t ConversionMfcc::FiltersMel(int32_t nFft, MfccInputPara para,
SEN_HILOGE("The divisor cannot be 0");
return Sensors::ERROR;
}
- for (int32_t j = 0; j < frmCount; j++) {
+ for (int32_t j = 0; j < frmCount; ++j) {
double binFreq = binFs[j];
double lower = (binFreq - prevFreq) / (thisFreq - prevFreq);
double upper = (nextFreq - binFreq) / (nextFreq - thisFreq);
@@ -261,11 +260,7 @@ int32_t ConversionMfcc::FiltersMel(int32_t nFft, MfccInputPara para,
}
}
melBasis = OHOS::Sensors::TransposeMatrix(nMels, basis);
- if (melBasis.empty()) {
- SEN_HILOGE("melBasis is empty");
- return Sensors::ERROR;
- }
- return Sensors::SUCCESS;
+ return melBasis.empty() ? Sensors::ERROR : Sensors::SUCCESS;
}
-} // namespace Sensors
-} // namespace OHOS
\ No newline at end of file
+} // namespace Sensors
+} // namespace OHOS
\ No newline at end of file
diff --git a/vibration_convert/core/algorithm/conversion/src/fft.cpp b/vibration_convert/core/algorithm/conversion/src/fft.cpp
deleted file mode 100644
index 5d6077c81238a1f76b89dc9a626d27b7d721efda..0000000000000000000000000000000000000000
--- a/vibration_convert/core/algorithm/conversion/src/fft.cpp
+++ /dev/null
@@ -1,450 +0,0 @@
-/*
- * 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 "fft.h"
-
-#include
-#include
-#include
-#include
-#include
-
-#include "sensor_log.h"
-#include "sensors_errors.h"
-
-#undef LOG_TAG
-#define LOG_TAG "Fft"
-
-namespace OHOS {
-namespace Sensors {
-namespace {
-constexpr uint32_t MAX_FAST_BITS { 16 };
-constexpr int32_t NUM_SAMPLES_MIN { 2 };
-constexpr double HAMMING_WND_UP { 0.54 };
-constexpr double HAMMING_WND_DOWN { 0.46 };
-constexpr float VOLUME_MIN { 0.000001 };
-constexpr double AMP_TO_DB_COEF { 20.0 };
-constexpr bool TRANSFORM_INVERSE_FLAG { true };
-} // namespace
-
-Fft::~Fft()
-{
- if (fftBitTable_ == nullptr) {
- return;
- }
- for (uint32_t i = 0; i < MAX_FAST_BITS; ++i) {
- if (fftBitTable_[i] != nullptr) {
- free(fftBitTable_[i]);
- fftBitTable_[i] = nullptr;
- }
- }
- free(fftBitTable_);
- fftBitTable_ = nullptr;
-}
-
-inline uint32_t Fft::FastReverseBits(uint32_t pos, uint32_t numBits)
-{
- if (numBits <= MAX_FAST_BITS && numBits >= 1) {
- return fftBitTable_[numBits - 1][pos];
- }
- return ReverseBits(pos, numBits);
-}
-
-int32_t Fft::AlgInitFFT()
-{
- // use malloc for 16 byte alignment
- fftBitTable_ = (uint32_t **)malloc(MAX_FAST_BITS * sizeof(uint32_t *));
- CHKPR(fftBitTable_, Sensors::ERROR);
- uint32_t length = 2;
- for (uint32_t j = 1; j <= MAX_FAST_BITS; ++j) {
- fftBitTable_[j - 1] = (uint32_t *)malloc(length * sizeof(uint32_t));
- CHKPR(fftBitTable_[j - 1], Sensors::ERROR);
- for (uint32_t i = 0; i < length; ++i) {
- fftBitTable_[j - 1][i] = ReverseBits(i, j);
- }
- length <<= 1;
- }
- return Sensors::SUCCESS;
-}
-
-/*
- * Complex Fast Fourier Transform
- */
-int32_t Fft::AlgFFT(bool inverseTransform, FftParaAndResult ¶Res)
-{
- uint32_t numSamples = static_cast(paraRes.numSamples);
- if (!IsPowerOfTwo(numSamples)) {
- SEN_HILOGE("The parameter is invalid,numSamples:%{public}d", numSamples);
- return Sensors::PARAMETER_ERROR;
- }
- if (PreprocessData(numSamples, paraRes) != Sensors::SUCCESS) {
- SEN_HILOGE("PreprocessData failed");
- return Sensors::ERROR;
- }
- // Do the FFT itself...
- int32_t blockEnd = 1;
- double angleNumerator = inverseTransform ? -(2 * M_PI) : (2 * M_PI);
- for (int32_t blockSize = 2; blockSize <= paraRes.numSamples; blockSize <<= 1) {
- double deltaAngle = angleNumerator / static_cast(blockSize);
- float twoSinMagnitude = sin(-2 * deltaAngle);
- float oneSinMagnitude = sin(-deltaAngle);
- float twoCosMagnitude = cos(-2 * deltaAngle);
- float oneCosMagnitude = cos(-deltaAngle);
- float w = 2 * oneCosMagnitude;
- for (int32_t i = 0; i < paraRes.numSamples; i += blockSize) {
- float secondAmpReal = twoCosMagnitude;
- float firstAmpReal = oneCosMagnitude;
- float thirdAmpImaginary = twoSinMagnitude;
- float secondAmpImaginary = oneSinMagnitude;
- for (int32_t j = i, n = 0; n < blockEnd; ++j, ++n) {
- float zerothAmpReal = w * firstAmpReal - secondAmpReal;
- secondAmpReal = firstAmpReal;
- firstAmpReal = zerothAmpReal;
- float firstAmpImaginary = w * secondAmpImaginary - thirdAmpImaginary;
- thirdAmpImaginary = secondAmpImaginary;
- secondAmpImaginary = firstAmpImaginary;
- int32_t k = j + blockEnd;
- float real = zerothAmpReal * paraRes.realOut[k] - firstAmpImaginary * paraRes.imagOut[k];
- float imaginary = zerothAmpReal * paraRes.imagOut[k] + firstAmpImaginary * paraRes.realOut[k];
- paraRes.realOut[k] = paraRes.realOut[j] - real;
- paraRes.imagOut[k] = paraRes.imagOut[j] - imaginary;
- paraRes.realOut[j] += real;
- paraRes.imagOut[j] += imaginary;
- }
- }
- blockEnd = blockSize;
- }
- // Need to normalize if inverse transform
- if (inverseTransform) {
- Normalize(paraRes);
- }
- return Sensors::SUCCESS;
-}
-
-void Fft::Normalize(FftParaAndResult ¶Res)
-{
- float denom = static_cast(paraRes.numSamples);
- for (int32_t i = 0; i < paraRes.numSamples; ++i) {
- paraRes.realOut[i] /= denom;
- paraRes.imagOut[i] /= denom;
- }
-}
-
-int32_t Fft::PreprocessData(uint32_t numSamples, FftParaAndResult ¶Res)
-{
- if ((fftBitTable_ == nullptr) && (AlgInitFFT() != Sensors::SUCCESS)) {
- SEN_HILOGE("fftBitTable_ failed to allocate memory");
- return Sensors::ERROR;
- }
- uint32_t numBits = ObtainNumberOfBits(numSamples);
- if (numBits < 1) {
- SEN_HILOGE("numBits is an invalid value");
- return Sensors::ERROR;
- }
- // Do simultaneous data copy and bit-reversal ordering into outputs...
- for (uint32_t i = 0; i < numSamples; ++i) {
- uint32_t j = FastReverseBits(i, numBits);
- paraRes.realOut[j] = paraRes.realIn[i];
- paraRes.imagOut[j] = (paraRes.imagIn.empty()) ? 0.0F : paraRes.imagIn[i];
- }
- return Sensors::SUCCESS;
-}
-
-/*
- * Real Fast Fourier Transform
- *
- * This function was based on the code in Numerical Recipes in C.
- * In Num. Rec., the inner loop is based on a single 1-based array
- * of interleaved real and imaginary numbers. Because we have two
- * separate zero-based arrays, our indices are quite different.
- * Here is the correspondence between Num. Rec. indices and our indices:
- *
- * i1 <-> real[i]
- * i2 <-> imag[i]
- * i3 <-> real[n/2-i]
- * i4 <-> imag[n/2-i]
- */
-int32_t Fft::AlgRealFFT(FftParaAndResult ¶Res)
-{
- if (paraRes.numSamples == 0) {
- SEN_HILOGE("The divisor should not be 0");
- return Sensors::PARAMETER_ERROR;
- }
- int32_t half = paraRes.numSamples / 2;
- float theta = M_PI / half;
- for (int32_t i = 0; i < half; ++i) {
- para_.realIn[i] = paraRes.realIn[2 * i];
- para_.imagIn[i] = paraRes.realIn[2 * i + 1];
- }
- AlgFFT(!TRANSFORM_INVERSE_FLAG, para_);
- float wtemp = static_cast(sin(F_HALF * theta));
- float wpr = -2.0 * wtemp * wtemp;
- float wpi = static_cast(sin(theta));
- float wr = 1.0 + wpr;
- float wi = wpi;
- float previousHalfReal = 0.0F;
- for (int32_t i = 1; i < (half / 2); ++i) {
- int32_t i3 = half - i;
- previousHalfReal = F_HALF * (para_.realOut[i] + para_.realOut[i3]);
- float previousHalfIm = F_HALF * (para_.imagOut[i] - para_.imagOut[i3]);
- float lastHalfReal = F_HALF * (para_.imagOut[i] + para_.imagOut[i3]);
- float lastHalfIm = -F_HALF * (para_.realOut[i] - para_.realOut[i3]);
- para_.realOut[i] = previousHalfReal + wr * lastHalfReal - wi * lastHalfIm;
- para_.imagOut[i] = previousHalfIm + wr * lastHalfIm + wi * lastHalfReal;
- para_.realOut[i3] = previousHalfReal - wr * lastHalfReal + wi * lastHalfIm;
- para_.imagOut[i3] = -previousHalfIm + wr * lastHalfIm + wi * lastHalfReal;
- wtemp = wr;
- wr = wtemp * wpr - wi * wpi + wr;
- wi = wi * wpr + wtemp * wpi + wi;
- }
- previousHalfReal = para_.realOut[0];
- para_.realOut[0] = previousHalfReal + para_.imagOut[0];
- para_.imagOut[0] = previousHalfReal - para_.imagOut[0];
- for (int32_t i = 0; i < half; ++i) {
- paraRes.realOut[i] = para_.realOut[i];
- paraRes.imagOut[i] = para_.imagOut[i];
- }
- return Sensors::SUCCESS;
-}
-
-/*
- * AlgPowerSpectrum
- *
- * This function computes the same as AlgRealFFT, above, but
- * adds the squares of the real and imaginary part of each
- * coefficient, extracting the power and throwing away the
- * phase.
- *
- * For speed, it does not call AlgRealFFT, but duplicates some
- * of its code.
- */
-int32_t Fft::AlgPowerSpectrum(int32_t numSamples, const std::vector &in, std::vector &out)
-{
- if (numSamples == 0) {
- SEN_HILOGE("The divisor should not be 0");
- return Sensors::PARAMETER_ERROR;
- }
- int32_t half = numSamples / 2;
- float theta = M_PI / half;
- for (int32_t i = 0; i < half; ++i) {
- para_.realIn[i] = in[2 * i];
- para_.imagIn[i] = in[2 * i + 1];
- }
- AlgFFT(!TRANSFORM_INVERSE_FLAG, para_);
- float wtemp = static_cast(sin(F_HALF * theta));
- float wpr = -2.0 * wtemp * wtemp;
- float wpi = static_cast(sin(theta));
- float wr = 1.0 + wpr;
- float wi = wpi;
- float previousHalfReal = 0.0F;
- float rt = 0.0F;
- float it = 0.0F;
- for (int32_t i = 1; i < (half / 2); ++i) {
- int32_t i3 = half - i;
- previousHalfReal = F_HALF * (para_.realOut[i] + para_.realOut[i3]);
- float previousHalfIm = F_HALF * (para_.imagOut[i] - para_.imagOut[i3]);
- float lastHalfReal = F_HALF * (para_.imagOut[i] + para_.imagOut[i3]);
- float lastHalfIm = -F_HALF * (para_.realOut[i] - para_.realOut[i3]);
- rt = previousHalfReal + wr * lastHalfReal - wi * lastHalfIm;
- it = previousHalfIm + wr * lastHalfIm + wi * lastHalfReal;
- out[i] = rt * rt + it * it;
- rt = previousHalfReal - wr * lastHalfReal + wi * lastHalfIm;
- it = -previousHalfIm + wr * lastHalfIm + wi * lastHalfReal;
- out[i3] = rt * rt + it * it;
- wr = (wtemp = wr) * wpr - wi * wpi + wr;
- wi = wi * wpr + wtemp * wpi + wi;
- }
- rt = (previousHalfReal = para_.realOut[0]) + para_.imagOut[0];
- it = previousHalfReal - para_.imagOut[0];
- out[0] = rt * rt + it * it;
- rt = para_.realOut[half / 2];
- it = para_.imagOut[half / 2];
- out[half / 2] = rt * rt + it * it;
- return Sensors::SUCCESS;
-}
-
-int32_t Fft::WindowFunc(int32_t whichFunction, int32_t numSamples, float *out)
-{
- if (numSamples < NUM_SAMPLES_MIN) {
- SEN_HILOGE("numSamples are less than 2");
- return Sensors::PARAMETER_ERROR;
- }
- switch (whichFunction) {
- case WND_TYPE_BARTLETT: {
- float samplesCount = static_cast(numSamples);
- // Bartlett (triangular) window
- for (int32_t i = 0; i < (numSamples / 2); ++i) {
- out[i] *= i / (samplesCount / 2);
- out[i + (numSamples / 2)] *= 1.0 - (i / (samplesCount / 2));
- }
- return Sensors::SUCCESS;
- }
- case WND_TYPE_HAMMING: {
- // Hamming
- for (int32_t i = 0; i < numSamples; ++i) {
- out[i] *= HAMMING_WND_UP - HAMMING_WND_DOWN * cos(2 * M_PI * i / (numSamples - 1));
- }
- return Sensors::SUCCESS;
- }
- case WND_TYPE_HANNING: {
- // Hanning
- for (int32_t i = 0; i < numSamples; ++i) {
- out[i] *= F_HALF - F_HALF * cos(2 * M_PI * i / (numSamples - 1));
- }
- return Sensors::SUCCESS;
- }
- default: {
- SEN_HILOGE("WindowType: %{public}d invalid", whichFunction);
- return Sensors::ERROR;
- }
- }
-}
-
-int32_t Fft::GenWindow(int32_t whichFunction, int32_t numSamples, std::vector &window)
-{
- if (numSamples < NUM_SAMPLES_MIN) {
- SEN_HILOGE("numSamples are less than 2");
- return Sensors::PARAMETER_ERROR;
- }
- switch (whichFunction) {
- case WND_TYPE_BARTLETT: {
- float samplesCount = static_cast(numSamples);
- // Bartlett (triangular) window
- for (int32_t i = 0; i < (numSamples / 2); ++i) {
- window[i] = i / (samplesCount / 2);
- window[i + (numSamples / 2)] = 1.0 - (i / (samplesCount / 2));
- }
- return Sensors::SUCCESS;
- }
- case WND_TYPE_HAMMING: {
- for (int32_t i = 0; i < numSamples; ++i) {
- window[i] = HAMMING_WND_UP - HAMMING_WND_DOWN * cos(2 * M_PI * i / (numSamples - 1));
- }
- return Sensors::SUCCESS;
- }
- case WND_TYPE_HANNING: {
- // Hanning
- for (int32_t i = 0; i < numSamples; ++i) {
- window[i] = F_HALF - F_HALF * cos(2 * M_PI * i / (numSamples - 1));
- }
- return Sensors::SUCCESS;
- }
- default: {
- SEN_HILOGE("WindowType: %{public}d invalid", whichFunction);
- return Sensors::ERROR;
- }
- }
-}
-
-void Fft::Init(int32_t fftSize)
-{
- fftSize_ = fftSize;
- half_ = fftSize / 2;
-
- fftParaRes_ = FftParaAndResult(fftSize_);
- para_ = FftParaAndResult(half_);
-}
-
-std::vector Fft::GetReal() const
-{
- return fftParaRes_.realOut;
-}
-
-std::vector Fft::GetImg() const
-{
- return fftParaRes_.imagOut;
-}
-
-void Fft::CalcFFT(const std::vector &data, const std::vector &window)
-{
- // windowing
- for (int32_t i = 0; i < fftSize_; ++i) {
- fftParaRes_.realIn[i] = data[i] * window[i];
- }
- // fftParaRes_.realIn include realIn and imageIn!
- AlgRealFFT(fftParaRes_);
-}
-
-void Fft::ConvertPolar(std::vector &magnitude, std::vector &phase)
-{
- for (int32_t i = 0; i < half_; ++i) {
- /* compute power */
- float power = pow(fftParaRes_.realOut[i], 2) + pow(fftParaRes_.imagOut[i], 2);
- /* compute magnitude and phase */
- magnitude[i] = sqrt(power);
- phase[i] = atan2(fftParaRes_.imagOut[i], fftParaRes_.realOut[i]);
- }
-}
-
-/* Calculate the power spectrum */
-void Fft::CalculatePowerSpectrum(const std::vector &data, const std::vector &window,
- std::vector &magnitude, std::vector &phase)
-{
- CalcFFT(data, window);
- ConvertPolar(magnitude, phase);
-}
-
-void Fft::ConvertDB(const std::vector &in, std::vector &out)
-{
- for (int32_t i = 0; i < half_; ++i) {
- if (IsLessNotEqual(in[i], VOLUME_MIN)) {
- // less than 0.1 nV
- out[i] = 0.0F; // out of range
- } else {
- out[i] = AMP_TO_DB_COEF * log10(in[i] + 1); // get to to db scale
- }
- }
-}
-
-void Fft::ConvertCart(const std::vector &magnitude, const std::vector &phase)
-{
- /* get real and imag part */
- for (int32_t i = 0; i < half_; ++i) {
- fftParaRes_.realIn[i] = magnitude[i] * cos(phase[i]);
- fftParaRes_.imagIn[i] = magnitude[i] * sin(phase[i]);
- }
- /* zero negative frequencies */
- std::fill(fftParaRes_.realIn.begin() + half_, fftParaRes_.realIn.begin() + half_ + half_, 0);
- std::fill(fftParaRes_.imagIn.begin() + half_, fftParaRes_.imagIn.begin() + half_ + half_, 0);
-}
-
-void Fft::CalcIFFT(const std::vector &window, std::vector &finalOut)
-{
- // second parameter indicates inverse transform
- fftParaRes_.numSamples = fftSize_;
- AlgFFT(TRANSFORM_INVERSE_FLAG, fftParaRes_);
- for (int32_t i = 0; i < fftSize_; ++i) {
- finalOut[i] += fftParaRes_.realOut[i] * window[i];
- }
-}
-
-void Fft::InverseFFTComplex(const std::vector &window, const std::vector &real,
- const std::vector &imaginary, std::vector &finalOut)
-{
- for (int32_t i = 0; i < half_; ++i) {
- fftParaRes_.realOut[i] = real[i];
- fftParaRes_.imagOut[i] = imaginary[i];
- }
- CalcIFFT(window, finalOut);
-}
-
-void Fft::InversePowerSpectrum(const std::vector &window, const std::vector &magnitude,
- const std::vector &phase, std::vector &finalOut)
-{
- ConvertCart(magnitude, phase);
- CalcIFFT(window, finalOut);
-}
-} // namespace Sensors
-} // namespace OHOS
\ No newline at end of file
diff --git a/vibration_convert/core/algorithm/frequency_estimation/include/frequency_estimation.h b/vibration_convert/core/algorithm/frequency_estimation/include/frequency_estimation.h
deleted file mode 100644
index 5a6fbf0c0fbd2b4289fbc6febd748bce63bdec52..0000000000000000000000000000000000000000
--- a/vibration_convert/core/algorithm/frequency_estimation/include/frequency_estimation.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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 FREQUENCY_ESTIMATION_H
-#define FREQUENCY_ESTIMATION_H
-
-#include
-#include
-#include
-#include
-
-#include "utils.h"
-
-namespace OHOS {
-namespace Sensors {
-/**
-Conversion functions
-*/
-class FrequencyEstimation {
-public:
- FrequencyEstimation() = default;
- ~FrequencyEstimation() = default;
-
- /**
- * @brief Get the zero crossing rate
- *
- * @param data Audio data.
- * @param frmLength The length of a frame, usually to the nth power of 2.
- * @param hopLength The length of the window to be processed in a frame, usually to the nth power of 2.
- *
- * @return std::vector Zero crossing rate'vector.
- */
- std::vector GetZeroCrossingRate(const std::vector &data, int32_t frmLength, int32_t hopLength);
-
- /**
- * @brief Invalid frequency processing
- * The default value of freqReaderAbsFlag is true.
- *
- * @param frequencyHz The calculated frequency includes invalid frequencies.
- * @param voiceSegmentFlag Set of voice and silent segment flags.
- * @param rmseIntensityNorm Normalized intensity values.
- * @param freqNorm Normalized frequency values.
- */
- void FreqPostProcess(const std::vector &frequencyHz, const std::vector &voiceSegmentFlag,
- const std::vector &rmseIntensityNorm, std::vector &freqNorm);
-
-private:
- double Mean(const std::vector &data);
-
-private:
- bool freqReaderAbsFlag_ { true };
-};
-} // namespace Sensors
-} // namespace OHOS
-#endif // FREQUENCY_ESTIMATION_H
\ No newline at end of file
diff --git a/vibration_convert/core/algorithm/frequency_estimation/src/frequency_estimation.cpp b/vibration_convert/core/algorithm/frequency_estimation/src/frequency_estimation.cpp
deleted file mode 100644
index eadfa93bd45a4d7997eb8ed7ef58e7c8277b6b5d..0000000000000000000000000000000000000000
--- a/vibration_convert/core/algorithm/frequency_estimation/src/frequency_estimation.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * 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 "frequency_estimation.h"
-
-#include
-#include
-#include
-
-#include "sensor_log.h"
-#include "sensors_errors.h"
-
-#undef LOG_TAG
-#define LOG_TAG "FrequencyEstimation"
-
-namespace OHOS {
-namespace Sensors {
-namespace {
-constexpr double BASE_SEMITONE { 69.0 };
-constexpr double PITCH_INTERVAL_MIN { 12.0 };
-constexpr double LA_FREQUENCE { 440.0 };
-constexpr double PITCH_INTERVAL_MAX { 108.0 };
-} // namespace
-
-double FrequencyEstimation::Mean(const std::vector &data)
-{
- if (data.empty()) {
- SEN_HILOGE("data is empty");
- return 0.0;
- }
- double sumValue = accumulate(data.begin(), data.end(), 0.0);
- return (sumValue / data.size());
-}
-
-void FrequencyEstimation::FreqPostProcess(const std::vector &frequencyHz, const std::vector &voiceSegmentFlag,
- const std::vector &rmseIntensityNorm, std::vector &freqNorm)
-{
- // Processing of effective values for filling in mute positions.
- std::vector hzTrims;
- int32_t ret = ProcessSilence(frequencyHz, voiceSegmentFlag, rmseIntensityNorm, hzTrims);
- if (ret != Sensors::SUCCESS) {
- SEN_HILOGE("ProcessSilence failed");
- return;
- }
- // Frequency conversion.
- std::vector pitch(hzTrims.size(), 0.0);
- for (size_t i = 0; i < hzTrims.size(); ++i) {
- pitch[i] = BASE_SEMITONE + (PITCH_INTERVAL_MIN * log2(hzTrims[i] / LA_FREQUENCE));
- }
- if (freqReaderAbsFlag_) {
- freqNorm = OHOS::Sensors::NormalizePercentageRange(pitch, PITCH_INTERVAL_MIN,
- (PITCH_INTERVAL_MIN + PITCH_INTERVAL_MAX));
- } else {
- freqNorm = OHOS::Sensors::NormalizePercentageMin(pitch);
- }
- if (!freqNorm.empty() && (freqNorm.size() + 1) == rmseIntensityNorm.size()) {
- freqNorm.push_back(freqNorm.back());
- }
-}
-
-std::vector FrequencyEstimation::GetZeroCrossingRate(const std::vector &data, int32_t frmLength, int32_t hopLength)
-{
- if (data.empty() || frmLength <= hopLength) {
- SEN_HILOGE("data is empty or frmLength is less than hopLength");
- return {};
- }
- size_t dataSize = data.size();
- size_t step = static_cast(frmLength - hopLength);
- size_t frameNum = ceil(dataSize / step);
- std::vector zcr(frameNum, 0.0);
- std::vector oneFrmData;
- auto it = data.begin();
- for (size_t i = 0; i < frameNum; ++i) {
- int32_t beginIndex = i * step;
- int32_t endIndex = std::min(beginIndex + frmLength, static_cast(dataSize));
- oneFrmData.assign(it + beginIndex, it + endIndex);
- double curFrameMean = Mean(oneFrmData);
- int32_t crossingN = 0;
- size_t curFrameSize = oneFrmData.size();
- if (curFrameSize == 0) {
- SEN_HILOGE("oneFrmData is empty");
- return {};
- }
- for (size_t j = 0; j < (curFrameSize - 1); ++j) {
- oneFrmData[j] = oneFrmData[j] - curFrameMean;
- if (IsLessOrEqual(oneFrmData[j] * oneFrmData[j + 1], 0.0)) {
- ++crossingN;
- }
- }
- zcr[i] = (static_cast(crossingN) / curFrameSize);
- }
- return zcr;
-}
-} // namespace Sensors
-} // namespace OHOS
\ No newline at end of file
diff --git a/vibration_convert/core/algorithm/onset/include/onset.h b/vibration_convert/core/algorithm/onset/include/onset.h
deleted file mode 100644
index 6d0d1aeed935859170a5dc4effff96b4abc76f04..0000000000000000000000000000000000000000
--- a/vibration_convert/core/algorithm/onset/include/onset.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 ONSET_H
-#define ONSET_H
-
-#include
-#include
-#include
-#include
-#include
-
-#include "peak_finder.h"
-
-namespace OHOS {
-namespace Sensors {
-struct OnsetInfo {
- /** If True, detected onset events are backtracked to the nearest. preceding minimum of energy.
- * This is primarily useful when using onsets as slice points for segmentation.
- */
- bool backTrackFlag { false };
- /** Compute a spectral flux onset strength envelope. */
- std::vector envelopes;
- std::vector idxs;
- std::vector times;
- void Clear() {
- backTrackFlag = false;
- envelopes.clear();
- idxs.clear();
- times.clear();
- }
-};
-
-class Onset {
-public:
- Onset() = default;
- ~Onset() = default;
-
- /**
- * @brief Locate note onset events by picking peaks in an onset strength envelope..
- *
- * @param data audio time-series.
- * @param nFft length of the windowed signal after padding with zeros. The number of rows in the STFT matrix D
- * is (1 + n_fft/2). The default value, n_fft=2048 samples.
- * @param hopLength If unspecified, defaults to win_length / 4.
- * @param onsets
- *
- * @return Returns 0 if the operation is successful; returns a negative value otherwise.
- */
- int32_t CheckOnset(const std::vector &data, int32_t nFft, int32_t hopLength, OnsetInfo &onsetInfo);
-
-private:
- int32_t Sfft(const std::vector &data, int32_t hopLength, int32_t &frmCount,
- std::vector &magnitudes, int32_t &numBins);
- int32_t GetMelBias(int32_t numBins, int32_t nFft, size_t &frmCount, std::vector &melBias);
- std::vector MatrixDot(size_t matrixAcols, const std::vector &matrixA,
- size_t matrixBcols, const std::vector &matrixB);
- std::vector MatrixDiff(size_t valueCols, const std::vector &values);
- std::vector PowerDB(const std::vector &values);
- std::optional Median(const std::vector &values);
- std::optional Mean(const std::vector &values);
-
-private:
- bool htkFlag_ { false };
- OnsetInfo onsetInfo_;
-};
-} // namespace Sensors
-} // namespace OHOS
-#endif // ONSET_H
\ No newline at end of file
diff --git a/vibration_convert/core/algorithm/onset/src/onset.cpp b/vibration_convert/core/algorithm/onset/src/onset.cpp
deleted file mode 100644
index 1602836359fedc31cf2f1e0e6897be52876d800a..0000000000000000000000000000000000000000
--- a/vibration_convert/core/algorithm/onset/src/onset.cpp
+++ /dev/null
@@ -1,265 +0,0 @@
-/*
- * 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 "onset.h"
-
-#include
-#include
-#include
-
-#include "conversion_fft.h"
-#include "conversion_mfcc.h"
-#include "sensor_log.h"
-#include "sensors_errors.h"
-#include "utils.h"
-
-#undef LOG_TAG
-#define LOG_TAG "Onset"
-
-namespace OHOS {
-namespace Sensors {
-namespace {
-// Effective threshold of note envelope
-constexpr double C_ONSET_ENV_VALIDE_THRESHOLD = 0.0001;
-constexpr double POWER_DB_COEF = 10.0;
-constexpr size_t N_MELS_OR_FILTERS = 128;
-/** 12 + 1 semitones*/
-constexpr uint32_t SEMITONE_NUM_COEFFS = 13;
-constexpr double ONSET_PEAK_THRESHOLD_RATIO = 0.4;
-constexpr double MIN_FREQ = 0.0;
-constexpr double MAX_FREQ = SAMPLE_RATE / 2.0;
-} // namespace
-
-std::vector Onset::MatrixDot(size_t matrixAcols, const std::vector &matrixA,
- size_t matrixBcols, const std::vector &matrixB)
-{
- if ((matrixAcols == 0) || (matrixBcols == 0)) {
- SEN_HILOGE("Invalid parameter");
- return {};
- }
- if ((matrixA.empty()) || (matrixB.empty())) {
- SEN_HILOGE("matrixA or matrixB is empty");
- return {};
- }
- size_t aRows = matrixA.size() / matrixAcols;
- size_t bRows = matrixB.size() / matrixBcols;
- std::vector result(aRows * matrixBcols);
- for (size_t i = 0; i < aRows; ++i) {
- for (size_t j = 0; j < matrixBcols; ++j) {
- // bRows must equal to matrixAcols.
- int32_t idx = j * aRows + i;
- double sum = 0.0;
- for (size_t k = 0; k < bRows; ++k) {
- // Multiply each column of the matrixB by each row of the matrixA, and then sum it up.
- sum += matrixA[k * aRows + i] * matrixB[j * bRows + k];
- }
- result[idx] = sum;
- }
- }
- return result;
-}
-
-std::vector Onset::MatrixDiff(size_t valueCols, const std::vector