Signed-off-by:xdurainbow<liudongmiao@huawei.com>

Signed-off-by: Mark <liudongmiao@huawei.com>
This commit is contained in:
Mark 2022-02-21 03:51:33 +00:00
parent 0c85a5173d
commit a945bca913
63 changed files with 5637 additions and 0 deletions

177
LICENSE Normal file
View File

@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

54
bundle.json Normal file
View File

@ -0,0 +1,54 @@
{
"name": "@ohos/device_status",
"description": "Msdp device status",
"version": "3.1",
"license": "Apache License 2.0",
"segment": {
"destPath": "base/msdp/device_status"
},
"component": {
"name": "device_status",
"subsystem": "msdp",
"syscap": ["SystemCapability.Msdp.DeviceStatus"],
"features": [],
"adapted_system_type": [ "standard" ],
"rom": "2048KB",
"ram": "~4096KB",
"deps": {
"components": [
"hiviewdfx_hilog_native",
"ipc",
"safwk",
"samgr_standard",
"utils_base",
"appexecfwk_standard",
"permission_standard",
"napi"
],
"third_party": []
},
"build": {
"sub_component": [
"//base/msdp/device_status/libs:devicestatus_sensorhdi",
"//base/msdp/device_status/libs:devicestatus_msdp",
"//base/msdp/device_status/interfaces/innerkits:devicestatus_client",
"//base/msdp/device_status/services:devicestatus_service",
"//base/msdp/device_status/frameworks/js/napi:devicestatus",
"//base/msdp/device_status/frameworks/native/src:deviceagent",
"//base/msdp/device_status/sa_profile:devicestatus_sa_profile"
],
"inner_kits": [
{
"name": "//base/msdp/device_status/interfaces/innerkits:devicestatus_client",
"header": {
"header_files": [],
"header_base": "//base/msdp/device_status/interfaces/innerkits/include"
}
}
],
"test": [
"//base/msdp/device_status/services/native/test:devicestatussrv_test"
]
}
}
}

21
device_status.gni Normal file
View File

@ -0,0 +1,21 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
device_status_part_name = "device_status"
device_status_root_path = "//base/msdp/device_status"
device_status_interfaces_path = "${device_status_root_path}/interfaces"
device_status_frameworks_path = "${device_status_root_path}/frameworks"
device_status_service_path = "${device_status_root_path}/services"
device_status_utils_path = "${device_status_root_path}/utils"

View File

@ -0,0 +1,58 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
import("//build/ohos/ace/ace.gni")
import("//base/msdp/device_status/device_status.gni")
config("devicestatusnapi_private_config") {
include_dirs = [
"include",
"//foundation/ace/napi/native_engine",
"//foundation/ace/napi/interfaces/kits",
"//utils/system/safwk/native/include",
"//third_party/node/src",
"${device_status_interfaces_path}/innerkits/include",
"${device_status_service_path}/native/include",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include",
]
}
ohos_shared_library("devicestatus") {
sources = [
"${device_status_frameworks_path}/js/napi/src/devicestatus_event.cpp",
"${device_status_frameworks_path}/js/napi/src/devicestatus_napi.cpp"
]
configs = [
"${device_status_utils_path}:devicestatus_utils_config",
":devicestatusnapi_private_config",
]
deps = [
"//base/msdp/device_status/interfaces/innerkits:devicestatus_client",
"//base/msdp/device_status/services:devicestatus_service",
"//foundation/ace/napi:ace_napi",
"//utils/native/base:utils"
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
relative_install_dir = "module"
subsystem_name = "msdp"
part_name = "${device_status_part_name}"
}

View File

@ -0,0 +1,56 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_EVENT_H
#define DEVICESTATUS_EVENT_H
#include <string>
#include <list>
#include <memory>
#include <map>
#include "napi/native_api.h"
namespace OHOS {
namespace Msdp {
struct DevicestatusEventListener {
int32_t eventType;
napi_ref handlerRef = nullptr;
};
class DevicestatusEvent {
public:
DevicestatusEvent(napi_env env, napi_value thisVar);
DevicestatusEvent() {};
virtual ~DevicestatusEvent();
virtual bool On(const int32_t& eventType, napi_value handler, bool isOnce);
virtual bool Off(const int32_t& eventType, bool isOnce);
virtual void OnEvent(const int32_t& eventType, size_t argc, const int32_t& value, bool isOnce);
protected:
napi_env env_;
napi_ref thisVarRef_;
std::map<int32_t, std::shared_ptr<DevicestatusEventListener>> eventMap_;
std::map<int32_t, std::shared_ptr<DevicestatusEventListener>> eventOnceMap_;
};
class JsResponse {
public:
int32_t devicestatusValue_ = -1;
};
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_EVENT_H

View File

@ -0,0 +1,68 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_NAPI_H
#define DEVICESTATUS_NAPI_H
#include <map>
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "devicestatus_callback_stub.h"
#include "devicestatus_data_utils.h"
#include "devicestatus_event.h"
namespace OHOS {
namespace Msdp {
class DevicestatusCallback : public DevicestatusCallbackStub {
public:
explicit DevicestatusCallback() {};
virtual ~DevicestatusCallback() {};
void OnDevicestatusChanged(const DevicestatusDataUtils::DevicestatusData& devicestatusData) override;
};
class DevicestatusNapi : public DevicestatusEvent {
public:
explicit DevicestatusNapi(napi_env env, napi_value thisVar);
virtual ~DevicestatusNapi();
static napi_value Init(napi_env env, napi_value exports);
static napi_value SubscribeDevicestatus(napi_env env, napi_callback_info info);
static napi_value UnSubscribeDevicestatus(napi_env env, napi_callback_info info);
static napi_value GetDevicestatus(napi_env env, napi_callback_info info);
static napi_value EnumDevicestatusTypeConstructor(napi_env env, napi_callback_info info);
static napi_value CreateEnumDevicestatusType(napi_env env, napi_value exports);
static napi_value EnumDevicestatusValueConstructor(napi_env env, napi_callback_info info);
static napi_value CreateDevicestatusValueType(napi_env env, napi_value exports);
static napi_value ResponseConstructor(napi_env env, napi_callback_info info);
static napi_status AddProperty(napi_env env, napi_value object, const std::string name, int32_t enumValue);
static napi_value CreateDevicestatusValueObject(napi_env env);
static napi_value CreateResponseClass(napi_env env, napi_value exports);
static napi_value CreateInstanceForResponse(napi_env env, int32_t value);
static void RegisterCallback(const int32_t& eventType);
static void InvokeCallBack(napi_env env, napi_value *args, bool voidParameter, int32_t value);
void OnDevicestatusChangedDone(const int32_t& type, const int32_t& value, bool isOnce);
static DevicestatusNapi* GetDevicestatusNapi(int32_t type);
static std::map<int32_t, sptr<IdevicestatusCallback>> callbackMap_;
static std::map<int32_t, DevicestatusNapi*> objectMap_;
private:
napi_ref callbackRef_;
static napi_ref devicestatusValueRef_;
napi_env env_;
};
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_NAPI_H

View File

@ -0,0 +1,163 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_event.h"
#include "devicestatus_common.h"
using namespace OHOS::Msdp;
DevicestatusEvent::DevicestatusEvent(napi_env env, napi_value thisVar)
{
env_ = env;
thisVarRef_ = nullptr;
napi_create_reference(env, thisVar, 1, &thisVarRef_);
}
DevicestatusEvent::~DevicestatusEvent()
{
for (auto iter = eventMap_.begin(); iter != eventMap_.end(); iter++) {
auto listener = iter->second;
napi_delete_reference(env_, listener->handlerRef);
}
eventMap_.clear();
napi_delete_reference(env_, thisVarRef_);
}
bool DevicestatusEvent::On(const int32_t& eventType, napi_value handler, bool isOnce)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, \
"DevicestatusEvent On in for event: %{public}d, isOnce: %{public}d", eventType, isOnce);
std::map<int32_t, std::shared_ptr<DevicestatusEventListener>>::iterator iter;
if (isOnce) {
iter = eventOnceMap_.find(eventType);
if (iter != eventOnceMap_.end()) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "eventType: %{public}d already exists", eventType);
return false;
}
} else {
iter = eventMap_.find(eventType);
if (iter != eventMap_.end()) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "eventType: %{public}d already exists", eventType);
return false;
}
}
auto listener = std::make_shared<DevicestatusEventListener>();
listener->eventType = eventType;
napi_create_reference(env_, handler, 1, &listener->handlerRef);
if (isOnce) {
eventOnceMap_[eventType] = listener;
} else {
eventMap_[eventType] = listener;
}
return true;
}
bool DevicestatusEvent::Off(const int32_t& eventType, bool isOnce)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, \
"DevicestatusEvent off in for event: %{public}d, isOnce: %{public}d", eventType, isOnce);
napi_handle_scope scope = nullptr;
napi_open_handle_scope(env_, &scope);
if (scope == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "scope is nullptr");
return false;
}
std::map<int32_t, std::shared_ptr<DevicestatusEventListener>>::iterator iter;
if (isOnce) {
iter = eventOnceMap_.find(eventType);
if (iter == eventOnceMap_.end()) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "eventType %{public}d not find", eventType);
return false;
}
} else {
iter = eventMap_.find(eventType);
if (iter == eventMap_.end()) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "eventType %{public}d not find", eventType);
return false;
}
}
auto listener = iter->second;
napi_delete_reference(env_, listener->handlerRef);
if (isOnce) {
eventOnceMap_.erase(eventType);
} else {
eventMap_.erase(eventType);
}
napi_close_handle_scope(env_, scope);
return true;
}
void DevicestatusEvent::OnEvent(const int32_t& eventType, size_t argc, const int32_t& value, bool isOnce)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "OnEvent for %{public}d, isOnce: %{public}d", eventType, isOnce);
napi_handle_scope scope = nullptr;
napi_open_handle_scope(env_, &scope);
if (scope == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "scope is nullptr");
return;
}
std::map<int32_t, std::shared_ptr<DevicestatusEventListener>>::iterator iter;
if (isOnce) {
iter = eventOnceMap_.find(eventType);
if (iter == eventOnceMap_.end()) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "OnEvent: eventType %{public}d not find", eventType);
return;
}
} else {
iter = eventMap_.find(eventType);
if (iter == eventMap_.end()) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "OnEvent: eventType %{public}d not find", eventType);
return;
}
}
auto listener = iter->second;
napi_value thisVar = nullptr;
napi_status status = napi_get_reference_value(env_, thisVarRef_, &thisVar);
if (status != napi_ok) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, \
"OnEvent napi_get_reference_value thisVar for %{public}d failed, status=%{public}d", eventType, status);
return;
}
napi_value handler = nullptr;
status = napi_get_reference_value(env_, listener->handlerRef, &handler);
if (status != napi_ok) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, \
"OnEvent napi_get_reference_value handler for %{public}d failed, status=%{public}d", eventType, status);
return;
}
napi_value callResult = nullptr;
napi_value result;
napi_create_object(env_, &result);
JsResponse jsResponse;
jsResponse.devicestatusValue_ = value;
napi_value tmpValue;
napi_create_int32(env_, jsResponse.devicestatusValue_, &tmpValue);
napi_set_named_property(env_, result, "devicestatusValue", tmpValue);
status = napi_call_function(env_, thisVar, handler, argc, &result, &callResult);
if (status != napi_ok) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, \
"OnEvent: napi_call_function for %{public}d failed, status=%{public}d", eventType, status);
return;
}
napi_close_handle_scope(env_, scope);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
}

View File

@ -0,0 +1,571 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_napi.h"
#include "devicestatus_common.h"
#include "devicestatus_client.h"
using namespace OHOS::Msdp;
using namespace OHOS;
namespace {
auto &g_DevicestatusClient = DevicestatusClient::GetInstance();
static napi_ref g_responseConstructor;
static const uint8_t ARG_0 = 0;
static const uint8_t ARG_1 = 1;
static const uint8_t ARG_2 = 2;
static const int32_t CALLBACK_SUCCESS = 200;
static const int32_t ERROR_MESSAGE = -1;
static const std::vector<std::string> vecDevicestatusValue {
"VALUE_ENTER", "VALUE_EXIT"
};
}
std::map<int32_t, sptr<IdevicestatusCallback>> DevicestatusNapi::callbackMap_;
std::map<int32_t, DevicestatusNapi*> DevicestatusNapi::objectMap_;
napi_ref DevicestatusNapi::devicestatusValueRef_;
struct ResponseEntity {
DevicestatusDataUtils::DevicestatusValue value;
};
void DevicestatusCallback::OnDevicestatusChanged(const DevicestatusDataUtils::DevicestatusData& devicestatusData)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Callback enter");
DevicestatusNapi* devicestatusNapi = DevicestatusNapi::GetDevicestatusNapi(devicestatusData.type);
if (devicestatusNapi == nullptr) {
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "devicestatus is nullptr");
return;
}
devicestatusNapi->OnDevicestatusChangedDone(static_cast<int32_t> (devicestatusData.type),
static_cast<int32_t> (devicestatusData.value), false);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Callback exit");
}
DevicestatusNapi* DevicestatusNapi::GetDevicestatusNapi(int32_t type)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter, type = %{public}d", type);
DevicestatusNapi* obj = nullptr;
bool isExists = false;
for (auto it = objectMap_.begin(); it != objectMap_.end(); ++it) {
if (it->first == type) {
isExists = true;
obj = (DevicestatusNapi*)(it->second);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Found object");
break;
}
}
if (!isExists) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "Didn't find object");
}
return obj;
}
DevicestatusNapi::DevicestatusNapi(napi_env env, napi_value thisVar) : DevicestatusEvent(env, thisVar)
{
env_ = env;
callbackRef_ = nullptr;
devicestatusValueRef_ = nullptr;
}
DevicestatusNapi::~DevicestatusNapi()
{
if (callbackRef_ != nullptr) {
napi_delete_reference(env_, callbackRef_);
}
if (devicestatusValueRef_ != nullptr) {
napi_delete_reference(env_, devicestatusValueRef_);
}
}
napi_value DevicestatusNapi::CreateInstanceForResponse(napi_env env, int32_t value)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter");
napi_value cons = nullptr;
napi_value instance = nullptr;
napi_status callBackStatus;
ResponseEntity *entity = nullptr;
callBackStatus = napi_get_reference_value(env, g_responseConstructor, &cons);
if (callBackStatus != napi_ok) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "napi get reference value failed");
return nullptr;
}
callBackStatus = napi_new_instance(env, cons, 0, nullptr, &instance);
if (callBackStatus != napi_ok || instance == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "napi new reference failed");
return nullptr;
}
callBackStatus = napi_unwrap(env, instance, (void **)&entity);
if (callBackStatus != napi_ok || entity == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "%{public}s: cannot unwrap entity from instance", __func__);
return nullptr;
}
entity->value = DevicestatusDataUtils::DevicestatusValue(value);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
return instance;
}
void DevicestatusNapi::OnDevicestatusChangedDone(const int32_t& type, const int32_t& value, bool isOnce)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter, value = %{public}d", value);
OnEvent(type, ARG_1, value, isOnce);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
}
void DevicestatusNapi::InvokeCallBack(napi_env env, napi_value *args, bool voidParameter, int32_t value)
{
napi_value callback = nullptr;
napi_value indexObj = nullptr;
napi_create_object(env, &indexObj);
napi_value successIndex = nullptr;
if (!voidParameter) {
napi_create_int32(env, value, &successIndex);
}
napi_ref callbackSuccess = nullptr;
napi_value ret;
napi_set_named_property(env, indexObj, "devicestatusValue", successIndex);
napi_create_reference(env, args[ARG_1], 1, &callbackSuccess);
napi_get_reference_value(env, callbackSuccess, &callback);
napi_call_function(env, nullptr, callback, 1, &indexObj, &ret);
napi_delete_reference(env, callbackSuccess);
}
napi_value DevicestatusNapi::SubscribeDevicestatus(napi_env env, napi_callback_info info)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter");
napi_value result = nullptr;
size_t argc = ARG_2;
napi_value args[ARG_2] = {0};
napi_value jsthis;
void *data = nullptr;
napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data);
NAPI_ASSERT(env, (status == napi_ok) && (argc >= 0), "Bad parameters");
napi_valuetype valueType1 = napi_undefined;
napi_typeof(env, args[ARG_0], &valueType1);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "valueType1: %{public}d", valueType1);
NAPI_ASSERT(env, valueType1 == napi_number, "type mismatch for parameter 1");
napi_valuetype valueType2 = napi_undefined;
napi_typeof(env, args[ARG_1], &valueType2);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "valueType2: %{public}d", valueType2);
NAPI_ASSERT(env, valueType2 == napi_function, "type mismatch for parameter 2");
int32_t type;
status = napi_get_value_int32(env, args[ARG_0], &type);
if (status != napi_ok) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "Failed to get type");
return result;
}
if (type < 0 || type > DevicestatusDataUtils::DevicestatusType::TYPE_LID_OPEN) {
InvokeCallBack(env, args, false, ERROR_MESSAGE);
return result;
}
DevicestatusNapi* obj = nullptr;
bool isObjExists = false;
for (auto it = objectMap_.begin(); it != objectMap_.end(); ++it) {
if (it->first == type) {
isObjExists = true;
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "Object already exists");
return result;
}
}
if (!isObjExists) {
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Didn't find object, so created it");
obj = new DevicestatusNapi(env, jsthis);
napi_wrap(env, jsthis, reinterpret_cast<void *>(obj),
[](napi_env env, void *data, void *hint) {
(void)env;
(void)hint;
DevicestatusNapi *devicestatus = (DevicestatusNapi *)data;
delete devicestatus;
},
nullptr, &(obj->callbackRef_));
objectMap_.insert(std::pair<int32_t, DevicestatusNapi*>(type, obj));
}
if (!obj->On(type, args[ARG_1], false)) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "type: %{public}d already exists", type);
return result;
}
sptr<IdevicestatusCallback> callback;
bool isCallbackExists = false;
for (auto it = callbackMap_.begin(); it != callbackMap_.end(); ++it) {
if (it->first == type) {
isCallbackExists = true;
break;
}
}
if (!isCallbackExists) {
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Didn't find callback, so created it");
callback = new DevicestatusCallback();
g_DevicestatusClient.SubscribeCallback(DevicestatusDataUtils::DevicestatusType(type), callback);
callbackMap_.insert(std::pair<int32_t, sptr<IdevicestatusCallback>>(type, callback));
InvokeCallBack(env, args, false, CALLBACK_SUCCESS);
} else {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "Callback exists.");
return result;
}
napi_get_undefined(env, &result);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
return result;
}
napi_value DevicestatusNapi::UnSubscribeDevicestatus(napi_env env, napi_callback_info info)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter");
napi_value result = nullptr;
size_t argc = ARG_2;
napi_value args[ARG_2] = { 0 };
napi_value jsthis;
void *data = nullptr;
napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data);
NAPI_ASSERT(env, (status == napi_ok) && (argc >= 0), "Bad parameters");
napi_valuetype valueType1 = napi_undefined;
napi_typeof(env, args[ARG_0], &valueType1);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "valueType1: %{public}d", valueType1);
NAPI_ASSERT(env, valueType1 == napi_number, "type mismatch for parameter 1");
int32_t type;
status = napi_get_value_int32(env, args[ARG_0], &type);
if (status != napi_ok) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "Failed to get type");
return result;
}
if (type < 0 || type > DevicestatusDataUtils::DevicestatusType::TYPE_LID_OPEN) {
InvokeCallBack(env, args, true, ERROR_MESSAGE);
return result;
}
DevicestatusNapi* obj = nullptr;
bool isObjExists = false;
for (auto it = objectMap_.begin(); it != objectMap_.end(); ++it) {
if (it->first == type) {
isObjExists = true;
obj = (DevicestatusNapi*)(it->second);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Found object");
}
}
if (!isObjExists) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "Didn't find object, so created it");
return result;
}
if (!obj->Off(type, false)) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "Failed to get callback for type: %{public}d", type);
return result;
} else {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "erase objectMap_");
InvokeCallBack(env, args, true, CALLBACK_SUCCESS);
objectMap_.erase(type);
}
sptr<IdevicestatusCallback> callback;
bool isCallbackExists = false;
for (auto it = callbackMap_.begin(); it != callbackMap_.end(); ++it) {
if (it->first == type) {
isCallbackExists = true;
callback = (sptr<IdevicestatusCallback>)(it->second);
break;
}
}
if (!isCallbackExists) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "No existed callback");
return result;
} else if (callback != nullptr) {
g_DevicestatusClient.UnSubscribeCallback(DevicestatusDataUtils::DevicestatusType(type), callback);
callbackMap_.erase(type);
}
napi_get_undefined(env, &result);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
return result;
}
napi_value DevicestatusNapi::GetDevicestatus(napi_env env, napi_callback_info info)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter");
napi_value result = nullptr;
size_t argc = ARG_2;
napi_value args[ARG_2] = {0};
napi_value jsthis;
void *data = nullptr;
napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data);
NAPI_ASSERT(env, (status == napi_ok) && (argc >= 0), "Bad parameters");
napi_valuetype valueType1 = napi_undefined;
napi_typeof(env, args[ARG_0], &valueType1);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "valueType1: %{public}d", valueType1);
NAPI_ASSERT(env, valueType1 == napi_number, "type mismatch for parameter 1");
napi_valuetype valueType2 = napi_undefined;
napi_typeof(env, args[ARG_1], &valueType2);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "valueType2: %{public}d", valueType2);
NAPI_ASSERT(env, valueType2 == napi_function, "type mismatch for parameter 2");
int32_t type;
status = napi_get_value_int32(env, args[ARG_0], &type);
if (status != napi_ok) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "Failed to get type");
return result;
}
DevicestatusNapi* obj = new DevicestatusNapi(env, jsthis);
napi_wrap(env, jsthis, reinterpret_cast<void *>(obj),
[](napi_env env, void *data, void *hint) {
(void)env;
(void)hint;
DevicestatusNapi *devicestatus = (DevicestatusNapi *)data;
delete devicestatus;
},
nullptr, &(obj->callbackRef_));
if (!obj->On(type, args[ARG_1], true)) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "type: %{public}d already exists", type);
return result;
}
DevicestatusDataUtils::DevicestatusData devicestatusData = \
g_DevicestatusClient.GetDevicestatusData(DevicestatusDataUtils::DevicestatusType(type));
obj->OnDevicestatusChangedDone(devicestatusData.type, devicestatusData.value, true);
obj->Off(devicestatusData.type, true);
napi_get_undefined(env, &result);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
return result;
}
napi_value DevicestatusNapi::EnumDevicestatusTypeConstructor(napi_env env, napi_callback_info info)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter");
napi_value thisArg = nullptr;
void *data = nullptr;
napi_get_cb_info(env, info, nullptr, nullptr, &thisArg, &data);
napi_value global = nullptr;
napi_get_global(env, &global);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
return thisArg;
}
napi_value DevicestatusNapi::CreateEnumDevicestatusType(napi_env env, napi_value exports)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter");
napi_value highStill = nullptr;
napi_value fineStill = nullptr;
napi_value carBluetooth = nullptr;
napi_create_int32(env, (int32_t)DevicestatusDataUtils::DevicestatusType::TYPE_HIGH_STILL, &highStill);
napi_create_int32(env, (int32_t)DevicestatusDataUtils::DevicestatusType::TYPE_FINE_STILL, &fineStill);
napi_create_int32(env, (int32_t)DevicestatusDataUtils::DevicestatusType::TYPE_CAR_BLUETOOTH, &carBluetooth);
napi_property_descriptor desc[] = {
DECLARE_NAPI_STATIC_PROPERTY("TYPE_HIGH_STILL", highStill),
DECLARE_NAPI_STATIC_PROPERTY("TYPE_FINE_STILL", fineStill),
DECLARE_NAPI_STATIC_PROPERTY("TYPE_CAR_BLUETOOTH", carBluetooth),
};
napi_value result = nullptr;
napi_define_class(env, "DevicestatusType", NAPI_AUTO_LENGTH, EnumDevicestatusTypeConstructor, nullptr,
sizeof(desc) / sizeof(*desc), desc, &result);
napi_set_named_property(env, exports, "DevicestatusType", result);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
return exports;
}
napi_value DevicestatusNapi::EnumDevicestatusValueConstructor(napi_env env, napi_callback_info info)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter");
napi_value thisArg = nullptr;
void *data = nullptr;
napi_get_cb_info(env, info, nullptr, nullptr, &thisArg, &data);
napi_value global = nullptr;
napi_get_global(env, &global);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
return thisArg;
}
napi_value DevicestatusNapi::CreateDevicestatusValueType(napi_env env, napi_value exports)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter");
napi_value enter = nullptr;
napi_value exit = nullptr;
napi_create_int32(env, (int32_t)DevicestatusDataUtils::DevicestatusValue::VALUE_ENTER, &enter);
napi_create_int32(env, (int32_t)DevicestatusDataUtils::DevicestatusValue::VALUE_EXIT, &exit);
napi_property_descriptor desc[] = {
DECLARE_NAPI_STATIC_PROPERTY("VALUE_ENTER", enter),
DECLARE_NAPI_STATIC_PROPERTY("VALUE_EXIT", exit),
};
napi_value result = nullptr;
napi_define_class(env, "DevicestatusValue", NAPI_AUTO_LENGTH, EnumDevicestatusValueConstructor, nullptr,
sizeof(desc) / sizeof(*desc), desc, &result);
napi_set_named_property(env, exports, "DevicestatusValue", result);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
return exports;
}
napi_value DevicestatusNapi::ResponseConstructor(napi_env env, napi_callback_info info)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter");
napi_value thisVar = nullptr;
void *data = nullptr;
napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, &data);
auto entity = new ResponseEntity();
napi_wrap(
env, thisVar, entity,
[](napi_env env, void *data, void *hint) {
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Destructor");
auto entity = (ResponseEntity*)data;
delete entity;
},
nullptr, nullptr);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
return thisVar;
}
napi_status DevicestatusNapi::AddProperty(napi_env env, napi_value object, const std::string name, int32_t enumValue)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter");
napi_status status;
napi_value enumNapiValue;
status = napi_create_int32(env, enumValue, &enumNapiValue);
if (status == napi_ok) {
status = napi_set_named_property(env, object, name.c_str(), enumNapiValue);
}
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
return status;
}
napi_value DevicestatusNapi::CreateDevicestatusValueObject(napi_env env)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter");
napi_value result = nullptr;
napi_status status;
std::string propName;
status = napi_create_object(env, &result);
if (status == napi_ok) {
for (unsigned int i = DevicestatusDataUtils::DevicestatusValue::VALUE_ENTER; \
i < vecDevicestatusValue.size(); i++) {
propName = vecDevicestatusValue[i];
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "propName: %{public}s", propName.c_str());
status = AddProperty(env, result, propName, i);
if (status != napi_ok) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "Failed to add named prop!");
break;
}
propName.clear();
}
}
if (status == napi_ok) {
// The reference count is for creation of devicestatus value Object Reference
status = napi_create_reference(env, result, 1, &devicestatusValueRef_);
if (status == napi_ok) {
return result;
}
}
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_JS_NAPI, "CreateDevicestatusValueObject is Failed!");
napi_get_undefined(env, &result);
return result;
}
napi_value DevicestatusNapi::CreateResponseClass(napi_env env, napi_value exports)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter");
napi_property_descriptor desc[] = {
DECLARE_NAPI_PROPERTY("devicestatusValue", CreateDevicestatusValueObject(env)),
};
napi_value result = nullptr;
napi_define_class(env, "Response", NAPI_AUTO_LENGTH, ResponseConstructor, nullptr,
sizeof(desc) / sizeof(*desc), desc, &result);
napi_create_reference(env, result, 1, &g_responseConstructor);
napi_set_named_property(env, exports, "Response", result);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
return exports;
}
napi_value DevicestatusNapi::Init(napi_env env, napi_value exports)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter");
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("on", SubscribeDevicestatus),
DECLARE_NAPI_FUNCTION("off", UnSubscribeDevicestatus),
DECLARE_NAPI_FUNCTION("once", GetDevicestatus),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
CreateEnumDevicestatusType(env, exports);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
return exports;
}
EXTERN_C_START
/*
* function for module exports
*/
static napi_value DevicestatusInit(napi_env env, napi_value exports)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Enter");
napi_value ret = DevicestatusNapi::Init(env, exports);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_JS_NAPI, "Exit");
return ret;
}
EXTERN_C_END
/*
* Module definition
*/
static napi_module g_module = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = "devicestatus",
.nm_register_func = DevicestatusInit,
.nm_modname = "devicestatus",
.nm_priv = ((void *)0),
.reserved = {0}
};
/*
* Module registration
*/
extern "C" __attribute__((constructor)) void RegisterModule(void)
{
napi_module_register(&g_module);
}

View File

@ -0,0 +1,51 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
import("//build/ohos/ace/ace.gni")
import("//base/msdp/device_status/device_status.gni")
config("devicestatusnapi_private_config") {
include_dirs = [
"include",
"${device_status_interfaces_path}/innerkits/include",
"${device_status_service_path}/native/include",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include",
]
}
ohos_shared_library("deviceagent") {
sources = [
"./devicestatus_agent.cpp",
]
configs = [
"${device_status_utils_path}:devicestatus_utils_config",
":devicestatusnapi_private_config",
]
deps = [
"//base/msdp/device_status/interfaces/innerkits:devicestatus_client",
"//base/msdp/device_status/services:devicestatus_service",
"//utils/native/base:utils"
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
subsystem_name = "msdp"
part_name = "${device_status_part_name}"
}

View File

@ -0,0 +1,64 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_agent.h"
#include "devicestatus_common.h"
#include "devicestatus_client.h"
namespace OHOS {
namespace Msdp {
void DeviceStatusAgent::DeviceStatusAgentCallback::OnDevicestatusChanged(
const DevicestatusDataUtils::DevicestatusData& devicestatusData)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_INNERKIT, "type = %{punlic}d, value=%{public}d",
static_cast<DevicestatusDataUtils::DevicestatusType>(devicestatusData.type),
static_cast<DevicestatusDataUtils::DevicestatusValue>(devicestatusData.value));
std::shared_ptr<DeviceStatusAgent> agent = agent_.lock();
agent->agentEvent_->OnEventResult(devicestatusData);
}
int32_t DeviceStatusAgent::SubscribeAgentEvent(const DevicestatusDataUtils::DevicestatusType& type,
const std::shared_ptr<DeviceStatusAgent::DeviceStatusAgentEvent>& agentEvent)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_INNERKIT, "%{public}s enter", __func__);
RegisterServiceEvent(type);
if (agentEvent == nullptr) {
return ERR_INVALID_VALUE;
}
agentEvent_ = agentEvent;
return ERR_OK;
}
int32_t DeviceStatusAgent::UnSubscribeAgentEvent(const DevicestatusDataUtils::DevicestatusType& type)
{
UnRegisterServiceEvent(type);
return ERR_OK;
}
void DeviceStatusAgent::RegisterServiceEvent(const DevicestatusDataUtils::DevicestatusType& type)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_INNERKIT, "%{public}s enter", __func__);
callback_ = new DeviceStatusAgentCallback(shared_from_this());
DevicestatusClient::GetInstance().SubscribeCallback(type, callback_);
}
void DeviceStatusAgent::UnRegisterServiceEvent(const DevicestatusDataUtils::DevicestatusType& type)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_INNERKIT, "%{public}s enter", __func__);
DevicestatusClient::GetInstance().UnSubscribeCallback(type, callback_);
}
} // namespace Msdp
} // namespace OHOS

View File

@ -0,0 +1,48 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_callback_proxy.h"
#include <ipc_types.h>
#include <message_parcel.h>
#include "devicestatus_common.h"
namespace OHOS {
namespace Msdp {
void DevicestatusCallbackProxy::OnDevicestatusChanged(const DevicestatusDataUtils::DevicestatusData& devicestatusData)
{
sptr<IRemoteObject> remote = Remote();
DEVICESTATUS_RETURN_IF(remote == nullptr);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(DevicestatusCallbackProxy::GetDescriptor())) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_INNERKIT, "Write descriptor failed");
return;
}
DEVICESTATUS_WRITE_PARCEL_NO_RET(data, Int32, static_cast<int32_t>(devicestatusData.type));
DEVICESTATUS_WRITE_PARCEL_NO_RET(data, Int32, static_cast<int32_t>(devicestatusData.value));
int ret = remote->SendRequest(static_cast<int>(IdevicestatusCallback::DEVICESTATUS_CHANGE), data, reply, option);
if (ret != ERR_OK) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_INNERKIT, "SendRequest is failed, error code: %{public}d", ret);
}
}
} // Msdp
} // OHOS

View File

@ -0,0 +1,126 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_client.h"
#include <iservice_registry.h>
#include <if_system_ability_manager.h>
#include <ipc_skeleton.h>
#include <system_ability_definition.h>
namespace OHOS {
namespace Msdp {
DevicestatusClient::DevicestatusClient() {}
DevicestatusClient::~DevicestatusClient()
{
if (devicestatusProxy_ != nullptr) {
auto remoteObject = devicestatusProxy_->AsObject();
if (remoteObject != nullptr) {
remoteObject->RemoveDeathRecipient(deathRecipient_);
}
}
}
ErrCode DevicestatusClient::Connect()
{
std::lock_guard<std::mutex> lock(mutex_);
if (devicestatusProxy_ != nullptr) {
return ERR_OK;
}
sptr<ISystemAbilityManager> sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sam == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_INNERKIT, "GetSystemAbilityManager failed");
return E_DEVICESTATUS_GET_SYSTEM_ABILITY_MANAGER_FAILED;
}
sptr<IRemoteObject> remoteObject_ = sam->CheckSystemAbility(MSDP_DEVICESTATUS_SERVICE_ID);
if (remoteObject_ == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_INNERKIT, "CheckSystemAbility failed");
return E_DEVICESTATUS_GET_SERVICE_FAILED;
}
deathRecipient_ = sptr<IRemoteObject::DeathRecipient>(new DevicestatusDeathRecipient());
if (deathRecipient_ == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_INNERKIT, "Failed to create DevicestatusDeathRecipient");
return ERR_NO_MEMORY;
}
if ((remoteObject_->IsProxyObject()) && (!remoteObject_->AddDeathRecipient(deathRecipient_))) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_INNERKIT, "Add death recipient to Devicestatus service failed");
return E_DEVICESTATUS_ADD_DEATH_RECIPIENT_FAILED;
}
devicestatusProxy_ = iface_cast<Idevicestatus>(remoteObject_);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "Connecting DevicestatusService success");
return ERR_OK;
}
void DevicestatusClient::ResetProxy(const wptr<IRemoteObject>& remote)
{
std::lock_guard<std::mutex> lock(mutex_);
DEVICESTATUS_RETURN_IF(devicestatusProxy_ == nullptr);
auto serviceRemote = devicestatusProxy_->AsObject();
if ((serviceRemote != nullptr) && (serviceRemote == remote.promote())) {
serviceRemote->RemoveDeathRecipient(deathRecipient_);
devicestatusProxy_ = nullptr;
}
}
void DevicestatusClient::DevicestatusDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
{
if (remote == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_INNERKIT, "OnRemoteDied failed, remote is nullptr");
return;
}
DevicestatusClient::GetInstance().ResetProxy(remote);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "Recv death notice");
}
void DevicestatusClient::SubscribeCallback(const DevicestatusDataUtils::DevicestatusType& type, \
const sptr<IdevicestatusCallback>& callback)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "Enter");
DEVICESTATUS_RETURN_IF((callback == nullptr) || (Connect() != ERR_OK));
devicestatusProxy_->Subscribe(type, callback);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "Exit");
}
void DevicestatusClient::UnSubscribeCallback(const DevicestatusDataUtils::DevicestatusType& type, \
const sptr<IdevicestatusCallback>& callback)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "Enter");
DEVICESTATUS_RETURN_IF((callback == nullptr) || (Connect() != ERR_OK));
devicestatusProxy_->UnSubscribe(type, callback);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "Exit");
}
DevicestatusDataUtils::DevicestatusData DevicestatusClient::GetDevicestatusData(const \
DevicestatusDataUtils::DevicestatusType& type)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "Enter");
DevicestatusDataUtils::DevicestatusData devicestatusData;
devicestatusData.type = DevicestatusDataUtils::DevicestatusType::TYPE_INVALID;
devicestatusData.value = DevicestatusDataUtils::DevicestatusValue::VALUE_INVALID;
DEVICESTATUS_RETURN_IF_WITH_RET((Connect() != ERR_OK), devicestatusData);
devicestatusData = devicestatusProxy_->GetCache(type);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "Exit");
return devicestatusData;
}
} // namespace Msdp
} // namespace OHOS

View File

@ -0,0 +1,121 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_srv_proxy.h"
#include <ipc_types.h>
#include <message_parcel.h>
#include <message_option.h>
#include "idevicestatus_callback.h"
#include "devicestatus_common.h"
namespace OHOS {
namespace Msdp {
void DevicestatusSrvProxy::Subscribe(const DevicestatusDataUtils::DevicestatusType& type, \
const sptr<IdevicestatusCallback>& callback)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "Enter");
sptr<IRemoteObject> remote = Remote();
DEVICESTATUS_RETURN_IF((remote == nullptr) || (callback == nullptr));
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(DevicestatusSrvProxy::GetDescriptor())) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_INNERKIT, "Write descriptor failed");
return;
}
DEVICESTATUS_WRITE_PARCEL_NO_RET(data, Int32, type);
DEVICESTATUS_WRITE_PARCEL_NO_RET(data, RemoteObject, callback->AsObject());
int ret = remote->SendRequest(static_cast<int>(Idevicestatus::DEVICESTATUS_SUBSCRIBE), data, reply, option);
if (ret != ERR_OK) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_INNERKIT, "SendRequest is failed, error code: %{public}d", ret);
return;
}
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "Exit");
}
void DevicestatusSrvProxy::UnSubscribe(const DevicestatusDataUtils::DevicestatusType& type,
const sptr<IdevicestatusCallback>& callback)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "Enter");
sptr<IRemoteObject> remote = Remote();
DEVICESTATUS_RETURN_IF((remote == nullptr) || (callback == nullptr));
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(DevicestatusSrvProxy::GetDescriptor())) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_INNERKIT, "Write descriptor failed!");
return;
}
DEVICESTATUS_WRITE_PARCEL_NO_RET(data, Int32, type);
DEVICESTATUS_WRITE_PARCEL_NO_RET(data, RemoteObject, callback->AsObject());
int ret = remote->SendRequest(static_cast<int>(Idevicestatus::DEVICESTATUS_UNSUBSCRIBE), data, reply, option);
if (ret != ERR_OK) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_INNERKIT, "SendRequest is failed, error code: %{public}d", ret);
return;
}
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "Exit");
}
DevicestatusDataUtils::DevicestatusData DevicestatusSrvProxy::GetCache(const \
DevicestatusDataUtils::DevicestatusType& type)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "Enter");
DevicestatusDataUtils::DevicestatusData devicestatusData;
devicestatusData.type = DevicestatusDataUtils::DevicestatusType::TYPE_INVALID;
devicestatusData.value = DevicestatusDataUtils::DevicestatusValue::VALUE_INVALID;
sptr<IRemoteObject> remote = Remote();
DEVICESTATUS_RETURN_IF_WITH_RET((remote == nullptr), devicestatusData);
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(DevicestatusSrvProxy::GetDescriptor())) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_INNERKIT, "Write descriptor failed!");
return devicestatusData;
}
DEVICESTATUS_WRITE_PARCEL_WITH_RET(data, Int32, type, devicestatusData);
int ret = remote->SendRequest(static_cast<int>(Idevicestatus::DEVICESTATUS_GETCACHE), data, reply, option);
if (ret != ERR_OK) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_INNERKIT, "SendRequest is failed, error code: %{public}d", ret);
return devicestatusData;
}
int32_t devicestatusType = -1;
int32_t devicestatusValue = -1;
DEVICESTATUS_READ_PARCEL_WITH_RET(reply, Int32, devicestatusType, devicestatusData);
DEVICESTATUS_READ_PARCEL_WITH_RET(reply, Int32, devicestatusValue, devicestatusData);
devicestatusData.type = DevicestatusDataUtils::DevicestatusType(devicestatusType);
devicestatusData.value = DevicestatusDataUtils::DevicestatusValue(devicestatusValue);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "type: %{public}d", devicestatusData.type);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "value: %{public}d", devicestatusData.value);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_INNERKIT, "Exit");
return devicestatusData;
}
} // Msdp
} // OHOS

View File

@ -0,0 +1,54 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//base/msdp/device_status/device_status.gni")
config("devicestatus_private_config") {
include_dirs = [ "//utils/system/safwk/native/include" ]
}
config("devicestatus_public_config") {
include_dirs = [
"include",
"${device_status_service_path}/native/include",
]
}
ohos_shared_library("devicestatus_client") {
sources = [
"${device_status_frameworks_path}/native/src/devicestatus_callback_proxy.cpp",
"${device_status_frameworks_path}/native/src/devicestatus_client.cpp",
"${device_status_frameworks_path}/native/src/devicestatus_srv_proxy.cpp",
]
configs = [
"${device_status_utils_path}:devicestatus_utils_config",
":devicestatus_private_config",
":devicestatus_public_config",
]
public_configs = [ ":devicestatus_public_config" ]
deps = [
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_standard:samgr_proxy",
]
part_name = "${device_status_part_name}"
}

View File

@ -0,0 +1,57 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_MSDP_DEVICESTATUS_AGENT_H
#define OHOS_MSDP_DEVICESTATUS_AGENT_H
#include <memory>
#include "devicestatus_callback_stub.h"
#include "devicestatus_data_utils.h"
namespace OHOS {
namespace Msdp {
class DeviceStatusAgent : public std::enable_shared_from_this<DeviceStatusAgent> {
public:
DeviceStatusAgent() {};
~DeviceStatusAgent() {};
class DeviceStatusAgentEvent {
public:
virtual ~DeviceStatusAgentEvent() = default;
virtual bool OnEventResult(const DevicestatusDataUtils::DevicestatusData& devicestatusData) = 0;
};
class DeviceStatusAgentCallback : public DevicestatusCallbackStub {
public:
explicit DeviceStatusAgentCallback(std::shared_ptr<DeviceStatusAgent> agent) : agent_(agent) {};
virtual ~DeviceStatusAgentCallback() {};
void OnDevicestatusChanged(const DevicestatusDataUtils::DevicestatusData& devicestatusData) override;
private:
std::weak_ptr<DeviceStatusAgent> agent_;
};
int32_t SubscribeAgentEvent(const DevicestatusDataUtils::DevicestatusType& type,
const std::shared_ptr<DeviceStatusAgent::DeviceStatusAgentEvent>& agentEvent);
int32_t UnSubscribeAgentEvent(const DevicestatusDataUtils::DevicestatusType& type);
friend class DeviceStatusAgentCallback;
private:
void RegisterServiceEvent(const DevicestatusDataUtils::DevicestatusType& type);
void UnRegisterServiceEvent(const DevicestatusDataUtils::DevicestatusType& type);
sptr<IdevicestatusCallback> callback_;
std::shared_ptr<DeviceStatusAgentEvent> agentEvent_;
};
} // namespace Msdp
} // namespace OHOS
#endif // OHOS_MSDP_DEVICESTATUS_AGENT_H

View File

@ -0,0 +1,40 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_CALLBACK_PROXY_H
#define DEVICESTATUS_CALLBACK_PROXY_H
#include <iremote_proxy.h>
#include <nocopyable.h>
#include "idevicestatus_callback.h"
#include "devicestatus_data_utils.h"
namespace OHOS {
namespace Msdp {
class DevicestatusCallbackProxy : public IRemoteProxy<IdevicestatusCallback> {
public:
explicit DevicestatusCallbackProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<IdevicestatusCallback>(impl) {}
~DevicestatusCallbackProxy() = default;
DISALLOW_COPY_AND_MOVE(DevicestatusCallbackProxy);
virtual void OnDevicestatusChanged(const DevicestatusDataUtils::DevicestatusData& devicestatusData) override;
private:
static inline BrokerDelegator<DevicestatusCallbackProxy> delegator_;
};
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_CALLBACK_PROXY_H

View File

@ -0,0 +1,57 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_CLIENT_H
#define DEVICESTATUS_CLIENT_H
#include <singleton.h>
#include "idevicestatus.h"
#include "idevicestatus_callback.h"
#include "devicestatus_data_utils.h"
#include "devicestatus_common.h"
namespace OHOS {
namespace Msdp {
class DevicestatusClient final : public DelayedRefSingleton<DevicestatusClient> {
DECLARE_DELAYED_REF_SINGLETON(DevicestatusClient)
public:
DISALLOW_COPY_AND_MOVE(DevicestatusClient);
void SubscribeCallback(const DevicestatusDataUtils::DevicestatusType& type, \
const sptr<IdevicestatusCallback>& callback);
void UnSubscribeCallback(const DevicestatusDataUtils::DevicestatusType& type, \
const sptr<IdevicestatusCallback>& callback);
DevicestatusDataUtils::DevicestatusData GetDevicestatusData(const DevicestatusDataUtils::DevicestatusType& type);
private:
class DevicestatusDeathRecipient : public IRemoteObject::DeathRecipient {
public:
DevicestatusDeathRecipient() = default;
~DevicestatusDeathRecipient() = default;
void OnRemoteDied(const wptr<IRemoteObject>& remote);
private:
DISALLOW_COPY_AND_MOVE(DevicestatusDeathRecipient);
};
ErrCode Connect();
sptr<Idevicestatus> devicestatusProxy_ {nullptr};
sptr<IRemoteObject::DeathRecipient> deathRecipient_ {nullptr};
void ResetProxy(const wptr<IRemoteObject>& remote);
std::mutex mutex_;
};
} // namespace Msdp
} // namespace OHOS
#endif // IDEVICESTATUS_H

View File

@ -0,0 +1,44 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_DATA_UTILS_H
#define DEVICESTATUS_DATA_UTILS_H
namespace OHOS {
namespace Msdp {
class DevicestatusDataUtils {
public:
enum DevicestatusType {
TYPE_INVALID = -1,
TYPE_HIGH_STILL,
TYPE_FINE_STILL,
TYPE_CAR_BLUETOOTH,
TYPE_LID_OPEN
};
enum DevicestatusValue {
VALUE_INVALID = -1,
VALUE_ENTER,
VALUE_EXIT
};
struct DevicestatusData {
DevicestatusType type;
DevicestatusValue value;
};
};
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_DATA_UTILS_H

View File

@ -0,0 +1,45 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_SRV_PROXY_H
#define DEVICESTATUS_SRV_PROXY_H
#include <nocopyable.h>
#include "iremote_proxy.h"
#include "idevicestatus.h"
namespace OHOS {
namespace Msdp {
class DevicestatusSrvProxy : public IRemoteProxy<Idevicestatus> {
public:
explicit DevicestatusSrvProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<Idevicestatus>(impl) {}
~DevicestatusSrvProxy() = default;
DISALLOW_COPY_AND_MOVE(DevicestatusSrvProxy);
virtual void Subscribe(const DevicestatusDataUtils::DevicestatusType& type, \
const sptr<IdevicestatusCallback>& callback) override;
virtual void UnSubscribe(const DevicestatusDataUtils::DevicestatusType& type, \
const sptr<IdevicestatusCallback>& callback) override;
virtual DevicestatusDataUtils::DevicestatusData GetCache(const \
DevicestatusDataUtils::DevicestatusType& type) override;
private:
static inline BrokerDelegator<DevicestatusSrvProxy> delegator_;
};
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_SRV_PROXY_H

View File

@ -0,0 +1,44 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef IDEVICESTATUS_H
#define IDEVICESTATUS_H
#include <iremote_broker.h>
#include "iremote_object.h"
#include "idevicestatus_callback.h"
#include "devicestatus_data_utils.h"
namespace OHOS {
namespace Msdp {
class Idevicestatus : public IRemoteBroker {
public:
enum {
DEVICESTATUS_SUBSCRIBE = 0,
DEVICESTATUS_UNSUBSCRIBE,
DEVICESTATUS_GETCACHE
};
virtual void Subscribe(const DevicestatusDataUtils::DevicestatusType& type, \
const sptr<IdevicestatusCallback>& callback) = 0;
virtual void UnSubscribe(const DevicestatusDataUtils::DevicestatusType& type, \
const sptr<IdevicestatusCallback>& callback) = 0;
virtual DevicestatusDataUtils::DevicestatusData GetCache(const DevicestatusDataUtils::DevicestatusType& type) = 0;
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.msdp.Idevicestatus");
};
} // namespace Msdp
} // namespace OHOS
#endif // IDEVICESTATUS_H

View File

@ -0,0 +1,35 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef IDEVICESTATUS_ALGORITHM_H
#define IDEVICESTATUS_ALGORITHM_H
#include <iremote_broker.h>
#include "idevicestatus_algorithm_callback.h"
namespace OHOS {
namespace Msdp {
class IdevicestatusAlgorithm : public IRemoteBroker {
public:
virtual bool Enable() = 0;
virtual bool Disable() = 0;
virtual bool Subscribe(const sptr<IdevicestatusAlgorithmCallback>& callback) = 0;
virtual bool UnSubscribe(const sptr<IdevicestatusAlgorithmCallback>& callback) = 0;
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.msdp.IdevicestatusAlgorithm");
};
} // namespace Msdp
} // namespace OHOS
#endif // IDEVICESTATUS_ALGORITHM_H

View File

@ -0,0 +1,33 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef IDEVICESTATUS_ALGORITHM_CALLBACK_H
#define IDEVICESTATUS_ALGORITHM_CALLBACK_H
#include <iremote_broker.h>
#include "devicestatus_data_utils.h"
namespace OHOS {
namespace Msdp {
class IdevicestatusAlgorithmCallback : public IRemoteBroker {
public:
virtual void OnDevicestatusChanged(const DevicestatusDataUtils::DevicestatusData& data) = 0;
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.msdp.IdevicestatusAlgorithmCallback");
};
} // namespace Msdp
} // namespace OHOS
#endif // IDEVICESTATUS_ALGORITHM_CALLBACK_H

View File

@ -0,0 +1,38 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef IDEVICESTATUS_CALLBACK_H
#define IDEVICESTATUS_CALLBACK_H
#include <iremote_broker.h>
#include <iremote_object.h>
#include "devicestatus_data_utils.h"
namespace OHOS {
namespace Msdp {
class IdevicestatusCallback : public IRemoteBroker {
public:
enum {
DEVICESTATUS_CHANGE = 0,
};
virtual void OnDevicestatusChanged(const DevicestatusDataUtils::DevicestatusData& devicestatusData) = 0;
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.msdp.IdevicestatusCallback");
};
} // namespace Msdp
} // namespace OHOS
#endif // IDEVICESTATUS_CALLBACK_H

View File

@ -0,0 +1,40 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef IDEVICESTATUS_STORAGE_H
#define IDEVICESTATUS_STORAGE_H
#include <iremote_broker.h>
#include "devicestatus_data_utils.h"
namespace OHOS {
namespace Msdp {
class IdevicestatusStorage : public IRemoteBroker {
public:
struct DevicestatusRecord {
DevicestatusDataUtils::DevicestatusType type;
DevicestatusDataUtils::DevicestatusValue value;
std::string date;
std::string time;
};
virtual bool Save(DevicestatusRecord record) = 0;
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.msdp.IdevicestatusStorage");
};
} // namespace Msdp
} // namespace OHOS
#endif // IDEVICESTATUS_STORAGE_H

View File

@ -0,0 +1,50 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { AsyncCallback } from "./basic";
declare namespace devicestatus {
export enum DevicestatusType {
TYPE_HIGH_STILL = 0,
TYPE_FINE_STILL = 1,
TYPE_CAR_BLUETOOTH = 2
}
export enum DevicestatusValue {
VALUE_ENTER = 0,
VALUE_EXIT
}
export interface DevicestatusResponse {
devicestatusValue: DevicestatusValue
}
export interface HighStillResponse extends DevicestatusResponse {}
export interface FineStillResponse extends DevicestatusResponse {}
export interface CarBluetoothResponse extends DevicestatusResponse {}
function on(type: DevicestatusType.TYPE_HIGH_STILL, callback: AsyncCallback<HighStillResponse>): void;
function once(type: DevicestatusType.TYPE_HIGH_STILL, callback: AsyncCallback<HighStillResponse>): void;
function off(type: DevicestatusType.TYPE_HIGH_STILL, callback: AsyncCallback<void>): void;
function on(type: DevicestatusType.TYPE_FINE_STILL, callback: AsyncCallback<FineStillResponse>): void;
function once(type: DevicestatusType.TYPE_FINE_STILL, callback: AsyncCallback<FineStillResponse>): void;
function off(type: DevicestatusType.TYPE_FINE_STILL, callback: AsyncCallback<void>): void;
function on(type: DevicestatusType.TYPE_CAR_BLUETOOTH, callback: AsyncCallback<CarBluetoothResponse>): void;
function once(type: DevicestatusType.TYPE_CAR_BLUETOOTH, callback: AsyncCallback<CarBluetoothResponse>): void;
function off(type: DevicestatusType.TYPE_CAR_BLUETOOTH, callback: AsyncCallback<void>): void;
}
export default devicestatus;

96
libs/BUILD.gn Normal file
View File

@ -0,0 +1,96 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//base/msdp/device_status/device_status.gni")
config("devicestatus_private_config") {
include_dirs = [ "//utils/system/safwk/native/include" ]
}
config("devicestatus_srv_public_config") {
include_dirs = [
"include",
"interface",
"${device_status_interfaces_path}/innerkits/include",
"//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include/",
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb/include/",
"//foundation/aafwk/standard/frameworks/kits/ability/native/include/",
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_appdatafwk/include/",
"//base/sensors/sensor/interfaces/native/include/"
]
}
ohos_shared_library("devicestatus_sensorhdi") {
sources = [
"src/devicestatus_sensor_rdb.cpp",
]
configs = [
"${device_status_utils_path}:devicestatus_utils_config",
":devicestatus_private_config",
]
public_configs = [ ":devicestatus_srv_public_config" ]
deps = [
"${device_status_interfaces_path}/innerkits:devicestatus_client",
"//utils/native/base:utils",
"//drivers/peripheral/sensor/hal:hdi_sensor",
"//third_party/jsoncpp"
]
external_deps = [
"ability_runtime:base",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_standard:samgr_proxy",
"permission_standard:libpermissionsdk_standard",
"native_appdatamgr:native_rdb",
"sensor:sensor_interface_native",
]
part_name = "${device_status_part_name}"
}
ohos_shared_library("devicestatus_msdp") {
sources = [
"src/devicestatus_msdp_rdb.cpp",
]
configs = [
"${device_status_utils_path}:devicestatus_utils_config",
":devicestatus_private_config",
]
public_configs = [ ":devicestatus_srv_public_config" ]
deps = [
"${device_status_interfaces_path}/innerkits:devicestatus_client",
"//utils/native/base:utils",
"//drivers/peripheral/sensor/hal:hdi_sensor",
"//third_party/jsoncpp"
]
external_deps = [
"ability_runtime:base",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_standard:samgr_proxy",
"permission_standard:libpermissionsdk_standard",
"native_appdatamgr:native_rdb",
]
part_name = "${device_status_part_name}"
}

View File

@ -0,0 +1,90 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_MSDP_RDB_H
#define DEVICESTATUS_MSDP_RDB_H
#include <string>
#include <memory>
#include <vector>
#include <thread>
#include <mutex>
#include <map>
#include <errors.h>
#include "rdb_store.h"
#include "rdb_helper.h"
#include "rdb_open_callback.h"
#include "rdb_store_config.h"
#include "values_bucket.h"
#include "result_set.h"
#include "devicestatus_data_utils.h"
#include "devicestatus_msdp_interface.h"
namespace OHOS {
namespace Msdp {
class DevicestatusMsdpRdb : public DevicestatusMsdpInterface {
public:
enum EventType {
EVENT_UEVENT_FD,
EVENT_TIMER_FD,
};
DevicestatusMsdpRdb() {}
virtual ~DevicestatusMsdpRdb() {}
bool Init();
void InitRdbStore();
void SetTimerInterval(int interval);
void InitTimer();
void TimerCallback();
int RegisterTimerCallback(const int fd, const EventType et);
void StartThread();
void LoopingThreadEntry();
ErrCode Enable() override;
ErrCode Disable() override;
ErrCode RegisterCallback(std::shared_ptr<MsdpAlgorithmCallback>& callback) override;
ErrCode UnregisterCallback() override;
ErrCode NotifyMsdpImpl(DevicestatusDataUtils::DevicestatusData& data);
int TrigerData(std::unique_ptr<NativeRdb::ResultSet> &resultSet);
int TrigerDatabaseObserver();
DevicestatusDataUtils::DevicestatusData SaveRdbData(DevicestatusDataUtils::DevicestatusData& data);
std::shared_ptr<MsdpAlgorithmCallback> GetCallbacksImpl()
{
std::unique_lock lock(mutex_);
return callbacksImpl_;
}
private:
using Callback = std::function<void(DevicestatusMsdpRdb*)>;
std::shared_ptr<MsdpAlgorithmCallback> callbacksImpl_;
std::map<int32_t, Callback> callbacks_;
std::shared_ptr<NativeRdb::RdbStore> store_;
int devicestatusType_ = -1;
int devicestatusStatus_ = -1;
bool notifyFlag_ = false;
int timerInterval_ = -1;
int32_t timerFd_ = -1;
int32_t epFd_ = -1;
std::map<DevicestatusDataUtils::DevicestatusType, DevicestatusDataUtils::DevicestatusValue> rdbDataMap_;
std::mutex mutex_;
};
class InsertOpenCallback : public NativeRdb::RdbOpenCallback {
public:
int OnCreate(NativeRdb::RdbStore &rdbStore) override;
int OnUpgrade(NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) override;
};
}
}
#endif // DEVICESTATUS_MSDP_RDB_H

View File

@ -0,0 +1,95 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_SENSOR_RDB_H
#define DEVICESTATUS_SENSOR_RDB_H
#include <string>
#include <memory>
#include <vector>
#include <thread>
#include <mutex>
#include <map>
#include <errors.h>
#include "rdb_store.h"
#include "rdb_helper.h"
#include "rdb_open_callback.h"
#include "rdb_store_config.h"
#include "values_bucket.h"
#include "result_set.h"
#include "devicestatus_data_utils.h"
#include "devicestatus_sensor_interface.h"
#include "sensor_agent.h"
#include "sensor_agent_type.h"
namespace OHOS {
namespace Msdp {
class DevicestatusSensorRdb : public DevicestatusSensorInterface {
public:
enum EventType {
EVENT_UEVENT_FD,
EVENT_TIMER_FD,
};
DevicestatusSensorRdb() {}
virtual ~DevicestatusSensorRdb() {}
bool Init();
void InitRdbStore();
void SetTimerInterval(int interval);
void InitTimer();
void TimerCallback();
int RegisterTimerCallback(const int fd, const EventType et);
void StartThread();
void LoopingThreadEntry();
ErrCode Enable() override;
ErrCode Disable() override;
ErrCode RegisterCallback(std::shared_ptr<DevicestatusSensorHdiCallback>& callback) override;
ErrCode UnregisterCallback() override;
ErrCode NotifyMsdpImpl(DevicestatusDataUtils::DevicestatusData& data);
int TrigerData(std::unique_ptr<NativeRdb::ResultSet> &resultSet);
int TrigerDatabaseObserver();
DevicestatusDataUtils::DevicestatusData SaveRdbData(DevicestatusDataUtils::DevicestatusData& data);
std::shared_ptr<DevicestatusSensorHdiCallback> GetCallbacksImpl()
{
std::unique_lock lock(mutex_);
return callbacksImpl_;
}
void HandleHallSensorEvent(SensorEvent *event);
void SubscribeHallSensor();
void UnSubscribeHallSensor();
private:
using Callback = std::function<void(DevicestatusSensorRdb*)>;
std::shared_ptr<DevicestatusSensorHdiCallback> callbacksImpl_;
std::map<int32_t, Callback> callbacks_;
std::shared_ptr<NativeRdb::RdbStore> store_;
int devicestatusType_ = -1;
int devicestatusStatus_ = -1;
bool notifyFlag_ = false;
int timerInterval_ = -1;
int32_t timerFd_ = -1;
int32_t epFd_ = -1;
std::map<DevicestatusDataUtils::DevicestatusType, DevicestatusDataUtils::DevicestatusValue> rdbDataMap_;
std::mutex mutex_;
};
class HelperCallback : public NativeRdb::RdbOpenCallback {
public:
int OnCreate(NativeRdb::RdbStore &rdbStore) override;
int OnUpgrade(NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) override;
};
}
}
#endif // DEVICESTATUS_SENSOR_RDB_H

View File

@ -0,0 +1,61 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_MSDP_INTERFACE_H
#define DEVICESTATUS_MSDP_INTERFACE_H
#include <string>
#include <memory>
#include <map>
#include <errors.h>
#include "devicestatus_data_utils.h"
namespace OHOS {
namespace Msdp {
class DevicestatusMsdpInterface {
public:
DevicestatusMsdpInterface() {}
virtual ~DevicestatusMsdpInterface() {}
class MsdpAlgorithmCallback {
public:
MsdpAlgorithmCallback() = default;
virtual ~MsdpAlgorithmCallback() = default;
virtual void OnResult(DevicestatusDataUtils::DevicestatusData& data) = 0;
};
virtual ErrCode RegisterCallback(std::shared_ptr<MsdpAlgorithmCallback>& callback) = 0;
virtual ErrCode UnregisterCallback() = 0;
virtual ErrCode Enable() = 0;
virtual ErrCode Disable() = 0;
};
struct MsdpAlgorithmHandle {
void* handle;
DevicestatusMsdpInterface* (*create)();
void* (*destroy)(DevicestatusMsdpInterface*);
DevicestatusMsdpInterface* pAlgorithm;
MsdpAlgorithmHandle() : handle(nullptr), create(nullptr), destroy(nullptr), pAlgorithm(nullptr) {}
~MsdpAlgorithmHandle() {}
void Clear()
{
handle = nullptr;
create = nullptr;
destroy = nullptr;
pAlgorithm = nullptr;
}
};
}
}
#endif // DEVICESTATUS_MSDP_INTERFACE_H

View File

@ -0,0 +1,61 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_SENSOR_INTERFACE_H
#define DEVICESTATUS_SENSOR_INTERFACE_H
#include <string>
#include <memory>
#include <map>
#include <errors.h>
#include "devicestatus_data_utils.h"
namespace OHOS {
namespace Msdp {
class DevicestatusSensorInterface {
public:
DevicestatusSensorInterface() {}
virtual ~DevicestatusSensorInterface() {}
class DevicestatusSensorHdiCallback {
public:
DevicestatusSensorHdiCallback() = default;
virtual ~DevicestatusSensorHdiCallback() = default;
virtual void OnSensorHdiResult(DevicestatusDataUtils::DevicestatusData& data) = 0;
};
virtual ErrCode RegisterCallback(std::shared_ptr<DevicestatusSensorHdiCallback>& callback) = 0;
virtual ErrCode UnregisterCallback() = 0;
virtual ErrCode Enable() = 0;
virtual ErrCode Disable() = 0;
};
struct SensorHdiHandle {
void* handle;
DevicestatusSensorInterface* (*create)();
void* (*destroy)(DevicestatusSensorInterface*);
DevicestatusSensorInterface* pAlgorithm;
SensorHdiHandle() : handle(nullptr), create(nullptr), destroy(nullptr), pAlgorithm(nullptr) {}
~SensorHdiHandle() {}
void Clear()
{
handle = nullptr;
create = nullptr;
destroy = nullptr;
pAlgorithm = nullptr;
}
};
}
}
#endif // DEVICESTATUS_SENSOR_INTERFACE_H

View File

@ -0,0 +1,366 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_msdp_rdb.h"
#include <string>
#include <cerrno>
#include <sys/epoll.h>
#include <sys/timerfd.h>
#include <unistd.h>
#include <linux/netlink.h>
#include "dummy_values_bucket.h"
#include "devicestatus_common.h"
using namespace OHOS::NativeRdb;
namespace OHOS {
namespace Msdp {
namespace {
const std::string DATABASE_NAME = "/data/MsdpStub.db";
const int TIMER_INTERVAL = 3;
const int ERR_INVALID_FD = -1;
const int READ_RDB_WAIT_TIME = 30;
std::unique_ptr<DevicestatusMsdpRdb> msdpRdb_ = std::make_unique<DevicestatusMsdpRdb>();
const int32_t ERR_NG = -1;
DevicestatusMsdpRdb* rdb;
}
bool DevicestatusMsdpRdb::Init()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DevicestatusMsdpRdbInit: enter");
InitRdbStore();
InitTimer();
StartThread();
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DevicestatusMsdpRdbInit: exit");
return true;
}
void DevicestatusMsdpRdb::InitRdbStore()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
int errCode = ERR_OK;
RdbStoreConfig config(DATABASE_NAME);
InsertOpenCallback helper;
store_ = RdbHelper::GetRdbStore(config, 1, helper, errCode);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
}
ErrCode DevicestatusMsdpRdb::RegisterCallback(std::shared_ptr<MsdpAlgorithmCallback>& callback)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
callbacksImpl_ = callback;
return ERR_OK;
}
ErrCode DevicestatusMsdpRdb::UnregisterCallback()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
return ERR_OK;
}
ErrCode DevicestatusMsdpRdb::Enable()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
Init();
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
return ERR_OK;
}
ErrCode DevicestatusMsdpRdb::Disable()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
return ERR_OK;
}
ErrCode DevicestatusMsdpRdb::NotifyMsdpImpl(DevicestatusDataUtils::DevicestatusData& data)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
if (rdb->GetCallbacksImpl() == nullptr) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "callbacksImpl is nullptr");
return ERR_NG;
}
rdb->GetCallbacksImpl()->OnResult(data);
return ERR_OK;
}
DevicestatusDataUtils::DevicestatusData DevicestatusMsdpRdb::SaveRdbData(DevicestatusDataUtils::DevicestatusData& data)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
for (auto iter = rdbDataMap_.begin(); iter != rdbDataMap_.end(); ++iter) {
if (iter->first == data.type) {
if (iter->second != data.value) {
notifyFlag_ = true;
iter->second = data.value;
}
return data;
}
}
rdbDataMap_.insert(std::make_pair(data.type, data.value));
notifyFlag_ = true;
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "devicestatusType_ = %{public}d, devicestatusStatus_ = %{public}d",
devicestatusType_, devicestatusStatus_);
return data;
}
int DevicestatusMsdpRdb::TrigerData(std::unique_ptr<NativeRdb::ResultSet> &resultSet)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
int columnIndex;
int intVal;
int ret = resultSet->GetColumnIndex("ID", columnIndex);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "TrigerDatabaseObserver GetColumnIndex = %{public}d", columnIndex);
if (ret != ERR_OK) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "CheckID: GetColumnIndex failed");
return -1;
}
ret = resultSet->GetInt(columnIndex, intVal);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "ret = %{public}d", ret);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "id = %{public}d", intVal);
if (ret != ERR_OK) {
return -1;
}
ret = resultSet->GetColumnIndex("DEVICESTATUS_TYPE", columnIndex);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DEVICESTATUS_TYPE GetColumnIndex = %{public}d", columnIndex);
if (ret != ERR_OK) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "CheckDevicestatusType: GetColumnIndex failed");
return -1;
}
ret = resultSet->GetInt(columnIndex, intVal);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "ret = %{public}d", ret);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DevicestatusType = %{public}d", intVal);
devicestatusType_ = intVal;
if (ret != ERR_OK) {
return -1;
}
ret = resultSet->GetColumnIndex("DEVICESTATUS_STATUS", columnIndex);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DEVICESTATUS_STATUS GetColumnIndex = %{public}d", columnIndex);
if (ret != ERR_OK) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "CheckDevicestatusStatus: GetColumnIndex failed");
return -1;
}
ret = resultSet->GetInt(columnIndex, intVal);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "ret = %{public}d", ret);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DevicestatusStatus = %{public}d", intVal);
devicestatusStatus_ = intVal;
if (ret != ERR_OK) {
return -1;
}
return ERR_OK;
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
}
int DevicestatusMsdpRdb::TrigerDatabaseObserver()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
std::string str;
if (store_ == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "store_ is not exist");
sleep(READ_RDB_WAIT_TIME);
InitRdbStore();
return -1;
}
std::unique_ptr<ResultSet> resultSet =
store_->QuerySql("SELECT * FROM DEVICESTATUS WHERE ID = (SELECT max(ID) from DEVICESTATUS)");
if (resultSet == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "database is not exist");
return -1;
}
int ret = resultSet->GoToFirstRow();
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "GoToFirstRow = %{public}d", ret);
if (ret != ERR_OK) {
sleep(READ_RDB_WAIT_TIME);
return -1;
}
if (TrigerData(resultSet) != ERR_OK) {
return -1;
}
ret = resultSet->Close();
if (ret != ERR_OK) {
return -1;
}
DevicestatusDataUtils::DevicestatusData data;
data.type = (DevicestatusDataUtils::DevicestatusType)devicestatusType_;
data.value = (DevicestatusDataUtils::DevicestatusValue)devicestatusStatus_;
SaveRdbData(data);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "msdp notifyFlag_ is %{public}d", notifyFlag_);
if (notifyFlag_) {
NotifyMsdpImpl(data);
notifyFlag_ = false;
}
return ERR_OK;
}
void DevicestatusMsdpRdb::InitTimer()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
epFd_ = epoll_create1(EPOLL_CLOEXEC);
if (epFd_ == -1) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "create epoll fd fail.");
}
timerFd_ = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
if (timerFd_ == ERR_INVALID_FD) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "create timer fd fail.");
}
SetTimerInterval(TIMER_INTERVAL);
fcntl(timerFd_, F_SETFL, O_NONBLOCK);
callbacks_.insert(std::make_pair(timerFd_, &DevicestatusMsdpRdb::TimerCallback));
if (RegisterTimerCallback(timerFd_, EVENT_TIMER_FD)) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "register timer fd fail.");
}
}
void DevicestatusMsdpRdb::SetTimerInterval(int interval)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
struct itimerspec itval;
if (timerFd_ == ERR_INVALID_FD) {
return;
}
timerInterval_ = interval;
if (interval < 0) {
interval = 0;
}
itval.it_interval.tv_sec = interval;
itval.it_interval.tv_nsec = 0;
itval.it_value.tv_sec = interval;
itval.it_value.tv_nsec = 0;
if (timerfd_settime(timerFd_, 0, &itval, nullptr) == -1) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "set timer failed");
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
return;
}
void DevicestatusMsdpRdb::TimerCallback()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
unsigned long long timers;
if (read(timerFd_, &timers, sizeof(timers)) == -1) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "read timer fd fail.");
return;
}
TrigerDatabaseObserver();
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
}
int DevicestatusMsdpRdb::RegisterTimerCallback(const int fd, const EventType et)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
struct epoll_event ev;
ev.events = EPOLLIN;
if (et == EVENT_TIMER_FD) {
ev.events |= EPOLLWAKEUP;
}
ev.data.ptr = reinterpret_cast<void*>(this);
ev.data.fd = fd;
if (epoll_ctl(epFd_, EPOLL_CTL_ADD, fd, &ev) == -1) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "epoll_ctl failed, error num =%{public}d", errno);
return -1;
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
return 0;
}
void DevicestatusMsdpRdb::StartThread()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
std::make_unique<std::thread>(&DevicestatusMsdpRdb::LoopingThreadEntry, this)->detach();
}
void DevicestatusMsdpRdb::LoopingThreadEntry()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
int nevents = 0;
size_t cbct = callbacks_.size();
struct epoll_event events[cbct];
while (true) {
int timeout = 0;
nevents = epoll_wait(epFd_, events, cbct, timeout);
if (nevents == -1) {
continue;
}
for (int n = 0; n < nevents; ++n) {
if (events[n].data.ptr) {
DevicestatusMsdpRdb *func = const_cast<DevicestatusMsdpRdb *>(this);
(callbacks_.find(events[n].data.fd)->second)(func);
}
}
}
}
int InsertOpenCallback::OnCreate(RdbStore &store)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
return ERR_OK;
}
int InsertOpenCallback::OnUpgrade(RdbStore &store, int oldVersion, int newVersion)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
return ERR_OK;
}
extern "C" DevicestatusMsdpInterface *Create(void)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
rdb = new DevicestatusMsdpRdb();
return rdb;
}
extern "C" void Destroy(DevicestatusMsdpInterface* algorithm)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
delete algorithm;
}
}
}

View File

@ -0,0 +1,440 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_sensor_rdb.h"
#include <string>
#include <cerrno>
#include <sys/epoll.h>
#include <sys/timerfd.h>
#include <unistd.h>
#include <linux/netlink.h>
#include "dummy_values_bucket.h"
#include "devicestatus_common.h"
using namespace OHOS::NativeRdb;
namespace OHOS {
namespace Msdp {
namespace {
const std::string DATABASE_NAME = "/data/MsdpStub.db";
const int TIMER_INTERVAL = 3;
const int ERR_INVALID_FD = -1;
const int READ_RDB_WAIT_TIME = 30;
const int NUM_HALL_SENSOR = 100000000;
std::unique_ptr<DevicestatusSensorRdb> msdpRdb_ = std::make_unique<DevicestatusSensorRdb>();
const int32_t ERR_NG = -1;
DevicestatusSensorRdb* rdb;
SensorUser user;
}
static void OnReceivedSensorEvent(SensorEvent *event)
{
if (event == nullptr) return;
rdb->HandleHallSensorEvent(event);
}
bool DevicestatusSensorRdb::Init()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DevicestatusSensorRdbInit: enter");
InitRdbStore();
InitTimer();
StartThread();
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DevicestatusSensorRdbInit: exit");
return true;
}
void DevicestatusSensorRdb::InitRdbStore()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
int errCode = ERR_OK;
RdbStoreConfig config(DATABASE_NAME);
HelperCallback helper;
store_ = RdbHelper::GetRdbStore(config, 1, helper, errCode);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
}
ErrCode DevicestatusSensorRdb::RegisterCallback(std::shared_ptr<DevicestatusSensorHdiCallback>& callback)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
callbacksImpl_ = callback;
return ERR_OK;
}
ErrCode DevicestatusSensorRdb::UnregisterCallback()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
return ERR_OK;
}
ErrCode DevicestatusSensorRdb::Enable()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
Init();
SubscribeHallSensor();
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
return ERR_OK;
}
ErrCode DevicestatusSensorRdb::Disable()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
UnSubscribeHallSensor();
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
return ERR_OK;
}
ErrCode DevicestatusSensorRdb::NotifyMsdpImpl(DevicestatusDataUtils::DevicestatusData& data)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
if (rdb->GetCallbacksImpl() == nullptr) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "callbacksImpl is nullptr");
return ERR_NG;
}
rdb->GetCallbacksImpl()->OnSensorHdiResult(data);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
return ERR_OK;
}
DevicestatusDataUtils::DevicestatusData DevicestatusSensorRdb::SaveRdbData(
DevicestatusDataUtils::DevicestatusData& data)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
for (auto iter = rdbDataMap_.begin(); iter != rdbDataMap_.end(); ++iter) {
if (iter->first == data.type) {
if (iter->second != data.value) {
notifyFlag_ = true;
iter->second = data.value;
}
return data;
}
}
rdbDataMap_.insert(std::make_pair(data.type, data.value));
notifyFlag_ = true;
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "devicestatusType_ = %{public}d, devicestatusStatus_ = %{public}d",
devicestatusType_, devicestatusStatus_);
return data;
}
int DevicestatusSensorRdb::TrigerData(std::unique_ptr<NativeRdb::ResultSet> &resultSet)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
int columnIndex;
int intVal;
int ret = resultSet->GetColumnIndex("ID", columnIndex);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "TrigerDatabaseObserver GetColumnIndex = %{public}d", columnIndex);
if (ret != ERR_OK) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "CheckID: GetColumnIndex failed");
return -1;
}
ret = resultSet->GetInt(columnIndex, intVal);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "ret = %{public}d", ret);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "id = %{public}d", intVal);
if (ret != ERR_OK) {
return -1;
}
ret = resultSet->GetColumnIndex("DEVICESTATUS_TYPE", columnIndex);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DEVICESTATUS_TYPE GetColumnIndex = %{public}d", columnIndex);
if (ret != ERR_OK) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "CheckDevicestatusType: GetColumnIndex failed");
return -1;
}
ret = resultSet->GetInt(columnIndex, intVal);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "ret = %{public}d", ret);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DevicestatusType = %{public}d", intVal);
devicestatusType_ = intVal;
if (ret != ERR_OK) {
return -1;
}
ret = resultSet->GetColumnIndex("DEVICESTATUS_STATUS", columnIndex);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DEVICESTATUS_STATUS GetColumnIndex = %{public}d", columnIndex);
if (ret != ERR_OK) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "CheckDevicestatusStatus: GetColumnIndex failed");
return -1;
}
ret = resultSet->GetInt(columnIndex, intVal);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "ret = %{public}d", ret);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DevicestatusStatus = %{public}d", intVal);
devicestatusStatus_ = intVal;
if (ret != ERR_OK) {
return -1;
}
return ERR_OK;
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
}
int DevicestatusSensorRdb::TrigerDatabaseObserver()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
std::string str;
if (store_ == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "store_ is not exist");
sleep(READ_RDB_WAIT_TIME);
InitRdbStore();
return -1;
}
std::unique_ptr<ResultSet> resultSet =
store_->QuerySql("SELECT * FROM DEVICESTATUSSENSOR WHERE ID = (SELECT max(ID) from DEVICESTATUSSENSOR)");
if (resultSet == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "database is not exist");
return -1;
}
int ret = resultSet->GoToFirstRow();
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "GoToFirstRow = %{public}d", ret);
if (ret != ERR_OK) {
sleep(READ_RDB_WAIT_TIME);
return -1;
}
if (TrigerData(resultSet) != ERR_OK) {
return -1;
}
ret = resultSet->Close();
if (ret != ERR_OK) {
return -1;
}
DevicestatusDataUtils::DevicestatusData data;
data.type = (DevicestatusDataUtils::DevicestatusType)devicestatusType_;
data.value = (DevicestatusDataUtils::DevicestatusValue)devicestatusStatus_;
SaveRdbData(data);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "notifyFlag_ is %{public}d", notifyFlag_);
if (notifyFlag_) {
NotifyMsdpImpl(data);
notifyFlag_ = false;
}
return ERR_OK;
}
void DevicestatusSensorRdb::HandleHallSensorEvent(SensorEvent *event)
{
if (event == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "HandleHallSensorEvent event is null");
return;
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE,
"HandleHallSensorEvent sensorTypeId: %{public}d, version: %{public}d, mode: %{public}d\n",
event[0].sensorTypeId, event[0].version, event[0].mode);
DevicestatusDataUtils::DevicestatusData data;
if (event[0].sensorTypeId == SENSOR_TYPE_ID_NONE) {
AccelData *sensorData = (AccelData *)event[0].data;
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE,
"HandleHallSensorEvent sensor_data: %{public}f\n", sensorData->axisX);
data.type = DevicestatusDataUtils::DevicestatusType::TYPE_LID_OPEN;
data.value = DevicestatusDataUtils::DevicestatusValue(event[0].mode);
} else if (event[0].sensorTypeId == SENSOR_TYPE_ID_HALL) {
HallData* sensor_data = (HallData *)event[0].data;
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE,
"HandleHallSensorEvent sensor_data: %{public}d\n", sensor_data->scalar);
data.type = DevicestatusDataUtils::DevicestatusType::TYPE_LID_OPEN;
data.value = DevicestatusDataUtils::DevicestatusValue(sensor_data->scalar);
}
NotifyMsdpImpl(data);
}
void DevicestatusSensorRdb::SubscribeHallSensor()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
int32_t sensorTypeId = 0;
user.callback = OnReceivedSensorEvent;
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "SubcribeHallSensor");
int32_t ret = SubscribeSensor(sensorTypeId, &user);
ret = SetBatch(sensorTypeId, &user, NUM_HALL_SENSOR, NUM_HALL_SENSOR);
ret = ActivateSensor(sensorTypeId, &user);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
}
void DevicestatusSensorRdb::UnSubscribeHallSensor()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
int32_t sensorTypeId = 0;
user.callback = OnReceivedSensorEvent;
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "UnsubcribeHallSensor");
int32_t ret = DeactivateSensor(sensorTypeId, &user);
ret = UnsubscribeSensor(sensorTypeId, &user);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "ret = %{public}d", ret);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
}
void DevicestatusSensorRdb::InitTimer()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
epFd_ = epoll_create1(EPOLL_CLOEXEC);
if (epFd_ == -1) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "create epoll fd fail.");
}
timerFd_ = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
if (timerFd_ == ERR_INVALID_FD) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "create timer fd fail.");
}
SetTimerInterval(TIMER_INTERVAL);
fcntl(timerFd_, F_SETFL, O_NONBLOCK);
callbacks_.insert(std::make_pair(timerFd_, &DevicestatusSensorRdb::TimerCallback));
if (RegisterTimerCallback(timerFd_, EVENT_TIMER_FD)) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "register timer fd fail.");
}
}
void DevicestatusSensorRdb::SetTimerInterval(int interval)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
struct itimerspec itval;
if (timerFd_ == ERR_INVALID_FD) {
return;
}
timerInterval_ = interval;
if (interval < 0) {
interval = 0;
}
itval.it_interval.tv_sec = interval;
itval.it_interval.tv_nsec = 0;
itval.it_value.tv_sec = interval;
itval.it_value.tv_nsec = 0;
if (timerfd_settime(timerFd_, 0, &itval, nullptr) == -1) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "set timer failed");
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
return;
}
void DevicestatusSensorRdb::TimerCallback()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
unsigned long long timers;
if (read(timerFd_, &timers, sizeof(timers)) == -1) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "read timer fd fail.");
return;
}
TrigerDatabaseObserver();
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
}
int DevicestatusSensorRdb::RegisterTimerCallback(const int fd, const EventType et)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
struct epoll_event ev;
ev.events = EPOLLIN;
if (et == EVENT_TIMER_FD) {
ev.events |= EPOLLWAKEUP;
}
ev.data.ptr = reinterpret_cast<void*>(this);
ev.data.fd = fd;
if (epoll_ctl(epFd_, EPOLL_CTL_ADD, fd, &ev) == -1) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "epoll_ctl failed, error num =%{public}d", errno);
return -1;
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
return 0;
}
void DevicestatusSensorRdb::StartThread()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
std::make_unique<std::thread>(&DevicestatusSensorRdb::LoopingThreadEntry, this)->detach();
}
void DevicestatusSensorRdb::LoopingThreadEntry()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
int nevents = 0;
size_t cbct = callbacks_.size();
struct epoll_event events[cbct];
while (true) {
int timeout = 0;
nevents = epoll_wait(epFd_, events, cbct, timeout);
if (nevents == -1) {
continue;
}
for (int n = 0; n < nevents; ++n) {
if (events[n].data.ptr) {
DevicestatusSensorRdb *func = const_cast<DevicestatusSensorRdb *>(this);
(callbacks_.find(events[n].data.fd)->second)(func);
}
}
}
}
int HelperCallback::OnCreate(RdbStore &store)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
return ERR_OK;
}
int HelperCallback::OnUpgrade(RdbStore &store, int oldVersion, int newVersion)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
return ERR_OK;
}
extern "C" DevicestatusSensorInterface *Create(void)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
rdb = new DevicestatusSensorRdb();
return rdb;
}
extern "C" void Destroy(DevicestatusSensorInterface* algorithm)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
delete algorithm;
}
}
}

25
sa_profile/2902.xml Normal file
View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2022 Huawei Device Co., Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<info>
<process>msdp</process>
<systemability>
<name>2902</name>
<libpath>libdevicestatus_service.z.so</libpath>
<run-on-create>true</run-on-create>
<distributed>false</distributed>
<dump-level>1</dump-level>
</systemability>
</info>

20
sa_profile/BUILD.gn Normal file
View File

@ -0,0 +1,20 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//base/msdp/device_status/device_status.gni")
import("//build/ohos/sa_profile/sa_profile.gni")
ohos_sa_profile("devicestatus_sa_profile") {
sources = [ "2902.xml" ]
part_name = "${device_status_part_name}"
}

66
services/BUILD.gn Normal file
View File

@ -0,0 +1,66 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//base/msdp/device_status/device_status.gni")
config("devicestatus_private_config") {
include_dirs = [ "//utils/system/safwk/native/include" ]
}
config("devicestatus_srv_public_config") {
include_dirs = [
"native/include",
"${device_status_interfaces_path}/innerkits/include",
"//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include/",
"//base/msdp/device_status/libs/interface",
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb/include/",
"//foundation/aafwk/standard/frameworks/kits/ability/native/include/",
"//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_appdatafwk/include/",
]
}
ohos_shared_library("devicestatus_service") {
sources = [
"native/src/devicestatus_callback_stub.cpp",
"native/src/devicestatus_manager.cpp",
"native/src/devicestatus_service.cpp",
"native/src/devicestatus_srv_stub.cpp",
"native/src/devicestatus_msdp_client_impl.cpp"
]
configs = [
"${device_status_utils_path}:devicestatus_utils_config",
":devicestatus_private_config",
]
public_configs = [ ":devicestatus_srv_public_config" ]
deps = [
"${device_status_interfaces_path}/innerkits:devicestatus_client",
"//utils/native/base:utils",
"//drivers/peripheral/sensor/hal:hdi_sensor",
"//third_party/jsoncpp"
]
external_deps = [
"ability_runtime:base",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_standard:samgr_proxy",
"permission_standard:libpermissionsdk_standard",
"native_appdatamgr:native_rdb",
]
part_name = "${device_status_part_name}"
}

View File

@ -0,0 +1,40 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_CALLBACK_STUB_H
#define DEVICESTATUS_CALLBACK_STUB_H
#include <iremote_stub.h>
#include <nocopyable.h>
#include "idevicestatus_callback.h"
#include "devicestatus_data_utils.h"
namespace OHOS {
namespace Msdp {
class DevicestatusCallbackStub : public IRemoteStub<IdevicestatusCallback> {
public:
DISALLOW_COPY_AND_MOVE(DevicestatusCallbackStub);
DevicestatusCallbackStub() = default;
virtual ~DevicestatusCallbackStub() = default;
int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
void OnDevicestatusChanged(const DevicestatusDataUtils::DevicestatusData& __attribute__((unused))value) override {}
private:
int32_t OnDevicestatusChangedStub(MessageParcel& data);
};
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_CALLBACK_STUB_H

View File

@ -0,0 +1,77 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_MANAGER_H
#define DEVICESTATUS_MANAGER_H
#include <set>
#include <map>
#include "sensor_if.h"
#include "devicestatus_data_utils.h"
#include "idevicestatus_algorithm.h"
#include "idevicestatus_callback.h"
#include "devicestatus_common.h"
#include "devicestatus_msdp_client_impl.h"
namespace OHOS {
namespace Msdp {
class DevicestatusService;
class DevicestatusManager {
public:
explicit DevicestatusManager(const wptr<DevicestatusService>& ms) : ms_(ms)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DevicestatusManager instance is created.");
}
~DevicestatusManager() = default;
class DevicestatusCallbackDeathRecipient : public IRemoteObject::DeathRecipient {
public:
DevicestatusCallbackDeathRecipient() = default;
virtual void OnRemoteDied(const wptr<IRemoteObject> &remote);
virtual ~DevicestatusCallbackDeathRecipient() = default;
};
bool Init();
bool InitInterface();
bool InitDataCallback();
void NotifyDevicestatusChange(const DevicestatusDataUtils::DevicestatusData& devicestatusData);
void Subscribe(const DevicestatusDataUtils::DevicestatusType& type, const sptr<IdevicestatusCallback>& callback);
void UnSubscribe(const DevicestatusDataUtils::DevicestatusType& type, const sptr<IdevicestatusCallback>& callback);
DevicestatusDataUtils::DevicestatusData GetLatestDevicestatusData(const \
DevicestatusDataUtils::DevicestatusType& type);
int32_t SensorDataCallback(const struct SensorEvents *event);
int32_t MsdpDataCallback(DevicestatusDataUtils::DevicestatusData& data);
int32_t LoadAlgorithm(bool bCreate);
int32_t UnloadAlgorithm(bool bCreate);
private:
struct classcomp {
bool operator()(const sptr<IdevicestatusCallback> &l, const sptr<IdevicestatusCallback> &r) const
{
return l->AsObject() < r->AsObject();
}
};
const wptr<DevicestatusService> ms_;
std::mutex mutex_;
sptr<IRemoteObject::DeathRecipient> devicestatusCBDeathRecipient_;
std::unique_ptr<DevicestatusMsdpClientImpl> msdpImpl_;
std::map<DevicestatusDataUtils::DevicestatusType, DevicestatusDataUtils::DevicestatusValue> msdpData_;
std::map<DevicestatusDataUtils::DevicestatusType, std::set<const sptr<IdevicestatusCallback>, classcomp>> \
listenerMap_;
};
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_MANAGER_H

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_MSDP_CLIENT_IMPL_H
#define DEVICESTATUS_MSDP_CLIENT_IMPL_H
#include <string>
#include <memory>
#include <mutex>
#include <vector>
#include <thread>
#include <map>
#include <errors.h>
#include "rdb_store.h"
#include "rdb_helper.h"
#include "rdb_open_callback.h"
#include "rdb_store_config.h"
#include "values_bucket.h"
#include "result_set.h"
#include "devicestatus_data_utils.h"
#include "devicestatus_delayed_sp_singleton.h"
#include "devicestatus_msdp_interface.h"
#include "devicestatus_sensor_interface.h"
namespace OHOS {
namespace Msdp {
class DevicestatusMsdpClientImpl :
public DevicestatusMsdpInterface::MsdpAlgorithmCallback,
public DevicestatusSensorInterface::DevicestatusSensorHdiCallback {
public:
using CallbackManager = std::function<int32_t(DevicestatusDataUtils::DevicestatusData&)>;
ErrCode InitMsdpImpl();
ErrCode RegisterImpl(CallbackManager& callback);
int32_t MsdpCallback(DevicestatusDataUtils::DevicestatusData& data);
ErrCode RegisterMsdp();
ErrCode UnregisterMsdp(void);
ErrCode RegisterSensor();
ErrCode UnregisterSensor(void);
DevicestatusDataUtils::DevicestatusData SaveObserverData(DevicestatusDataUtils::DevicestatusData& data);
std::map<DevicestatusDataUtils::DevicestatusType, DevicestatusDataUtils::DevicestatusValue> GetObserverData() const;
void GetDevicestatusTimestamp();
void GetLongtitude();
void GetLatitude();
int32_t LoadAlgorithmLibrary(bool bCreate);
int32_t UnloadAlgorithmLibrary(bool bCreate);
int32_t LoadSensorHdiLibrary(bool bCreate);
int32_t UnloadSensorHdiLibrary(bool bCreate);
private:
ErrCode ImplCallback(DevicestatusDataUtils::DevicestatusData& data);
DevicestatusMsdpInterface* msdpInterface_;
DevicestatusSensorInterface* sensorHdiInterface_;
DevicestatusSensorInterface* GetSensorHdiInst();
DevicestatusMsdpInterface* GetAlgorithmInst();
MsdpAlgorithmHandle mAlgorithm_;
SensorHdiHandle sensorHdi_;
std::mutex mMutex_;
bool notifyManagerFlag_ = false;
void OnResult(DevicestatusDataUtils::DevicestatusData& data) override;
void OnSensorHdiResult(DevicestatusDataUtils::DevicestatusData& data) override;
};
}
}
#endif // DEVICESTATUS_MSDP_CLIENT_IMPL_H

View File

@ -0,0 +1,53 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_SERVICE_H
#define DEVICESTATUS_SERVICE_H
#include <memory>
#include <iremote_object.h>
#include <system_ability.h>
#include "devicestatus_srv_stub.h"
#include "idevicestatus_callback.h"
#include "devicestatus_data_utils.h"
#include "devicestatus_manager.h"
#include "devicestatus_delayed_sp_singleton.h"
namespace OHOS {
namespace Msdp {
class DevicestatusService final : public SystemAbility, public DevicestatusSrvStub {
DECLARE_SYSTEM_ABILITY(DevicestatusService)
DECLARE_DELAYED_SP_SINGLETON(DevicestatusService);
public:
virtual void OnStart() override;
virtual void OnStop() override;
void Subscribe(const DevicestatusDataUtils::DevicestatusType& type, \
const sptr<IdevicestatusCallback>& callback) override;
void UnSubscribe(const DevicestatusDataUtils::DevicestatusType& type, \
const sptr<IdevicestatusCallback>& callback) override;
DevicestatusDataUtils::DevicestatusData GetCache(const DevicestatusDataUtils::DevicestatusType& type) override;
bool IsServiceReady();
std::shared_ptr<DevicestatusManager> GetDevicestatusManager();
private:
bool Init();
bool ready_ = false;
std::shared_ptr<DevicestatusManager> devicestatusManager_;
std::shared_ptr<DevicestatusMsdpClientImpl> msdpImpl_;
};
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_SERVICE_H

View File

@ -0,0 +1,40 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_SRV_STUB_H
#define DEVICESTATUS_SRV_STUB_H
#include <iremote_stub.h>
#include <nocopyable.h>
#include "idevicestatus.h"
namespace OHOS {
namespace Msdp {
class DevicestatusSrvStub : public IRemoteStub<Idevicestatus> {
public:
DevicestatusSrvStub() = default;
virtual ~DevicestatusSrvStub() = default;
DISALLOW_COPY_AND_MOVE(DevicestatusSrvStub);
int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
private:
int32_t SubscribeStub(MessageParcel& data);
int32_t UnSubscribeStub(MessageParcel& data);
int32_t GetLatestDevicestatusDataStub(MessageParcel& data, MessageParcel& reply);
};
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_SRV_STUB_H

View File

@ -0,0 +1,62 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_callback_stub.h"
#include <message_parcel.h>
#include "devicestatus_common.h"
#include "devicestatus_callback_proxy.h"
namespace OHOS {
namespace Msdp {
int DevicestatusCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, \
MessageOption &option)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_SERVICE, "cmd = %{public}d, flags= %{public}d", code, option.GetFlags());
std::u16string descripter = DevicestatusCallbackStub::GetDescriptor();
std::u16string remoteDescripter = data.ReadInterfaceToken();
if (descripter != remoteDescripter) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, \
"DevicestatusCallbackStub::OnRemoteRequest failed, descriptor mismatch");
return E_DEVICESTATUS_GET_SERVICE_FAILED;
}
switch (code) {
case static_cast<int>(IdevicestatusCallback::DEVICESTATUS_CHANGE): {
return OnDevicestatusChangedStub(data);
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
return ERR_OK;
}
int32_t DevicestatusCallbackStub::OnDevicestatusChangedStub(MessageParcel& data)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_SERVICE, "Enter");
int32_t type;
int32_t value;
DEVICESTATUS_READ_PARCEL_WITH_RET(data, Int32, type, E_DEVICESTATUS_READ_PARCEL_ERROR);
DEVICESTATUS_READ_PARCEL_WITH_RET(data, Int32, value, E_DEVICESTATUS_READ_PARCEL_ERROR);
DevicestatusDataUtils::DevicestatusData devicestatusData = {
static_cast<DevicestatusDataUtils::DevicestatusType>(type),
static_cast<DevicestatusDataUtils::DevicestatusValue>(value)
};
OnDevicestatusChanged(devicestatusData);
return ERR_OK;
}
} // namespace Msdp
} // namespace OHOS

View File

@ -0,0 +1,227 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_manager.h"
#include "devicestatus_msdp_client_impl.h"
namespace OHOS {
namespace Msdp {
void DevicestatusManager::DevicestatusCallbackDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
{
if (remote == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "OnRemoteDied failed, remote is nullptr");
return;
}
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_SERVICE, "Recv death notice");
}
bool DevicestatusManager::Init()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DevicestatusManager: Init start");
if (devicestatusCBDeathRecipient_ == nullptr) {
devicestatusCBDeathRecipient_ = new DevicestatusCallbackDeathRecipient();
}
msdpImpl_ = std::make_unique<DevicestatusMsdpClientImpl>();
if (msdpImpl_ == nullptr) {
return false;
}
LoadAlgorithm(false);
if (!InitInterface()) {
return false;
}
if (!InitDataCallback()) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "%{public}s init msdp callback fail.", __func__);
return false;
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "DevicestatusManager: Init success");
return true;
}
DevicestatusDataUtils::DevicestatusData DevicestatusManager::GetLatestDevicestatusData(const \
DevicestatusDataUtils::DevicestatusType& type)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
DevicestatusDataUtils::DevicestatusData data = {type, DevicestatusDataUtils::DevicestatusValue::VALUE_EXIT};
msdpData_ = msdpImpl_->GetObserverData();
for (auto iter = msdpData_.begin(); iter != msdpData_.end(); ++iter) {
if (data.type == iter->first) {
data.value = iter->second;
return data;
}
}
data.value = DevicestatusDataUtils::DevicestatusValue::VALUE_INVALID;
return data;
}
bool DevicestatusManager::InitInterface()
{
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "enter");
if (msdpImpl_ != nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "Init msdp client impl");
msdpImpl_->InitMsdpImpl();
}
return true;
}
bool DevicestatusManager::InitDataCallback()
{
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "enter");
if (msdpImpl_ != nullptr) {
DevicestatusMsdpClientImpl::CallbackManager callback =
std::bind(&DevicestatusManager::MsdpDataCallback, this, std::placeholders::_1);
msdpImpl_->RegisterImpl(callback);
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "InitDataCallback: after register impl");
}
return true;
}
int32_t DevicestatusManager::MsdpDataCallback(DevicestatusDataUtils::DevicestatusData& data)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
NotifyDevicestatusChange(data);
return ERR_OK;
}
int32_t DevicestatusManager::SensorDataCallback(const struct SensorEvents *event)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
// TO-DO, handle sensor event properly when we get the data details of sensor HDI.
DevicestatusDataUtils::DevicestatusData data = {DevicestatusDataUtils::DevicestatusType::TYPE_HIGH_STILL,
DevicestatusDataUtils::DevicestatusValue::VALUE_ENTER};
NotifyDevicestatusChange(data);
return ERR_OK;
}
void DevicestatusManager::NotifyDevicestatusChange(const DevicestatusDataUtils::DevicestatusData& devicestatusData)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
// Call back for all listeners
std::set<const sptr<IdevicestatusCallback>, classcomp> listeners;
bool isExists = false;
for (auto it = listenerMap_.begin(); it != listenerMap_.end(); ++it) {
if (it->first == devicestatusData.type) {
isExists = true;
listeners = (std::set<const sptr<IdevicestatusCallback>, classcomp>)(it->second);
break;
}
}
if (!isExists) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "No listener found for type: %{public}d", \
devicestatusData.type);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
return;
}
for (auto& listener : listeners) {
listener->OnDevicestatusChanged(devicestatusData);
}
}
void DevicestatusManager::Subscribe(const DevicestatusDataUtils::DevicestatusType& type,
const sptr<IdevicestatusCallback>& callback)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
DEVICESTATUS_RETURN_IF(callback == nullptr);
auto object = callback->AsObject();
DEVICESTATUS_RETURN_IF(object == nullptr);
std::set<const sptr<IdevicestatusCallback>, classcomp> listeners;
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "listenerMap_.size=%{public}zu", listenerMap_.size());
std::lock_guard lock(mutex_);
auto dtTypeIter = listenerMap_.find(type);
if (dtTypeIter == listenerMap_.end()) {
if (listeners.insert(callback).second) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "no found set list of type, insert success");
object->AddDeathRecipient(devicestatusCBDeathRecipient_);
}
listenerMap_.insert(std::make_pair(type, listeners));
} else {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "callbacklist.size=%{public}zu",
listenerMap_[dtTypeIter->first].size());
auto iter = listenerMap_[dtTypeIter->first].find(callback);
if (iter != listenerMap_[dtTypeIter->first].end()) {
return;
} else {
if (listenerMap_[dtTypeIter->first].insert(callback).second) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "found set list of type, insert success");
object->AddDeathRecipient(devicestatusCBDeathRecipient_);
}
}
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "object = %{public}p, callback = %{public}p",
object.GetRefPtr(), callback.GetRefPtr());
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
}
void DevicestatusManager::UnSubscribe(const DevicestatusDataUtils::DevicestatusType& type,
const sptr<IdevicestatusCallback>& callback)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
std::lock_guard lock(mutex_);
DEVICESTATUS_RETURN_IF(callback == nullptr);
auto object = callback->AsObject();
DEVICESTATUS_RETURN_IF(object == nullptr);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "listenerMap_.size=%{public}zu", listenerMap_.size());
auto dtTypeIter = listenerMap_.find(type);
if (dtTypeIter == listenerMap_.end()) {
return;
} else {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "callbacklist.size=%{public}zu",
listenerMap_[dtTypeIter->first].size());
auto iter = listenerMap_[dtTypeIter->first].find(callback);
if (iter != listenerMap_[dtTypeIter->first].end()) {
if (listenerMap_[dtTypeIter->first].erase(callback) != 0) {
object->RemoveDeathRecipient(devicestatusCBDeathRecipient_);
if (listenerMap_[dtTypeIter->first].size() == 0) {
listenerMap_.erase(dtTypeIter);
}
}
}
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "object = %{public}p, callback = %{public}p",
object.GetRefPtr(), callback.GetRefPtr());
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
}
int32_t DevicestatusManager::LoadAlgorithm(bool bCreate)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
if (msdpImpl_ != nullptr) {
msdpImpl_->LoadAlgorithmLibrary(bCreate);
msdpImpl_->LoadSensorHdiLibrary(bCreate);
}
return ERR_OK;
}
int32_t DevicestatusManager::UnloadAlgorithm(bool bCreate)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
if (msdpImpl_ != nullptr) {
msdpImpl_->UnloadAlgorithmLibrary(bCreate);
msdpImpl_->UnloadSensorHdiLibrary(bCreate);
}
return ERR_OK;
}
} // namespace Msdp
} // namespace OHOS

View File

@ -0,0 +1,374 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_msdp_client_impl.h"
#include <dlfcn.h>
#include <string>
#include <cerrno>
#include <sys/epoll.h>
#include <sys/timerfd.h>
#include <unistd.h>
#include <errors.h>
#include <linux/netlink.h>
#include "dummy_values_bucket.h"
#include "devicestatus_common.h"
using namespace OHOS::NativeRdb;
namespace OHOS {
namespace Msdp {
namespace {
const int ERR_OK = 0;
const int ERR_NG = -1;
const std::string DEVICESTATUS_SENSOR_HDI_LIB_PATH = "libdevicestatus_sensorhdi.z.so";
const std::string DEVICESTATUS_MSDP_ALGORITHM_LIB_PATH = "libdevicestatus_msdp.z.so";
std::map<DevicestatusDataUtils::DevicestatusType, DevicestatusDataUtils::DevicestatusValue> devicestatusDataMap_;
DevicestatusMsdpClientImpl::CallbackManager callbacksMgr_;
using clientType = DevicestatusDataUtils::DevicestatusType;
using clientValue = DevicestatusDataUtils::DevicestatusValue;
}
ErrCode DevicestatusMsdpClientImpl::InitMsdpImpl()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
if (msdpInterface_ == nullptr) {
msdpInterface_ = GetAlgorithmInst();
if (msdpInterface_ == nullptr) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "get msdp module instance failed");
return ERR_NG;
}
}
if (sensorHdiInterface_ == nullptr) {
sensorHdiInterface_ = GetSensorHdiInst();
if (sensorHdiInterface_ == nullptr) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "get sensor module instance failed");
return ERR_NG;
}
}
msdpInterface_->Enable();
sensorHdiInterface_->Enable();
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
return ERR_OK;
}
ErrCode DevicestatusMsdpClientImpl::RegisterSensor()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
if (sensorHdiInterface_ != nullptr) {
std::shared_ptr<DevicestatusSensorHdiCallback> callback = std::make_shared<DevicestatusMsdpClientImpl>();
sensorHdiInterface_->RegisterCallback(callback);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "sensorHdiInterface_ is not nullptr");
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
return ERR_OK;
}
ErrCode DevicestatusMsdpClientImpl::UnregisterSensor(void)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
int32_t ret = sensorHdiInterface_->UnregisterCallback();
if (ret < 0) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "unregister sensor failed");
return ERR_NG;
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
return ERR_OK;
}
ErrCode DevicestatusMsdpClientImpl::RegisterImpl(CallbackManager& callback)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
callbacksMgr_ = callback;
if (msdpInterface_ == nullptr) {
msdpInterface_ = GetAlgorithmInst();
if (msdpInterface_ == nullptr) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "get msdp module instance failed");
return ERR_NG;
}
}
if (sensorHdiInterface_ == nullptr) {
sensorHdiInterface_ = GetSensorHdiInst();
if (sensorHdiInterface_ == nullptr) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "get sensor module instance failed");
return ERR_NG;
}
}
RegisterMsdp();
RegisterSensor();
return ERR_OK;
}
ErrCode DevicestatusMsdpClientImpl::ImplCallback(DevicestatusDataUtils::DevicestatusData& data)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
if (callbacksMgr_ == nullptr) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "callbacksMgr_ is nullptr");
return ERR_NG;
}
callbacksMgr_(data);
return ERR_OK;
}
void DevicestatusMsdpClientImpl::OnResult(DevicestatusDataUtils::DevicestatusData& data)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
MsdpCallback(data);
}
void DevicestatusMsdpClientImpl::OnSensorHdiResult(DevicestatusDataUtils::DevicestatusData& data)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
MsdpCallback(data);
}
ErrCode DevicestatusMsdpClientImpl::RegisterMsdp()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
if (msdpInterface_ != nullptr) {
std::shared_ptr<MsdpAlgorithmCallback> callback = std::make_shared<DevicestatusMsdpClientImpl>();
msdpInterface_->RegisterCallback(callback);
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
return ERR_OK;
}
ErrCode DevicestatusMsdpClientImpl::UnregisterMsdp(void)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
int32_t ret = msdpInterface_->UnregisterCallback();
if (ret < 0) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "unregister Msdp failed");
return ERR_NG;
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
return ERR_OK;
}
int32_t DevicestatusMsdpClientImpl::MsdpCallback(DevicestatusDataUtils::DevicestatusData& data)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
SaveObserverData(data);
if (notifyManagerFlag_) {
ImplCallback(data);
notifyManagerFlag_ = false;
}
return ERR_OK;
}
DevicestatusDataUtils::DevicestatusData DevicestatusMsdpClientImpl::SaveObserverData(
DevicestatusDataUtils::DevicestatusData& data)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
for (auto iter = devicestatusDataMap_.begin(); iter != devicestatusDataMap_.end(); ++iter) {
if (iter->first == data.type) {
iter->second = data.value;
notifyManagerFlag_ = true;
return data;
}
}
devicestatusDataMap_.insert(std::make_pair(data.type, data.value));
notifyManagerFlag_ = true;
return data;
}
std::map<clientType, clientValue> DevicestatusMsdpClientImpl::GetObserverData() const
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
return devicestatusDataMap_;
}
void DevicestatusMsdpClientImpl::GetDevicestatusTimestamp()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
}
void DevicestatusMsdpClientImpl::GetLongtitude()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
}
void DevicestatusMsdpClientImpl::GetLatitude()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
}
int32_t DevicestatusMsdpClientImpl::LoadSensorHdiLibrary(bool bCreate)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
if (sensorHdi_.handle != nullptr) {
return ERR_OK;
}
sensorHdi_.handle = dlopen(DEVICESTATUS_SENSOR_HDI_LIB_PATH.c_str(), RTLD_LAZY);
if (sensorHdi_.handle == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE,
"Cannot load sensor hdi library error = %{public}s", dlerror());
return ERR_NG;
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "start create sensor hdi pointer");
sensorHdi_.create = (DevicestatusSensorInterface* (*)()) dlsym(sensorHdi_.handle, "Create");
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "start destroy sensor hdi pointer");
sensorHdi_.destroy = (void *(*)(DevicestatusSensorInterface*))dlsym(sensorHdi_.handle, "Destroy");
if (sensorHdi_.create == nullptr || sensorHdi_.destroy == nullptr) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "%{public}s dlsym Create or Destory sensor hdi failed!",
DEVICESTATUS_MSDP_ALGORITHM_LIB_PATH.c_str());
dlclose(sensorHdi_.handle);
sensorHdi_.Clear();
bCreate = false;
return ERR_NG;
}
if (bCreate) {
sensorHdi_.pAlgorithm = sensorHdi_.create();
}
return ERR_OK;
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
}
int32_t DevicestatusMsdpClientImpl::UnloadSensorHdiLibrary(bool bCreate)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
if (sensorHdi_.handle == nullptr) {
return ERR_NG;
}
if (sensorHdi_.pAlgorithm != nullptr) {
sensorHdi_.destroy(sensorHdi_.pAlgorithm);
sensorHdi_.pAlgorithm = nullptr;
}
if (!bCreate) {
dlclose(sensorHdi_.handle);
sensorHdi_.Clear();
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
return ERR_OK;
}
DevicestatusSensorInterface* DevicestatusMsdpClientImpl::GetSensorHdiInst()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
if (sensorHdi_.handle == nullptr) {
return nullptr;
}
if (sensorHdi_.pAlgorithm == nullptr) {
std::unique_lock<std::mutex> lock(mMutex_);
if (sensorHdi_.pAlgorithm == nullptr) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Get mAlgorithm.pAlgorithm");
sensorHdi_.pAlgorithm = sensorHdi_.create();
}
}
return sensorHdi_.pAlgorithm;
}
int32_t DevicestatusMsdpClientImpl::LoadAlgorithmLibrary(bool bCreate)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
if (mAlgorithm_.handle != nullptr) {
return ERR_OK;
}
mAlgorithm_.handle = dlopen(DEVICESTATUS_MSDP_ALGORITHM_LIB_PATH.c_str(), RTLD_LAZY);
if (mAlgorithm_.handle == nullptr) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "Cannot load library error = %{public}s", dlerror());
return ERR_NG;
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "start create pointer");
mAlgorithm_.create = (DevicestatusMsdpInterface* (*)()) dlsym(mAlgorithm_.handle, "Create");
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "start destroy pointer");
mAlgorithm_.destroy = (void *(*)(DevicestatusMsdpInterface*))dlsym(mAlgorithm_.handle, "Destroy");
if (mAlgorithm_.create == nullptr || mAlgorithm_.destroy == nullptr) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "%{public}s dlsym Create or Destory failed!",
DEVICESTATUS_MSDP_ALGORITHM_LIB_PATH.c_str());
dlclose(mAlgorithm_.handle);
mAlgorithm_.Clear();
bCreate = false;
return ERR_NG;
}
if (bCreate) {
mAlgorithm_.pAlgorithm = mAlgorithm_.create();
}
return ERR_OK;
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
}
int32_t DevicestatusMsdpClientImpl::UnloadAlgorithmLibrary(bool bCreate)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
if (mAlgorithm_.handle == nullptr) {
return ERR_NG;
}
if (mAlgorithm_.pAlgorithm != nullptr) {
mAlgorithm_.destroy(mAlgorithm_.pAlgorithm);
mAlgorithm_.pAlgorithm = nullptr;
}
if (!bCreate) {
dlclose(mAlgorithm_.handle);
mAlgorithm_.Clear();
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "exit");
return ERR_OK;
}
DevicestatusMsdpInterface* DevicestatusMsdpClientImpl::GetAlgorithmInst()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "enter");
if (mAlgorithm_.handle == nullptr) {
return nullptr;
}
if (mAlgorithm_.pAlgorithm == nullptr) {
std::unique_lock<std::mutex> lock(mMutex_);
if (mAlgorithm_.pAlgorithm == nullptr) {
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Get mAlgorithm.pAlgorithm");
mAlgorithm_.pAlgorithm = mAlgorithm_.create();
}
}
return mAlgorithm_.pAlgorithm;
}
}
}

View File

@ -0,0 +1,125 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_service.h"
#include <ipc_skeleton.h>
#include "if_system_ability_manager.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
#include "devicestatus_permission.h"
#include "devicestatus_common.h"
namespace OHOS {
namespace Msdp {
namespace {
auto ms = DelayedSpSingleton<DevicestatusService>::GetInstance();
const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(ms.GetRefPtr());
}
DevicestatusService::DevicestatusService() : SystemAbility(MSDP_DEVICESTATUS_SERVICE_ID, true)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_SERVICE, "Add SystemAbility");
}
DevicestatusService::~DevicestatusService() {}
void DevicestatusService::OnStart()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
if (ready_) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "OnStart is ready, nothing to do.");
return;
}
if (!Init()) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "OnStart call init fail");
return;
}
if (!Publish(DelayedSpSingleton<DevicestatusService>::GetInstance())) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "OnStart register to system ability manager failed");
return;
}
ready_ = true;
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "OnStart and add system ability success");
}
void DevicestatusService::OnStop()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
if (!ready_) {
return;
}
ready_ = false;
if (!devicestatusManager_) {
devicestatusManager_->UnloadAlgorithm(false);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "unload algorithm library");
}
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
}
bool DevicestatusService::Init()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
if (!devicestatusManager_) {
devicestatusManager_ = std::make_shared<DevicestatusManager>(ms);
}
if (!devicestatusManager_->Init()) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, "OnStart init fail");
return false;
}
return true;
}
bool DevicestatusService::IsServiceReady()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
return ready_;
}
std::shared_ptr<DevicestatusManager> DevicestatusService::GetDevicestatusManager()
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
return devicestatusManager_;
}
void DevicestatusService::Subscribe(const DevicestatusDataUtils::DevicestatusType& type,
const sptr<IdevicestatusCallback>& callback)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
devicestatusManager_->Subscribe(type, callback);
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Exit");
}
void DevicestatusService::UnSubscribe(const DevicestatusDataUtils::DevicestatusType& type,
const sptr<IdevicestatusCallback>& callback)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
devicestatusManager_->UnSubscribe(type, callback);
}
DevicestatusDataUtils::DevicestatusData DevicestatusService::GetCache(const \
DevicestatusDataUtils::DevicestatusType& type)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "Enter");
return devicestatusManager_->GetLatestDevicestatusData(type);
}
} // namespace Msdp
} // namespace OHOS

View File

@ -0,0 +1,100 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_srv_stub.h"
#include "message_parcel.h"
#include "devicestatus_srv_proxy.h"
#include "devicestatus_common.h"
#include "idevicestatus_callback.h"
#include "devicestatus_data_utils.h"
#include "devicestatus_service.h"
namespace OHOS {
namespace Msdp {
int DevicestatusSrvStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, \
MessageOption &option)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_SERVICE, "cmd = %{public}d, flags = %{public}d", code, option.GetFlags());
std::u16string descriptor = DevicestatusSrvStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_SERVICE, \
"DevicestatusSrvStub::OnRemoteRequest failed, descriptor is not matched!");
return E_DEVICESTATUS_GET_SERVICE_FAILED;
}
switch (code) {
case static_cast<int>(Idevicestatus::DEVICESTATUS_SUBSCRIBE): {
return SubscribeStub(data);
}
case static_cast<int>(Idevicestatus::DEVICESTATUS_UNSUBSCRIBE): {
return UnSubscribeStub(data);
}
case static_cast<int>(Idevicestatus::DEVICESTATUS_GETCACHE): {
return GetLatestDevicestatusDataStub(data, reply);
}
default: {
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
return ERR_OK;
}
int32_t DevicestatusSrvStub::SubscribeStub(MessageParcel& data)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_SERVICE, "Enter");
int32_t type = -1;
DEVICESTATUS_READ_PARCEL_WITH_RET(data, Int32, type, E_DEVICESTATUS_READ_PARCEL_ERROR);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_SERVICE, "Read type successfully");
sptr<IRemoteObject> obj = data.ReadRemoteObject();
DEVICESTATUS_RETURN_IF_WITH_RET((obj == nullptr), E_DEVICESTATUS_READ_PARCEL_ERROR);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_SERVICE, "Read remote obj successfully");
sptr<IdevicestatusCallback> callback = iface_cast<IdevicestatusCallback>(obj);
DEVICESTATUS_RETURN_IF_WITH_RET((callback == nullptr), E_DEVICESTATUS_READ_PARCEL_ERROR);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_SERVICE, "Read callback successfully");
Subscribe(DevicestatusDataUtils::DevicestatusType(type), callback);
return ERR_OK;
}
int32_t DevicestatusSrvStub::UnSubscribeStub(MessageParcel& data)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_SERVICE, "Enter");
int32_t type = -1;
DEVICESTATUS_READ_PARCEL_WITH_RET(data, Int32, type, E_DEVICESTATUS_READ_PARCEL_ERROR);
sptr<IRemoteObject> obj = data.ReadRemoteObject();
DEVICESTATUS_RETURN_IF_WITH_RET((obj == nullptr), E_DEVICESTATUS_READ_PARCEL_ERROR);
sptr<IdevicestatusCallback> callback = iface_cast<IdevicestatusCallback>(obj);
DEVICESTATUS_RETURN_IF_WITH_RET((callback == nullptr), E_DEVICESTATUS_READ_PARCEL_ERROR);
UnSubscribe(DevicestatusDataUtils::DevicestatusType(type), callback);
return ERR_OK;
}
int32_t DevicestatusSrvStub::GetLatestDevicestatusDataStub(MessageParcel& data, MessageParcel& reply)
{
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_SERVICE, "Enter");
int32_t type = -1;
DEVICESTATUS_READ_PARCEL_WITH_RET(data, Int32, type, E_DEVICESTATUS_READ_PARCEL_ERROR);
DevicestatusDataUtils::DevicestatusData devicestatusData = GetCache(DevicestatusDataUtils::DevicestatusType(type));
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_SERVICE, "devicestatusData.type: %{public}d", devicestatusData.type);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_SERVICE, "devicestatusData.value: %{public}d", devicestatusData.value);
DEVICESTATUS_WRITE_PARCEL_WITH_RET(reply, Int32, devicestatusData.type, E_DEVICESTATUS_WRITE_PARCEL_ERROR);
DEVICESTATUS_WRITE_PARCEL_WITH_RET(reply, Int32, devicestatusData.value, E_DEVICESTATUS_WRITE_PARCEL_ERROR);
DEVICESTATUS_HILOGD(DEVICESTATUS_MODULE_SERVICE, "Exit");
return ERR_OK;
}
} // Msdp
} // OHOS

View File

@ -0,0 +1,24 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//base/msdp/device_status/device_status.gni")
import("//build/test.gni")
group("devicestatussrv_test") {
testonly = true
deps = []
deps += [
"unittest:unittest",
"moduletest:moduletest",
]
}

View File

@ -0,0 +1,70 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//base/msdp/device_status/device_status.gni")
import("//build/test.gni")
module_output_path = "${device_status_part_name}/devicestatussrv"
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
"//utils/system/safwk/native/include",
"//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/rdb/include"
]
}
ohos_moduletest("test_devicestatus_module") {
module_out_path = module_output_path
sources = [ "src/devicestatus_module_test.cpp" ]
configs = [
"${device_status_utils_path}:devicestatus_utils_config",
":module_private_config",
]
deps = [
"${device_status_interfaces_path}/innerkits:devicestatus_client",
"${device_status_service_path}:devicestatus_service",
"//third_party/googletest:gtest_main",
"//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native",
"//drivers/peripheral/sensor/hal:hdi_sensor",
"//utils/native/base:utils",
]
external_deps = [
"ability_runtime:base",
"ability_runtime:want",
"ability_runtime:intent",
"bundle_framework:appexecfwk_base",
"bundle_framework:appexecfwk_core",
"eventhandler:libeventhandler",
"ces_standard:cesfwk_innerkits",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_standard:samgr_proxy",
]
}
group("moduletest") {
testonly = true
deps = []
deps += [
":test_devicestatus_module",
]
}

View File

@ -0,0 +1,37 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_SERVICE_TEST_H
#define DEVICESTATUS_SERVICE_TEST_H
#include <gtest/gtest.h>
#include "devicestatus_callback_stub.h"
#include "devicestatus_service.h"
namespace OHOS {
namespace Msdp {
class DevicestatusModuleTest : public testing::Test {
public:
class DevicestatusModuleTestCallback : public DevicestatusCallbackStub {
public:
DevicestatusModuleTestCallback() {};
virtual ~DevicestatusModuleTestCallback() {};
virtual void OnDevicestatusChanged(const DevicestatusDataUtils::DevicestatusData& devicestatusData) override;
};
};
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_SERVICE_TEST_H

View File

@ -0,0 +1,109 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_module_test.h"
#include <iostream>
#include <chrono>
#include <thread>
#include <gtest/gtest.h>
#include <if_system_ability_manager.h>
#include <ipc_skeleton.h>
#include <string_ex.h>
#include "devicestatus_common.h"
#include "devicestatus_client.h"
using namespace testing::ext;
using namespace OHOS::Msdp;
using namespace OHOS;
using namespace std;
void DevicestatusModuleTest::DevicestatusModuleTestCallback::OnDevicestatusChanged(const \
DevicestatusDataUtils::DevicestatusData& devicestatusData)
{
GTEST_LOG_(INFO) << "DevicestatusModuleTestCallback type: " << devicestatusData.type;
GTEST_LOG_(INFO) << "DevicestatusModuleTestCallback value: " << devicestatusData.value;
EXPECT_EQ(true, devicestatusData.type == DevicestatusDataUtils::DevicestatusType::TYPE_FINE_STILL && \
devicestatusData.value == DevicestatusDataUtils::DevicestatusValue::VALUE_ENTER) << \
"DevicestatusModuleTestCallback falied";
}
/**
* @tc.name: DevicestatusCallbackTest
* @tc.desc: test devicestatus callback in proxy
* @tc.type: FUNC
*/
HWTEST_F (DevicestatusModuleTest, DevicestatusCallbackTest, TestSize.Level0)
{
DevicestatusDataUtils::DevicestatusType type = DevicestatusDataUtils::DevicestatusType::TYPE_FINE_STILL;
auto& devicestatusClient = DevicestatusClient::GetInstance();
sptr<IdevicestatusCallback> cb = new DevicestatusModuleTestCallback();
GTEST_LOG_(INFO) << "Start register";
devicestatusClient.SubscribeCallback(type, cb);
GTEST_LOG_(INFO) << "Cancell register";
devicestatusClient.UnSubscribeCallback(type, cb);
}
/**
* @tc.name: GetDevicestatusDataTest
* @tc.desc: test get devicestatus data in proxy
* @tc.type: FUNC
*/
HWTEST_F (DevicestatusModuleTest, GetDevicestatusDataTest001, TestSize.Level0)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "GetDevicestatusDataTest001 Enter");
DevicestatusDataUtils::DevicestatusType type = DevicestatusDataUtils::DevicestatusType::TYPE_HIGH_STILL;
auto& devicestatusClient = DevicestatusClient::GetInstance();
DevicestatusDataUtils::DevicestatusData data = devicestatusClient.GetDevicestatusData(type);
GTEST_LOG_(INFO) << "type: " << data.type;
GTEST_LOG_(INFO) << "value: " << data.value;
EXPECT_EQ(true, data.type == DevicestatusDataUtils::DevicestatusType::TYPE_HIGH_STILL && \
data.value == DevicestatusDataUtils::DevicestatusValue::VALUE_INVALID) << "GetDevicestatusData falied";
}
/**
* @tc.name: GetDevicestatusDataTest
* @tc.desc: test get devicestatus data in proxy
* @tc.type: FUNC
*/
HWTEST_F (DevicestatusModuleTest, GetDevicestatusDataTest002, TestSize.Level0)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "GetDevicestatusDataTest002 Enter");
DevicestatusDataUtils::DevicestatusType type = DevicestatusDataUtils::DevicestatusType::TYPE_FINE_STILL;
auto& devicestatusClient = DevicestatusClient::GetInstance();
DevicestatusDataUtils::DevicestatusData data = devicestatusClient.GetDevicestatusData(type);
GTEST_LOG_(INFO) << "type: " << data.type;
GTEST_LOG_(INFO) << "value: " << data.value;
EXPECT_EQ(true, data.type == DevicestatusDataUtils::DevicestatusType::TYPE_FINE_STILL && \
data.value == DevicestatusDataUtils::DevicestatusValue::VALUE_INVALID) << "GetDevicestatusData falied";
}
/**
* @tc.name: GetDevicestatusDataTest
* @tc.desc: test get devicestatus data in proxy
* @tc.type: FUNC
*/
HWTEST_F (DevicestatusModuleTest, GetDevicestatusDataTest003, TestSize.Level0)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "GetDevicestatusDataTest003 Enter");
DevicestatusDataUtils::DevicestatusType type = DevicestatusDataUtils::DevicestatusType::TYPE_CAR_BLUETOOTH;
auto& devicestatusClient = DevicestatusClient::GetInstance();
DevicestatusDataUtils::DevicestatusData data = devicestatusClient.GetDevicestatusData(type);
GTEST_LOG_(INFO) << "type: " << data.type;
GTEST_LOG_(INFO) << "value: " << data.value;
EXPECT_EQ(true, data.type == DevicestatusDataUtils::DevicestatusType::TYPE_CAR_BLUETOOTH && \
data.value == DevicestatusDataUtils::DevicestatusValue::VALUE_INVALID) << "GetDevicestatusData falied";
}

View File

@ -0,0 +1,98 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//base/msdp/device_status/device_status.gni")
import("//build/test.gni")
module_output_path = "${device_status_part_name}/devicestatussrv"
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
"//utils/system/safwk/native/include",
"//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/rdb/include"
]
}
ohos_unittest("test_devicestatus_service") {
module_out_path = module_output_path
sources = [ "src/devicestatus_service_test.cpp" ]
configs = [
"${device_status_utils_path}:devicestatus_utils_config",
":module_private_config",
]
deps = [
"${device_status_interfaces_path}/innerkits:devicestatus_client",
"${device_status_service_path}:devicestatus_service",
"//third_party/googletest:gtest_main",
"//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native",
"//drivers/peripheral/sensor/hal:hdi_sensor",
"//utils/native/base:utils",
]
external_deps = [
"ability_runtime:base",
"ability_runtime:want",
"ability_runtime:intent",
"bundle_framework:appexecfwk_base",
"bundle_framework:appexecfwk_core",
"eventhandler:libeventhandler",
"ces_standard:cesfwk_innerkits",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_standard:samgr_proxy",
]
}
ohos_unittest("DevicestatusAgentTest") {
module_out_path = module_output_path
include_dirs = [
"//base/msdp/devicestatus/interfaces/innerkits/include",
]
sources = [ "src/devicestatus_agent_test.cpp" ]
configs = [
"${device_status_utils_path}:devicestatus_utils_config",
":module_private_config",
]
deps = [
"//base/msdp/device_status/frameworks/native/src:deviceagent",
"//base/msdp/device_status/services:devicestatus_service",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_standard:samgr_proxy",
]
}
group("unittest") {
testonly = true
deps = []
deps += [
":test_devicestatus_service",
":DevicestatusAgentTest"
]
}

View File

@ -0,0 +1,39 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_MSDP_DEVICESTATUS_AGENT_TEST_H
#define OHOS_MSDP_DEVICESTATUS_AGENT_TEST_H
#include <gtest/gtest.h>
#include "devicestatus_agent.h"
#include "devicestatus_data_utils.h"
namespace OHOS {
namespace Msdp {
class DevicestatusAgentTest : public testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
void SetUp();
void TearDown();
};
class DevicestatusAgentListener : public DeviceStatusAgent::DeviceStatusAgentEvent {
public:
virtual ~DevicestatusAgentListener() {};
bool OnEventResult(const DevicestatusDataUtils::DevicestatusData& devicestatusData) override;
};
} // namespace Msdp
} // namespace OHOS
#endif // OHOS_MSDP_DEVICESTATUS_AGENT_TEST_H

View File

@ -0,0 +1,37 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_SERVICE_TEST_H
#define DEVICESTATUS_SERVICE_TEST_H
#include <gtest/gtest.h>
#include "devicestatus_callback_stub.h"
#include "devicestatus_service.h"
namespace OHOS {
namespace Msdp {
class DevicestatusServiceTest : public testing::Test {
public:
class DevicestatusServiceTestCallback : public DevicestatusCallbackStub {
public:
DevicestatusServiceTestCallback() {};
virtual ~DevicestatusServiceTestCallback() {};
virtual void OnDevicestatusChanged(const DevicestatusDataUtils::DevicestatusData& devicestatusData) override;
};
};
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_SERVICE_TEST_H

View File

@ -0,0 +1,92 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_agent_test.h"
#include "devicestatus_common.h"
using namespace testing::ext;
using namespace OHOS::Msdp;
using namespace OHOS;
using namespace std;
static std::shared_ptr<DeviceStatusAgent> agent1_;
static std::shared_ptr<DeviceStatusAgent> agent2_;
void DevicestatusAgentTest::SetUpTestCase()
{
}
void DevicestatusAgentTest::TearDownTestCase()
{
}
void DevicestatusAgentTest::SetUp()
{
agent1_ = std::make_shared<DeviceStatusAgent>();
agent2_ = std::make_shared<DeviceStatusAgent>();
}
void DevicestatusAgentTest::TearDown()
{
}
bool DevicestatusAgentListener::OnEventResult(const DevicestatusDataUtils::DevicestatusData& devicestatusData)
{
GTEST_LOG_(INFO) << "agent type: " << devicestatusData.type;
GTEST_LOG_(INFO) << "agent value: " << devicestatusData.value;
EXPECT_EQ(true, devicestatusData.type == DevicestatusDataUtils::DevicestatusType::TYPE_LID_OPEN);
return true;
}
namespace {
/**
* @tc.name: DevicestatusAgentTest001
* @tc.desc: test devicestatus callback in proxy
* @tc.type: FUNC
*/
HWTEST_F (DevicestatusAgentTest, DevicestatusAgentTest001, TestSize.Level0)
{
GTEST_LOG_(INFO) << "DevicestatusAgentTest001 start";
std::shared_ptr<DevicestatusAgentListener> agentEvent1 =
std::make_shared<DevicestatusAgentListener>();
int ret = agent1_->SubscribeAgentEvent(DevicestatusDataUtils::DevicestatusType::TYPE_LID_OPEN, agentEvent1);
EXPECT_EQ(true, ret == ERR_OK);
sleep(10);
agent1_->UnSubscribeAgentEvent(DevicestatusDataUtils::DevicestatusType::TYPE_LID_OPEN);
GTEST_LOG_(INFO) << "DevicestatusAgentTest001 end";
}
/**
* @tc.name: DevicestatusAgentTest002
* @tc.desc: test devicestatus callback in proxy
* @tc.type: FUNC
*/
HWTEST_F (DevicestatusAgentTest, DevicestatusAgentTest002, TestSize.Level0)
{
GTEST_LOG_(INFO) << "DevicestatusAgentTest002 start";
std::shared_ptr<DevicestatusAgentListener> agentEvent1 =
std::make_shared<DevicestatusAgentListener>();
std::shared_ptr<DevicestatusAgentListener> agentEvent2 =
std::make_shared<DevicestatusAgentListener>();
int ret = agent1_->SubscribeAgentEvent(DevicestatusDataUtils::DevicestatusType::TYPE_LID_OPEN, agentEvent1);
ret = agent2_->SubscribeAgentEvent(DevicestatusDataUtils::DevicestatusType::TYPE_LID_OPEN, agentEvent2);
EXPECT_EQ(true, ret == ERR_OK);
sleep(10);
agent1_->UnSubscribeAgentEvent(DevicestatusDataUtils::DevicestatusType::TYPE_LID_OPEN);
agent2_->UnSubscribeAgentEvent(DevicestatusDataUtils::DevicestatusType::TYPE_LID_OPEN);
GTEST_LOG_(INFO) << "DevicestatusAgentTest002 end";
}
}

View File

@ -0,0 +1,109 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_service_test.h"
#include <iostream>
#include <chrono>
#include <thread>
#include <gtest/gtest.h>
#include <if_system_ability_manager.h>
#include <ipc_skeleton.h>
#include <string_ex.h>
#include "devicestatus_common.h"
#include "devicestatus_client.h"
using namespace testing::ext;
using namespace OHOS::Msdp;
using namespace OHOS;
using namespace std;
void DevicestatusServiceTest::DevicestatusServiceTestCallback::OnDevicestatusChanged(const \
DevicestatusDataUtils::DevicestatusData& devicestatusData)
{
GTEST_LOG_(INFO) << "DevicestatusServiceTestCallback type: " << devicestatusData.type;
GTEST_LOG_(INFO) << "DevicestatusServiceTestCallback value: " << devicestatusData.value;
EXPECT_EQ(true, devicestatusData.type == DevicestatusDataUtils::DevicestatusType::TYPE_FINE_STILL && \
devicestatusData.value == DevicestatusDataUtils::DevicestatusValue::VALUE_ENTER) << \
"DevicestatusServiceTestCallback falied";
}
/**
* @tc.name: DevicestatusCallbackTest
* @tc.desc: test devicestatus callback in proxy
* @tc.type: FUNC
*/
HWTEST_F (DevicestatusServiceTest, DevicestatusCallbackTest, TestSize.Level0)
{
DevicestatusDataUtils::DevicestatusType type = DevicestatusDataUtils::DevicestatusType::TYPE_FINE_STILL;
auto& devicestatusClient = DevicestatusClient::GetInstance();
sptr<IdevicestatusCallback> cb = new DevicestatusServiceTestCallback();
GTEST_LOG_(INFO) << "Start register";
devicestatusClient.SubscribeCallback(type, cb);
GTEST_LOG_(INFO) << "Cancell register";
devicestatusClient.UnSubscribeCallback(type, cb);
}
/**
* @tc.name: GetDevicestatusDataTest
* @tc.desc: test get devicestatus data in proxy
* @tc.type: FUNC
*/
HWTEST_F (DevicestatusServiceTest, GetDevicestatusDataTest001, TestSize.Level0)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "GetDevicestatusDataTest001 Enter");
DevicestatusDataUtils::DevicestatusType type = DevicestatusDataUtils::DevicestatusType::TYPE_HIGH_STILL;
auto& devicestatusClient = DevicestatusClient::GetInstance();
DevicestatusDataUtils::DevicestatusData data = devicestatusClient.GetDevicestatusData(type);
GTEST_LOG_(INFO) << "type: " << data.type;
GTEST_LOG_(INFO) << "value: " << data.value;
EXPECT_EQ(true, data.type == DevicestatusDataUtils::DevicestatusType::TYPE_HIGH_STILL && \
data.value == DevicestatusDataUtils::DevicestatusValue::VALUE_INVALID) << "GetDevicestatusData falied";
}
/**
* @tc.name: GetDevicestatusDataTest
* @tc.desc: test get devicestatus data in proxy
* @tc.type: FUNC
*/
HWTEST_F (DevicestatusServiceTest, GetDevicestatusDataTest002, TestSize.Level0)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "GetDevicestatusDataTest002 Enter");
DevicestatusDataUtils::DevicestatusType type = DevicestatusDataUtils::DevicestatusType::TYPE_FINE_STILL;
auto& devicestatusClient = DevicestatusClient::GetInstance();
DevicestatusDataUtils::DevicestatusData data = devicestatusClient.GetDevicestatusData(type);
GTEST_LOG_(INFO) << "type: " << data.type;
GTEST_LOG_(INFO) << "value: " << data.value;
EXPECT_EQ(true, data.type == DevicestatusDataUtils::DevicestatusType::TYPE_FINE_STILL && \
data.value == DevicestatusDataUtils::DevicestatusValue::VALUE_INVALID) << "GetDevicestatusData falied";
}
/**
* @tc.name: GetDevicestatusDataTest
* @tc.desc: test get devicestatus data in proxy
* @tc.type: FUNC
*/
HWTEST_F (DevicestatusServiceTest, GetDevicestatusDataTest003, TestSize.Level0)
{
DEVICESTATUS_HILOGI(DEVICESTATUS_MODULE_SERVICE, "GetDevicestatusDataTest003 Enter");
DevicestatusDataUtils::DevicestatusType type = DevicestatusDataUtils::DevicestatusType::TYPE_CAR_BLUETOOTH;
auto& devicestatusClient = DevicestatusClient::GetInstance();
DevicestatusDataUtils::DevicestatusData data = devicestatusClient.GetDevicestatusData(type);
GTEST_LOG_(INFO) << "type: " << data.type;
GTEST_LOG_(INFO) << "value: " << data.value;
EXPECT_EQ(true, data.type == DevicestatusDataUtils::DevicestatusType::TYPE_CAR_BLUETOOTH && \
data.value == DevicestatusDataUtils::DevicestatusValue::VALUE_INVALID) << "GetDevicestatusData falied";
}

12
test/BUILD.gn Normal file
View File

@ -0,0 +1,12 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

12
test/systemtest/BUILD.gn Normal file
View File

@ -0,0 +1,12 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

21
utils/BUILD.gn Normal file
View File

@ -0,0 +1,21 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//base/msdp/device_status/device_status.gni")
config("devicestatus_utils_config") {
include_dirs = [
"include",
"//utils/native/base/include",
]
}

View File

@ -0,0 +1,77 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_COMMON_H
#define DEVICESTATUS_COMMON_H
#include <cstdint>
#include <type_traits>
#include "devicestatus_hilog_wrapper.h"
#include "devicestatus_errors.h"
namespace OHOS {
namespace Msdp {
#define DEVICESTATUS_RETURN_IF_WITH_RET(cond, retval) if (cond) {return (retval);}
#define DEVICESTATUS_RETURN_IF(cond) if (cond) {return;}
#define DEVICESTATUS_RETURN_IF_WITH_LOG(cond, loginfo) \
do { \
if (cond) { \
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_COMMON, "%{public}s "#loginfo" ", __func__); \
return; \
} \
} while (0) \
#define DEVICESTATUS_READ_PARCEL_NO_RET(parcel, type, out) \
do { \
if (!(parcel).Read##type(out)) { \
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_COMMON, "%{public}s read "#out" failed", __func__); \
return; \
} \
} while (0) \
#define DEVICESTATUS_WRITE_PARCEL_NO_RET(parcel, type, data) \
do { \
if (!(parcel).Write##type(data)) { \
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_COMMON, "%{public}s write "#data" failed", __func__); \
return; \
} \
} while (0) \
#define DEVICESTATUS_READ_PARCEL_WITH_RET(parcel, type, out, retval) \
do { \
if (!(parcel).Read##type(out)) { \
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_COMMON, "%{public}s read "#out" failed", __func__); \
return (retval); \
} \
} while (0) \
#define DEVICESTATUS_WRITE_PARCEL_WITH_RET(parcel, type, data, retval) \
do { \
if (!(parcel).Write##type(data)) { \
DEVICESTATUS_HILOGE(DEVICESTATUS_MODULE_COMMON, "%{public}s write "#data" failed", __func__); \
return (retval); \
} \
} while (0)
template<typename E>
constexpr auto DevicestatusToUnderlying(E e) noexcept
{
return static_cast<std::underlying_type_t<E>>(e);
}
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_COMMON_H

View File

@ -0,0 +1,74 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_SINGLETON_H
#define DEVICESTATUS_SINGLETON_H
#include <mutex>
#include <memory>
#include <refbase.h>
#include "nocopyable.h"
namespace OHOS {
namespace Msdp {
#define DECLARE_DELAYED_SP_SINGLETON(MyClass) \
public: \
~MyClass(); \
private: \
friend DelayedSpSingleton<MyClass>; \
MyClass();
template<typename T>
class DelayedSpSingleton : public NoCopyable {
public:
static sptr<T> GetInstance();
static void DestroyInstance();
private:
static sptr<T> instance_;
static std::mutex mutex_;
};
template<typename T>
sptr<T> DelayedSpSingleton<T>::instance_ = nullptr;
template<typename T>
std::mutex DelayedSpSingleton<T>::mutex_;
template<typename T>
sptr<T> DelayedSpSingleton<T>::GetInstance()
{
if (!instance_) {
std::lock_guard<std::mutex> lock(mutex_);
if (instance_ == nullptr) {
instance_ = new T();
}
}
return instance_;
}
template<typename T>
void DelayedSpSingleton<T>::DestroyInstance()
{
std::lock_guard<std::mutex> lock(mutex_);
if (instance_) {
instance_.clear();
instance_ = nullptr;
}
}
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_SINGLETON_H

View File

@ -0,0 +1,48 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_ERRORS_H
#define DEVICESTATUS_ERRORS_H
#include <errors.h>
namespace OHOS {
namespace Msdp {
enum {
/**
* Module type: Devicestatus Service
*/
DEVICESTATUS_MODULE_TYPE_SERVICE = 0,
/**
* Module type: Devicestatus Kit
*/
DEVICESTATUS_MODULE_TYPE_KIT = 1
};
// offset of devicestatus error, only be used in this file.
constexpr ErrCode DEVICESTATUS_SERVICE_ERR_OFFSET = ErrCodeOffset(SUBSYS_MSDP, DEVICESTATUS_MODULE_TYPE_SERVICE);
enum {
E_DEVICESTATUS_WRITE_PARCEL_ERROR = DEVICESTATUS_SERVICE_ERR_OFFSET,
E_DEVICESTATUS_READ_PARCEL_ERROR,
E_DEVICESTATUS_GET_SYSTEM_ABILITY_MANAGER_FAILED,
E_DEVICESTATUS_GET_SERVICE_FAILED,
E_DEVICESTATUS_ADD_DEATH_RECIPIENT_FAILED,
E_DEVICESTATUS_INNER_ERR
};
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_ERRORS_H

View File

@ -0,0 +1,99 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_HILOG_WRAPPER_H
#define DEVICESTATUS_HILOG_WRAPPER_H
#define CONFIG_HILOG
#ifdef CONFIG_HILOG
#include "hilog/log.h"
namespace OHOS {
namespace Msdp {
#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__)
#define __FORMATED(fmt, ...) "[%{public}s] %{public}s# " fmt, __FILENAME__, __FUNCTION__, ##__VA_ARGS__
#ifdef DEVICESTATUS_HILOGF
#undef DEVICESTATUS_HILOGF
#endif
#ifdef DEVICESTATUS_HILOGE
#undef DEVICESTATUS_HILOGE
#endif
#ifdef DEVICESTATUS_HILOGW
#undef DEVICESTATUS_HILOGW
#endif
#ifdef DEVICESTATUS_HILOGI
#undef DEVICESTATUS_HILOGI
#endif
#ifdef DEVICESTATUS_HILOGD
#undef DEVICESTATUS_HILOGD
#endif
// param of log interface, such as DEVICESTATUS_HILOGF.
enum DevicestatusSubModule {
DEVICESTATUS_MODULE_INNERKIT = 0,
DEVICESTATUS_MODULE_SERVICE,
DEVICESTATUS_MODULE_JS_NAPI,
DEVICESTATUS_MODULE_COMMON,
DEVICESTATUS_MODULE_BUTT,
};
// 0xD002900: subsystem:Msdp module:Devicestatus, 8 bits reserved.
static constexpr unsigned int BASE_MSDP_DOMAIN_ID = 0xD002900;
enum DevicestatusDomainId {
DEVICESTATUS_INNERKIT_DOMAIN = BASE_MSDP_DOMAIN_ID + DEVICESTATUS_MODULE_INNERKIT,
DEVICESTATUS_SERVICE_DOMAIN,
DEVICESTATUS_JS_NAPI,
DEVICESTATUS_COMMON,
DEVICESTATUS_BUTT,
};
static constexpr OHOS::HiviewDFX::HiLogLabel DEVICESTATUS_LABEL[DEVICESTATUS_MODULE_BUTT] = {
{LOG_CORE, DEVICESTATUS_INNERKIT_DOMAIN, "DevicestatusClient"},
{LOG_CORE, DEVICESTATUS_SERVICE_DOMAIN, "DevicestatusService"},
{LOG_CORE, DEVICESTATUS_JS_NAPI, "DevicestatusJsNapi"},
{LOG_CORE, DEVICESTATUS_COMMON, "DevicestatusCommon"},
};
// In order to improve performance, do not check the module range.
// Besides, make sure module is less than DEVICESTATUS_MODULE_BUTT.
#define DEVICESTATUS_HILOGF(module, ...) \
(void)OHOS::HiviewDFX::HiLog::Fatal(DEVICESTATUS_LABEL[module], __FORMATED(__VA_ARGS__))
#define DEVICESTATUS_HILOGE(module, ...) \
(void)OHOS::HiviewDFX::HiLog::Error(DEVICESTATUS_LABEL[module], __FORMATED(__VA_ARGS__))
#define DEVICESTATUS_HILOGW(module, ...) \
(void)OHOS::HiviewDFX::HiLog::Warn(DEVICESTATUS_LABEL[module], __FORMATED(__VA_ARGS__))
#define DEVICESTATUS_HILOGI(module, ...) \
(void)OHOS::HiviewDFX::HiLog::Info(DEVICESTATUS_LABEL[module], __FORMATED(__VA_ARGS__))
#define DEVICESTATUS_HILOGD(module, ...) \
(void)OHOS::HiviewDFX::HiLog::Debug(DEVICESTATUS_LABEL[module], __FORMATED(__VA_ARGS__))
} // namespace Msdp
} // namespace OHOS
#else
#define DEVICESTATUS_HILOGF(...)
#define DEVICESTATUS_HILOGE(...)
#define DEVICESTATUS_HILOGW(...)
#define DEVICESTATUS_HILOGI(...)
#define DEVICESTATUS_HILOGD(...)
#endif // CONFIG_HILOG
#endif // DEVICESTATUS_HILOG_WRAPPER_H

View File

@ -0,0 +1,34 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DEVICESTATUS_PERMISSION_H
#define DEVICESTATUS_PERMISSION_H
#include <string>
#include "permission/permission_kit.h"
namespace OHOS {
namespace Msdp {
class DevicestatusPermission {
public:
/* check caller's permission by finding pid uid by system */
static bool CheckCallingPermission(const std::string &permissionName);
/* construct appIdInfo string */
static std::string FindAppIdInfo();
};
} // namespace Msdp
} // namespace OHOS
#endif // DEVICESTATUS_PERMISSION_H

View File

@ -0,0 +1,36 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "devicestatus_permission.h"
#include "ipc_skeleton.h"
namespace OHOS {
namespace Msdp {
bool DevicestatusPermission::CheckCallingPermission(const string &permissionName)
{
string appIdInfo = GetAppInfo();
int auth = Security::Permission::PermissionKit::CheckPermission(permissionName, appIdInfo);
return auth == Security::Permission::PermissionKit::GRANTED;
}
string DevicestatusPermission::GetAppInfo()
{
pid_t pid = IPCSkeleton::GetCallingPid();
uid_t uid = IPCSkeleton::GetCallingUid();
return Security::Permission::AppIdInfoHelper::CreateAppIdInfo(pid, uid);
}
} // namespace Msdp
} // namespace OHOS