connected tag service for communication.

Signed-off-by: knpingan <zhangxiuping@huawei.com>
This commit is contained in:
knpingan
2022-03-11 19:10:03 +08:00
parent 2c0eecb20c
commit 1fd501f0be
43 changed files with 2987 additions and 25 deletions
+177
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
Executable
+30
View File
@@ -0,0 +1,30 @@
<?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.
This is the configuration file template for OpenHarmony OSS Audit Tool, please copy it to your project root dir and modify it refer to OpenHarmony/tools_oat/README.
-->
<configuration>
<oatconfig>
<licensefile></licensefile>
<filefilterlist>
<filefilter name="defaultFilter" desc="Files that do not need to be scanned">
</filefilter>
<filefilter name="binaryFileTypePolicyFilter" desc="Filters for binary file policies" >
<filteritem type="filename" name="*.png|*.gif" desc="png and gif"/>
</filefilter>
</filefilterlist>
</oatconfig>
</configuration>
+43 -25
View File
@@ -1,37 +1,55 @@
# communication_nfc
# NFC<a name="EN-US_TOPIC_0000001133207781"></a>
#### 介绍
NFC英文全称Near Field Communication,近距离无线通信。提供NFC有源标签的读写能力。
- [Introduction](#section13587125816351)
- [Architecture](#section13587185873516)
- [Directory Structure](#section161941989596)
- [Constraints](#section119744591305)
- [Usage](#section1312121216216)
- [Repositories Involved](#section1371113476307)
#### 软件架构
软件架构说明
## Introduction<a name="section13587125816351"></a>
Near-field communication \(NFC\) is a non-contact identification and interconnection technology for short-distance wireless communication between mobile devices, consumer electronic products, PCs, and smart devices.
The NFC module provides connected tag reading and writing.
## Architecture<a name="section13587185873516"></a>
**Figure 1** NFC architecture<a name="fig4460722185514"></a>
#### 安装教程
![](figures/en-us_image_0000001086731550.gif)
1. xxxx
2. xxxx
3. xxxx
## Directory Structure<a name="section161941989596"></a>
#### 使用说明
The main code directory structure of Intelligent Soft Bus is as follows:
1. xxxx
2. xxxx
3. xxxx
```
/foundation/communication
├── interfaces # 接口代码
│ └── kits
│ └── native_cpp # 本地SDK库
│ └── connected_tag_base # NFC有源标签SDK实现
│ └── napi # native api
│ └── connected_tag # NFC有源标签native api
└── sa_profile # 服务属性声明
│ └── connected_tag # NFC有源标签服务属性声明
└── services # 子系统服务代码
└── connected_tag # NFC有源标签服务
├── etc # 系统服务配置
├── include # 头文件
└── src # 源文件
```
#### 参与贡献
## Constraints<a name="section119744591305"></a>
1. Fork 本仓库
2. 新建 Feat_xxx 分支
3. 提交代码
4. 新建 Pull Request
- Devices must has the connected tag chip.
## Usage<a name="section1312121216216"></a>
#### 特技
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com)
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
## Repositories Involved<a name="section1371113476307"></a>
hmf/communication/nfc
+64
View File
@@ -0,0 +1,64 @@
# NFC组件<a name="ZH-CN_TOPIC_0000001124412109"></a>
- [简介](#section11660541593)
- [系统架构](#section342962219551)
- [目录](#section161941989596)
- [约束](#section119744591305)
- [说明](#section1312121216216)
- [使用说明](#section129654513264)
- [相关仓](#section1371113476307)
## 简介<a name="section11660541593"></a>
近距离无线通信技术\(Near Field CommunicationNFC\) ,是一种非接触式识别和互联技术,可以在移动设备、消费类电子产品、PC和智能设备间进行近距离无线通信。
OpenHarmony中NFC服务提供有源标签读写业务能力。
## 系统架构<a name="section342962219551"></a>
**图 1** NFC组件架构图<a name="fig444313176464"></a>
![](figures/zh-cn_image_0000001124327253.png)
<a name="table1716174620235"></a>
<table><thead align="left"></thead>
<tbody></tbody>
</table>
## 目录<a name="section161941989596"></a>
```
/foundation/communication/nfc
├── interfaces # 接口代码
│ └── kits
│ └── native_cpp # 本地SDK库
│ └── connected_tag_base # NFC有源标签SDK实现
│ └── napi # native api
│ └── connected_tag # NFC有源标签native api
└── sa_profile # 服务属性声明
│ └── connected_tag # NFC有源标签服务属性声明
└── services # 子系统服务代码
└── connected_tag # NFC有源标签服务
├── etc # 系统服务配置
├── include # 头文件
└── src # 源文件
```
## 约束<a name="section119744591305"></a>
设备必须具备有源标签芯片,才能使用有源标签的读写服务。
## 说明<a name="section1312121216216"></a>
### 使用说明<a name="section129654513264"></a>
- 有源标签的读写
设备必须具备有源标签芯片,才能使用有源标签的读写服务,参考“js-apis-connectedTag.md”有源标签开发指南。
## 相关仓<a name="section1371113476307"></a>
hmf/communication/nfc
Executable
+81
View File
@@ -0,0 +1,81 @@
{
"name": "@ohos/communication_nfc",
"version": "3.1",
"description": "nfc service",
"homePage": "https://gitee.com/openharmony",
"license": "Apache License 2.0",
"repository": "https://gitee.com/openharmony/communication_nfc",
"domain": "os",
"language": "",
"publishAs": "code-segment",
"private": false,
"scripts": {},
"tags": [
"foundation"
],
"keywords": [
"communication",
"nfc"
],
"envs": [],
"dirs": [],
"author": {
"name": "",
"email": "",
"url": ""
},
"contributors": [
{
"name": "",
"email": "",
"url": ""
}
],
"segment": {
"destPath": "foundation/communication/nfc"
},
"component": {
"name": "nfc_connected_tag",
"subsystem": "communication",
"syscap": [
"SystemCapability.Communication.ConnectedTag"
],
"features": [],
"adapted_system_type": [
],
"rom": "",
"ram": "",
"deps": {
"components": [
"ipc",
"hiviewdfx_hilog_native"
],
"third_party": [
]
},
"build": {
"sub_component": [
"//foundation/communication/nfc/sa_profile/connected_tag:connected_tag_profile",
"//foundation/communication/nfc/interfaces/kits/native_cpp/connected_tag_base:connected_tag_base",
"//foundation/communication/nfc/services/connected_tag:nfc_connected_tag_service",
"//foundation/communication/nfc/interfaces/kits/native_cpp/napi/connected_tag:connectedtag"
],
"inner_kits": [
{
"type": "so",
"name": "//foundation/communication/nfc/interfaces/kits/native_cpp/connected_tag_base:connected_tag_base",
"header": {
"header_files": [
"connected_tag_impl.h"
],
"header_base": "//foundation/communication/nfc/interfaces/kits/native_cpp/connected_tag_base/include"
}
}
],
"test": [
]
},
"hisysevent_config": [
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

+56
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.
import("//build/ohos.gni")
import("//build/ohos_var.gni")
config("connected_tag_base_config") {
cflags_cc = [
"-fPIC",
"-Wno-unused-parameter",
"-Wunused-private-field",
]
include_dirs = [
"//utils/system/safwk/native/include",
"//foundation/communication/nfc/interfaces/kits/native_cpp/connected_tag_base/interfaces",
"//foundation/communication/nfc/interfaces/kits/native_cpp/connected_tag_base/include",
]
}
config("connected_tag_base_public_config") {
include_dirs = [
]
}
ohos_shared_library("connected_tag_base") {
configs = [ ":connected_tag_base_config" ]
public_configs = [ ":connected_tag_base_public_config" ]
sources = [
"src/connected_tag_impl.cpp",
"src/tag_session_proxy.cpp",
"src/connected_tag_callback_stub.cpp",
]
deps = [
"//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"samgr_standard:samgr_proxy",
]
subsystem_name = "communication"
part_name = "nfc_connected_tag"
}
@@ -0,0 +1,46 @@
/*
* 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_CONNECTED_TAG_CALLBACK_STUB_H
#define OHOS_CONNECTED_TAG_CALLBACK_STUB_H
#include "iremote_stub.h"
#include "iremote_object.h"
#include "iconnected_tag_callback.h"
#include <shared_mutex>
#include "error_code.h"
namespace OHOS {
namespace ConnectedTag {
class ConnectedTagCallBackStub : public IRemoteStub<IConnectedTagCallBack> {
public:
ConnectedTagCallBackStub();
virtual ~ConnectedTagCallBackStub();
static ConnectedTagCallBackStub& GetInstance();
ErrCode RegisterUserCallBack(const sptr<IConnectedTagCallBack> &callBack);
virtual int OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
void OnNotify(int nfcRfState) override;
private:
int RemoteOnNotify(MessageParcel &data, MessageParcel &reply);
sptr<IConnectedTagCallBack> callback_;
std::shared_mutex callbackMutex;
bool mRemoteDied;
};
} // namespace ConnectedTag
} // namespace OHOS
#endif
@@ -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 NAPI_CONNECTED_TAG_IMPL_H_
#define NAPI_CONNECTED_TAG_IMPL_H_
#include "tag_session_proxy.h"
#include "error_code.h"
#include "iconnected_tag.h"
#include "iconnected_tag_callback.h"
namespace OHOS {
namespace ConnectedTag {
class ConnectedTagImpl : public IConnectedTag {
public:
explicit ConnectedTagImpl();
virtual ~ConnectedTagImpl();
static ConnectedTagImpl& GetInstance();
ErrCode Init() override;
ErrCode Uninit() override;
ErrCode ReadNdefTag(std::string &response) override;
ErrCode WriteNdefTag(std::string data) override;
ErrCode RegListener(const sptr<IConnectedTagCallBack> &callback) override;
ErrCode UnregListener(const sptr<IConnectedTagCallBack> &callback) override;
private:
sptr<ITagSession> tagSessionProxy_;
};
} // namespace ConnectedTag
} // namespace OHOS
#endif /* NAPI_CONNECTED_TAG_IMPL_H_ */
@@ -0,0 +1,42 @@
/*
* 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 NAPI_ICONNECTED_TAG_H_
#define NAPI_ICONNECTED_TAG_H_
#include "iremote_object.h"
#include "error_code.h"
#include "iconnected_tag_callback.h"
namespace OHOS {
namespace ConnectedTag {
class IConnectedTag {
public:
virtual ~IConnectedTag() = default;
virtual ErrCode Init() = 0;
virtual ErrCode Uninit() = 0;
virtual ErrCode ReadNdefTag(std::string &response) = 0;
virtual ErrCode WriteNdefTag(std::string data) = 0;
virtual ErrCode RegListener(const sptr<IConnectedTagCallBack> &callback) = 0;
virtual ErrCode UnregListener(const sptr<IConnectedTagCallBack> &callback) = 0;
};
} // namespace ConnectedTag
} // namespace OHOS
#endif /* NAPI_ICONNECTED_TAG_H_ */
@@ -0,0 +1,29 @@
/*
* 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 NFC_ICONNECTED_TAG_CALLBACK_H
#define NFC_ICONNECTED_TAG_CALLBACK_H
#include <iremote_stub.h>
namespace OHOS {
namespace ConnectedTag {
class IConnectedTagCallBack : public IRemoteBroker {
public:
virtual void OnNotify(int nfcRfState) = 0;
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.connected_tag.IConnectedTagCallBack");
};
} // namespace ConnectedTag
} // namespace OHOS
#endif //NFC_ICONNECTED_TAG_CALLBACK_H
@@ -0,0 +1,83 @@
/*
* 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 NFC_LOG_H
#define NFC_LOG_H
#define CONFIG_HILOG
#ifdef CONFIG_HILOG
#include "hilog/log.h"
#ifdef HILOGF
#undef HILOGF
#endif
#ifdef HILOGE
#undef HILOGE
#endif
#ifdef HILOGW
#undef HILOGW
#endif
#ifdef HILOGI
#undef HILOGI
#endif
#ifdef HILOGD
#undef HILOGD
#endif
#ifndef NFC_LOG_DOMAIN
#define NFC_LOG_DOMAIN 0xD006000
#endif
#ifndef NFC_LOG_TAG
#define NFC_LOG_TAG "Nfc_Connected_Tag"
#endif
#ifdef LOG_LABEL
#undef LOG_LABEL
#endif
static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = {LOG_CORE, NFC_LOG_DOMAIN, NFC_LOG_TAG};
#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__)
#define HILOGF(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Fatal( \
LOG_LABEL, "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define HILOGE(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Error( \
LOG_LABEL, "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define HILOGW(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Warn( \
LOG_LABEL, "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define HILOGI(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Info( \
LOG_LABEL, "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define HILOGD(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Debug( \
LOG_LABEL, "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define HILOGF(...)
#define HILOGE(...)
#define HILOGW(...)
#define HILOGI(...)
#define HILOGD(...)
#endif // CONFIG_HILOG
#endif // NFC_LOG_H
@@ -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.
*/
#ifndef OHOS_NFC_TAG_SESSION_PROXY_H
#define OHOS_NFC_TAG_SESSION_PROXY_H
#include "i_tag_session.h"
#include <stdint.h>
#include "iremote_proxy.h"
namespace OHOS {
namespace ConnectedTag {
class TagSessionProxy : public IRemoteProxy<ITagSession>, public IRemoteObject::DeathRecipient {
public:
explicit TagSessionProxy(const sptr<IRemoteObject> &impl);
~TagSessionProxy();
ErrCode Init() override;
ErrCode Uninit() override;
ErrCode ReadNdefTag(std::string &response) override;
ErrCode WriteNdefTag(std::string data) override;
ErrCode RegListener(const sptr<IConnectedTagCallBack> &callback) override;
ErrCode UnregListener(const sptr<IConnectedTagCallBack> &callback) override;
/**
* @Description Handle remote object died event.
* @param remoteObject remote object.
*/
void OnRemoteDied(const wptr<IRemoteObject> &remoteObject) override;
private:
bool mRemoteDied;
};
} // namespace ConnectedTag
} // namespace OHOS
#endif
@@ -0,0 +1,29 @@
/*
* 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_NFC_ERRCODE_H
#define OHOS_NFC_ERRCODE_H
namespace OHOS {
namespace ConnectedTag {
/* Nfc errcode defines */
enum ErrCode {
NFC_OPT_SUCCESS = 0, /* successfully */
NFC_OPT_FAILED, /* failed */
NFC_OPT_NOT_SUPPORTED, /* not supported */
};
} // namespace ConnectedTag
} // namespace OHOS
#endif
@@ -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 OHOS_I_TAG_SESSION_H
#define OHOS_I_TAG_SESSION_H
#include "iremote_broker.h"
#include "error_code.h"
#include "iconnected_tag_callback.h"
namespace OHOS {
namespace ConnectedTag {
class ITagSession : public IRemoteBroker {
public:
virtual ~ITagSession() {}
virtual ErrCode Init() = 0;
virtual ErrCode Uninit() = 0;
virtual ErrCode ReadNdefTag(std::string &response) = 0;
virtual ErrCode WriteNdefTag(std::string data) = 0;
virtual ErrCode RegListener(const sptr<IConnectedTagCallBack> &callback) = 0;
virtual ErrCode UnregListener(const sptr<IConnectedTagCallBack> &callback) = 0;
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.nfc.INfcConnectedTagService");
};
} // namespace ConnectedTag
} // namespace OHOS
#endif
@@ -0,0 +1,29 @@
/*
* 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_IPC_CMD_H
#define OHOS_IPC_CMD_H
/* ------------connected tag module message define--------- */
#define NFC_SVR_CMD_INIT 0x1001
#define NFC_SVR_CMD_UNINIT 0x1002
#define NFC_SVR_CMD_READ_NDEF_TAG 0x1003
#define NFC_SVR_CMD_WRITE_NDEF_TAG 0x1004
#define CMD_ON_NOTIFY 0x2001
/* ---------Feature service ability id */
#define NFC_CONNECTED_TAG_ABILITY_ID 1140
#endif
@@ -0,0 +1,91 @@
/*
* 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 "connected_tag_callback_stub.h"
#include "ipc_cmd.h"
#include "error_code.h"
#include "log.h"
namespace OHOS {
namespace ConnectedTag {
ConnectedTagCallBackStub::ConnectedTagCallBackStub() : callback_(nullptr), mRemoteDied(false)
{}
ConnectedTagCallBackStub::~ConnectedTagCallBackStub()
{}
ConnectedTagCallBackStub& ConnectedTagCallBackStub::GetInstance()
{
static ConnectedTagCallBackStub sConnectedTagCallBackStub;
return sConnectedTagCallBackStub;
}
void ConnectedTagCallBackStub::OnNotify(int nfcRfState)
{
HILOGD("ConnectedTagCallBackStub::OnNotify");
if (callback_) {
callback_->OnNotify(nfcRfState);
}
}
int ConnectedTagCallBackStub::OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
HILOGD("ConnectedTagCallBackStub::OnRemoteRequest!");
if (mRemoteDied) {
HILOGE("Failed to `%{public}s`,Remote service is died!", __func__);
return NFC_OPT_FAILED;
}
int exception = data.ReadInt32();
if (exception) {
HILOGE("ConnectedTagCallBackStub::OnRemoteRequest, got exception: %{public}d!", exception);
return NFC_OPT_FAILED;
}
int ret = NFC_OPT_FAILED;
switch (code) {
case CMD_ON_NOTIFY: {
ret = RemoteOnNotify(data, reply);
break;
}
default: {
ret = IPCObjectStub::OnRemoteRequest(code, data, reply, option);
break;
}
}
return ret;
}
ErrCode ConnectedTagCallBackStub::RegisterUserCallBack(const sptr<IConnectedTagCallBack> &callBack)
{
std::shared_lock<std::shared_mutex> guard(callbackMutex);
if (callBack == nullptr) {
HILOGW("RegisterUserCallBack:callBack is nullptr!");
}
callback_ = callBack;
return NFC_OPT_SUCCESS;
}
int ConnectedTagCallBackStub::RemoteOnNotify(MessageParcel &data, MessageParcel &reply)
{
HILOGD("run %{public}s datasize %{public}zu", __func__, data.GetRawDataSize());
int state = data.ReadInt32();
std::shared_lock<std::shared_mutex> guard(callbackMutex);
if (callback_) {
callback_->OnNotify(state);
}
reply.WriteInt32(NFC_OPT_SUCCESS); /* Reply 0 to indicate that no exception occurs. */
return NFC_OPT_SUCCESS;
}
} // namespace ConnectedTag
} // namespace OHOS
@@ -0,0 +1,80 @@
/*
* 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 "connected_tag_impl.h"
#include "iservice_registry.h"
#include "ipc_cmd.h"
#include "log.h"
namespace OHOS {
namespace ConnectedTag {
ConnectedTagImpl::ConnectedTagImpl()
{
HILOGI("ConnectedTagImpl() in");
sptr<ISystemAbilityManager> sa_mgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sa_mgr == nullptr) {
HILOGE("failed to get SystemAbilityManager");
return;
}
sptr<IRemoteObject> object = sa_mgr->GetSystemAbility(NFC_CONNECTED_TAG_ABILITY_ID);
if (object == nullptr) {
HILOGE("failed to get connected tag SERVICE");
return;
}
tagSessionProxy_ = iface_cast<ITagSession>(object);
if (tagSessionProxy_ == nullptr) {
tagSessionProxy_ = new (std::nothrow) TagSessionProxy(object);
}
if (tagSessionProxy_ == nullptr) {
HILOGE("TagSessionProxy init failed!");
}
}
ConnectedTagImpl::~ConnectedTagImpl()
{
}
ConnectedTagImpl& ConnectedTagImpl::GetInstance()
{
static ConnectedTagImpl tagImplSingleton;
return tagImplSingleton;
}
ErrCode ConnectedTagImpl::Init()
{
return tagSessionProxy_->Init();
}
ErrCode ConnectedTagImpl::Uninit()
{
return tagSessionProxy_->Uninit();
}
ErrCode ConnectedTagImpl::ReadNdefTag(std::string &response)
{
return tagSessionProxy_->ReadNdefTag(response);
}
ErrCode ConnectedTagImpl::WriteNdefTag(std::string data)
{
return tagSessionProxy_->WriteNdefTag(data);
}
ErrCode ConnectedTagImpl::RegListener(const sptr<IConnectedTagCallBack> &callback)
{
return tagSessionProxy_->RegListener(callback);
}
ErrCode ConnectedTagImpl::UnregListener(const sptr<IConnectedTagCallBack> &callback)
{
return tagSessionProxy_->UnregListener(callback);
}
} // namespace ConnectedTag
} // namespace OHOS
@@ -0,0 +1,149 @@
/*
* 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 <stdint.h>
#include <string>
#include "tag_session_proxy.h"
#include "log.h"
#include "ipc_cmd.h"
#include "connected_tag_callback_stub.h"
namespace OHOS {
namespace ConnectedTag {
TagSessionProxy::TagSessionProxy(const sptr<IRemoteObject> &impl) : IRemoteProxy<ITagSession>(impl), mRemoteDied(false)
{
HILOGI("TagSessionProxy() in!");
if (impl) {
if ((impl->IsProxyObject()) && (!impl->AddDeathRecipient(this))) {
HILOGD("AddDeathRecipient!");
} else {
HILOGW("no recipient!");
}
}
}
TagSessionProxy::~TagSessionProxy()
{
}
ErrCode TagSessionProxy::Init()
{
if (mRemoteDied) {
HILOGD("failed to `%{public}s`,remote service is died!", __func__);
return NFC_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
data.WriteInt32(NFC_OPT_SUCCESS);
int error = Remote()->SendRequest(NFC_SVR_CMD_INIT, data, reply, option);
if (error != ERR_NONE) {
HILOGE("Init failed, error code is %{public}d", error);
return NFC_OPT_FAILED;
}
int exception = reply.ReadInt32();
if (exception) {
return NFC_OPT_FAILED;
}
return ErrCode(reply.ReadInt32());
}
ErrCode TagSessionProxy::Uninit()
{
if (mRemoteDied) {
HILOGD("failed to `%{public}s`,remote service is died!", __func__);
return NFC_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
data.WriteInt32(NFC_OPT_SUCCESS);
int error = Remote()->SendRequest(NFC_SVR_CMD_UNINIT, data, reply, option);
if (error != ERR_NONE) {
HILOGE("Uninit failed, error code is %{public}d", error);
return NFC_OPT_FAILED;
}
int exception = reply.ReadInt32();
if (exception) {
return NFC_OPT_FAILED;
}
return ErrCode(reply.ReadInt32());
}
ErrCode TagSessionProxy::ReadNdefTag(std::string &response)
{
if (mRemoteDied) {
HILOGD("failed to `%{public}s`,remote service is died!", __func__);
return NFC_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
data.WriteInt32(NFC_OPT_SUCCESS);
int error = Remote()->SendRequest(NFC_SVR_CMD_READ_NDEF_TAG, data, reply, option);
if (error != ERR_NONE) {
HILOGE("ReadNdefTag failed, error code is %{public}d", error);
return NFC_OPT_FAILED;
}
int exception = reply.ReadInt32();
if (exception) {
return NFC_OPT_FAILED;
}
response = reply.ReadString();
return ErrCode(NFC_OPT_SUCCESS);
}
ErrCode TagSessionProxy::WriteNdefTag(std::string tagData)
{
if (mRemoteDied) {
HILOGD("failed to `%{public}s`,remote service is died!", __func__);
return NFC_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
data.WriteInt32(NFC_OPT_SUCCESS);
data.WriteString(tagData);
HILOGE("TagSessionProxy WriteNdefTag tagData is %{public}s", tagData.c_str());
int error = Remote()->SendRequest(NFC_SVR_CMD_WRITE_NDEF_TAG, data, reply, option);
if (error != ERR_NONE) {
HILOGE("WriteNdefTag failed,error code is %{public}d", error);
return NFC_OPT_FAILED;
}
int exception = reply.ReadInt32();
if (exception) {
return NFC_OPT_FAILED;
}
return ErrCode(reply.ReadInt32());
}
ErrCode TagSessionProxy::RegListener(const sptr<IConnectedTagCallBack> &callback)
{
return OHOS::ConnectedTag::ConnectedTagCallBackStub::GetInstance().RegisterUserCallBack(callback);
}
ErrCode TagSessionProxy::UnregListener(const sptr<IConnectedTagCallBack> &callback)
{
return OHOS::ConnectedTag::ConnectedTagCallBackStub::GetInstance().RegisterUserCallBack(nullptr);
}
void TagSessionProxy::OnRemoteDied(const wptr<IRemoteObject> &remoteObject)
{
HILOGD("Remote service is died!");
mRemoteDied = true;
}
} // namespace ConnectedTag
} // namespace OHOS
+50
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("//build/ohos.gni")
ohos_shared_library("connectedtag") {
install_enable = true
include_dirs = [
"//third_party/node/src",
"//native_engine",
"//utils/native/base/include",
"//utils/system/safwk/native/include",
"//foundation/communication/nfc/interfaces/kits/native_cpp/connected_tag_base/include",
"//foundation/communication/nfc/interfaces/kits/native_cpp/connected_tag_base/interfaces",
"//base/hiviewdfx/hilog/interfaces/native/innerkits/include",
"//base/notification/ces_standard/frameworks/core/include",
]
sources = [
"nfc_napi_adapter.cpp",
"nfc_napi_event.cpp",
"nfc_napi_entry.cpp",
"nfc_napi_utils.cpp",
]
deps = [
"//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog",
"//base/notification/ces_standard/frameworks/core:cesfwk_core",
"//base/notification/ces_standard/frameworks/native:cesfwk_innerkits",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/ace/napi:ace_napi",
"//foundation/communication/nfc/interfaces/kits/native_cpp/connected_tag_base:connected_tag_base",
"//utils/native/base:utils",
]
external_deps = [ "ipc:ipc_core" ]
relative_install_dir = "module"
part_name = "nfc_connected_tag"
subsystem_name = "communication"
}
@@ -0,0 +1,108 @@
/*
* 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 "nfc_napi_adapter.h"
#include "error_code.h"
#include "connected_tag_impl.h"
#include "log.h"
#include <vector>
#include <functional>
namespace OHOS {
namespace ConnectedTag {
std::string g_writtenNdefData = "";
napi_value Init(napi_env env, napi_callback_info info)
{
TRACE_FUNC_CALL;
ConnectedTagImpl connectedTagPtr = OHOS::ConnectedTag::ConnectedTagImpl::GetInstance();
ErrCode ret = connectedTagPtr.Init();
napi_value result;
napi_get_boolean(env, ret == NFC_OPT_SUCCESS, &result);
return result;
}
napi_value Uninit(napi_env env, napi_callback_info info)
{
TRACE_FUNC_CALL;
ConnectedTagImpl connectedTagPtr = OHOS::ConnectedTag::ConnectedTagImpl::GetInstance();
ErrCode ret = connectedTagPtr.Uninit();
napi_value result;
napi_get_boolean(env, ret == NFC_OPT_SUCCESS, &result);
return result;
}
napi_value ReadNdefTag(napi_env env, napi_callback_info info)
{
TRACE_FUNC_CALL;
size_t argc = 2;
napi_value argv[argc];
napi_value thisVar = nullptr;
void *data = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data));
HILOGI("ReadNdefTag argc = %{public}d", argc);
ReadAsyncContext *asyncContext = new ReadAsyncContext(env);
napi_create_string_latin1(env, "readNdefTag", NAPI_AUTO_LENGTH, &asyncContext->resourceName);
asyncContext->executeFunc = [&](void* data) -> void {
ReadAsyncContext *context = static_cast<ReadAsyncContext *>(data);
TRACE_FUNC_CALL_NAME("connectedTagPtr->ReadNdefTag");
ConnectedTagImpl connectedTagPtr = OHOS::ConnectedTag::ConnectedTagImpl::GetInstance();
context->errorCode = connectedTagPtr.ReadNdefTag(context->respNdefData);
HILOGI("ReadNdefTag end errorCode = %{public}d", context->errorCode);
};
asyncContext->completeFunc = [&](void* data) -> void {
ReadAsyncContext *context = static_cast<ReadAsyncContext *>(data);
napi_create_string_utf8(context->env, context->respNdefData.c_str(), NAPI_AUTO_LENGTH, &context->result);
HILOGI("ReadNdefTag respNdefData=%{public}s, len = %{public}d",
context->respNdefData.c_str(), context->respNdefData.length());
};
size_t nonCallbackArgNum = 0;
return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum);
}
napi_value WriteNdefTag(napi_env env, napi_callback_info info)
{
TRACE_FUNC_CALL;
size_t argc = 2;
napi_value argv[argc];
napi_value thisVar = nullptr;
void *data = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data));
g_writtenNdefData = "";
ParseString(env, g_writtenNdefData, argv[0]);
HILOGI("WriteNdefTag argc = %{public}d, data=%{public}s, len = %{public}d", argc,
g_writtenNdefData.c_str(), g_writtenNdefData.length());
WriteAsyncContext *asyncContext = new WriteAsyncContext(env);
napi_create_string_latin1(env, "writeNdefTag", NAPI_AUTO_LENGTH, &asyncContext->resourceName);
asyncContext->executeFunc = [&](void* data) -> void {
WriteAsyncContext *context = static_cast<WriteAsyncContext *>(data);
TRACE_FUNC_CALL_NAME("connectedTagPtr->WriteNdefTag");
ConnectedTagImpl connectedTagPtr = OHOS::ConnectedTag::ConnectedTagImpl::GetInstance();
HILOGI("WriteNdefTag start ndefData = %{public}s", g_writtenNdefData.c_str());
context->errorCode = connectedTagPtr.WriteNdefTag(g_writtenNdefData);
HILOGI("WriteNdefTag end errorCode = %{public}d", context->errorCode);
};
size_t nonCallbackArgNum = 1;
return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum);
}
} // namespace ConnectedTag
} // namespace OHOS
@@ -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.
*/
#ifndef NFC_NAPI_ADAPTER_H_
#define NFC_NAPI_ADAPTER_H_
#include "nfc_napi_utils.h"
namespace OHOS {
namespace ConnectedTag {
napi_value Init(napi_env env, napi_callback_info info);
napi_value Uninit(napi_env env, napi_callback_info info);
napi_value ReadNdefTag(napi_env env, napi_callback_info info);
napi_value WriteNdefTag(napi_env env, napi_callback_info info);
class ReadAsyncContext : public AsyncContext {
public:
std::string respNdefData;
ReadAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) :
AsyncContext(env, work, deferred){}
ReadAsyncContext() = delete;
virtual ~ReadAsyncContext(){}
};
class WriteAsyncContext : public AsyncContext {
public:
WriteAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) :
AsyncContext(env, work, deferred){}
WriteAsyncContext() = delete;
virtual ~WriteAsyncContext(){}
};
} // namespace ConnectedTag
} // namespace OHOS
#endif
@@ -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.
*/
#include "nfc_napi_adapter.h"
#include "nfc_napi_event.h"
#include "log.h"
namespace OHOS {
namespace ConnectedTag {
/*
* Module initialization function
*/
static napi_value InitJs(napi_env env, napi_value exports)
{
HILOGI("Init, nfc_napi_entry");
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("init", Init),
DECLARE_NAPI_FUNCTION("uninit", Uninit),
DECLARE_NAPI_FUNCTION("readNdefTag", ReadNdefTag),
DECLARE_NAPI_FUNCTION("writeNdefTag", WriteNdefTag),
DECLARE_NAPI_FUNCTION("on", On),
DECLARE_NAPI_FUNCTION("off", Off),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc));
return exports;
}
static napi_module nfcConnectedTagModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = NULL,
.nm_register_func = InitJs,
.nm_modname = "connectedTag",
.nm_priv = ((void *)0),
.reserved = { 0 }
};
extern "C" __attribute__((constructor)) void RegisterModule(void)
{
napi_module_register(&nfcConnectedTagModule);
}
} // namespace ConnectedTag
} // namespace OHOS
@@ -0,0 +1,289 @@
/*
* 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 "nfc_napi_event.h"
#include <uv.h>
#include "nfc_napi_utils.h"
#include "log.h"
#include "iconnected_tag_callback.h"
#include "connected_tag_impl.h"
namespace OHOS {
namespace ConnectedTag {
const std::string EVENT_NOTIFY = "notify";
static std::set<std::string> g_supportEventList = {
EVENT_NOTIFY,
};
bool EventRegister::isEventRegistered = false;
void NapiEvent::EventNotify(AsyncEventData *asyncEvent)
{
HILOGI("Enter nfc event notify");
if (asyncEvent == nullptr) {
HILOGE("asyncEvent is null.");
return;
}
uv_loop_s* loop = nullptr;
napi_get_uv_event_loop(asyncEvent->env, &loop);
uv_work_t* work = new uv_work_t;
if (work == nullptr) {
HILOGE("uv_work_t work is null.");
delete asyncEvent;
asyncEvent = nullptr;
return;
}
HILOGI("Get the event loop, napi_env: %{public}p", asyncEvent->env);
work->data = asyncEvent;
uv_queue_work(
loop,
work,
[](uv_work_t* work) {},
[](uv_work_t* work, int status) {
AsyncEventData *asyncData = static_cast<AsyncEventData*>(work->data);
if (asyncData == nullptr) {
HILOGE("asyncData is null.");
return;
}
HILOGI("Napi event uv_queue_work, env: %{public}p, status: %{public}d", asyncData->env, status);
napi_handle_scope scope = nullptr;
napi_open_handle_scope(asyncData->env, &scope);
if (scope == nullptr) {
HILOGE("scope is nullptr");
napi_close_handle_scope(asyncData->env, scope);
return;
}
napi_value undefine;
napi_get_undefined(asyncData->env, &undefine);
napi_value handler = nullptr;
napi_get_reference_value(asyncData->env, asyncData->callbackRef, &handler);
HILOGI("Push event to js, env: %{public}p, ref : %{public}p", asyncData->env, &asyncData->callbackRef);
if (napi_call_function(asyncData->env, nullptr, handler, 1, &asyncData->jsEvent, &undefine) != napi_ok) {
HILOGE("Report event to Js failed");
}
napi_close_handle_scope(asyncData->env, scope);
if (asyncData != nullptr) {
delete asyncData;
asyncData = nullptr;
}
delete work;
work = nullptr;
}
);
}
bool NapiEvent::CheckIsRegister(const std::string& type)
{
return g_eventRegisterInfo.find(type) != g_eventRegisterInfo.end();
}
class NfcListenerEvent : public IConnectedTagCallBack, public NapiEvent {
public:
NfcListenerEvent() {
}
virtual ~NfcListenerEvent() {
}
public:
void OnNotify(int nfcRfState) override {
HILOGI("OnNotify rcvd nfcRfState: %{public}d", nfcRfState);
CheckAndNotify(EVENT_NOTIFY, nfcRfState);
}
OHOS::sptr<OHOS::IRemoteObject> AsObject() override {
return nullptr;
}
};
sptr<NfcListenerEvent> nfcListenerEvent =
sptr<NfcListenerEvent>(new (std::nothrow) NfcListenerEvent());
napi_value On(napi_env env, napi_callback_info cbinfo) {
TRACE_FUNC_CALL;
size_t requireArgc = 2;
size_t argc = 2;
napi_value argv[2] = {0};
napi_value thisVar = 0;
napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, nullptr);
napi_valuetype eventName = napi_undefined;
napi_typeof(env, argv[0], &eventName);
napi_valuetype handler = napi_undefined;
napi_typeof(env, argv[1], &handler);
if (argc != requireArgc || eventName != napi_string || handler != napi_function)
{
HILOGE("On args invalid, failed!");
napi_value result;
napi_get_boolean(env, false, &result);
return result;
}
char type[64] = {0};
size_t typeLen = 0;
napi_get_value_string_utf8(env, argv[0], type, sizeof(type), &typeLen);
EventRegister::GetInstance().Register(env, type, argv[1]);
napi_value result = nullptr;
napi_get_undefined(env, &result);
return result;
}
napi_value Off(napi_env env, napi_callback_info cbinfo) {
TRACE_FUNC_CALL;
size_t requireArgc = 1;
size_t requireArgcWithCb = 2;
size_t argc = 2;
napi_value argv[2] = {0};
napi_value thisVar = 0;
napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, nullptr);
napi_valuetype eventName = napi_undefined;
napi_typeof(env, argv[0], &eventName);
if ((argc != requireArgc && argc != requireArgcWithCb) || eventName != napi_string)
{
HILOGE("On args invalid, failed!");
napi_value result;
napi_get_boolean(env, false, &result);
return result;
}
if (argc == requireArgcWithCb)
{
napi_valuetype handler = napi_undefined;
napi_typeof(env, argv[1], &handler);
if (handler != napi_function)
{
HILOGE("On args invalid napi_function, failed!");
napi_value result;
napi_get_boolean(env, false, &result);
return result;
}
}
char type[64] = {0};
size_t typeLen = 0;
napi_get_value_string_utf8(env, argv[0], type, sizeof(type), &typeLen);
EventRegister::GetInstance().Unregister(env, type, argc >= requireArgcWithCb ? argv[1] : nullptr);
napi_value result = nullptr;
napi_get_undefined(env, &result);
return result;
}
ErrCode EventRegister::RegisterNfcEvents()
{
ConnectedTagImpl connectedTag = OHOS::ConnectedTag::ConnectedTagImpl::GetInstance();
ErrCode ret = connectedTag.RegListener(nfcListenerEvent);
if (ret != NFC_OPT_SUCCESS) {
HILOGE("RegisterNfcEvents nfcListenerEvent failed!");
return ret;
}
return ret;
}
EventRegister& EventRegister::GetInstance()
{
static EventRegister inst;
return inst;
}
bool EventRegister::IsEventSupport(const std::string& type)
{
return g_supportEventList.find(type) != g_supportEventList.end();
}
void EventRegister::Register(const napi_env& env, const std::string& type, napi_value handler)
{
HILOGI("Register event: %{public}s, env: %{public}p", type.c_str(), env);
if (!IsEventSupport(type)) {
HILOGE("Register type error or not support!");
return;
}
std::unique_lock<std::shared_mutex> guard(g_regInfoMutex);
if (!isEventRegistered) {
if (RegisterNfcEvents() != NFC_OPT_SUCCESS) {
return;
}
isEventRegistered = true;
}
napi_ref handlerRef = nullptr;
napi_create_reference(env, handler, 1, &handlerRef);
RegObj regObj(env, handlerRef);
auto iter = g_eventRegisterInfo.find(type);
if (iter == g_eventRegisterInfo.end()) {
g_eventRegisterInfo[type] = std::vector<RegObj>{regObj};
} else {
iter->second.emplace_back(regObj);
}
}
void EventRegister::DeleteRegisterObj(std::vector<RegObj>& vecRegObjs, napi_value& handler)
{
auto iter = vecRegObjs.begin();
for (; iter != vecRegObjs.end();) {
napi_value handlerTemp = nullptr;
napi_get_reference_value(iter->m_regEnv, iter->m_regHanderRef, &handlerTemp);
bool isEqual = false;
napi_strict_equals(iter->m_regEnv, handlerTemp, handler, &isEqual);
if (isEqual) {
napi_delete_reference(iter->m_regEnv, iter->m_regHanderRef);
HILOGI("Delete register object ref.");
iter = vecRegObjs.erase(iter);
} else {
++iter;
}
}
}
void EventRegister::DeleteAllRegisterObj(std::vector<RegObj>& vecRegObjs)
{
for (auto& each : vecRegObjs) {
napi_delete_reference(each.m_regEnv, each.m_regHanderRef);
}
vecRegObjs.clear();
}
void EventRegister::Unregister(const napi_env& env, const std::string& type, napi_value handler)
{
HILOGI("Unregister event: %{public}s, env: %{public}p", type.c_str(), env);
if (!IsEventSupport(type)) {
HILOGE("Unregister type error or not support!");
return;
}
std::unique_lock<std::shared_mutex> guard(g_regInfoMutex);
auto iter = g_eventRegisterInfo.find(type);
if (iter == g_eventRegisterInfo.end()) {
HILOGE("Unregister type not registered!");
return;
}
if (handler != nullptr) {
DeleteRegisterObj(iter->second, handler);
} else {
HILOGW("All callback is unsubscribe for event: %{public}s", type.c_str());
DeleteAllRegisterObj(iter->second);
}
if (iter->second.empty()) {
g_eventRegisterInfo.erase(iter);
}
}
} // namespace ConnectedTag
} // namespace OHOS
@@ -0,0 +1,117 @@
/*
* 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 NFC_NAPI_EVENT_H_
#define NFC_NAPI_EVENT_H_
#include <string>
#include <set>
#include <map>
#include <vector>
#include <shared_mutex>
#include "napi/native_api.h"
#include "error_code.h"
namespace OHOS {
namespace ConnectedTag {
class AsyncEventData {
public:
napi_env env;
napi_ref callbackRef;
napi_value jsEvent;
explicit AsyncEventData(napi_env e, napi_ref r, napi_value v) {
env = e;
callbackRef = r;
jsEvent = v;
}
AsyncEventData() = delete;
virtual ~AsyncEventData() {
}
};
class RegObj {
public:
RegObj() : m_regEnv(0), m_regHanderRef(nullptr) {
}
explicit RegObj(const napi_env& env, const napi_ref& ref) {
m_regEnv = env;
m_regHanderRef = ref;
}
~RegObj() {
}
napi_env m_regEnv;
napi_ref m_regHanderRef;
};
static std::shared_mutex g_regInfoMutex;
static std::map<std::string, std::vector<RegObj>> g_eventRegisterInfo;
class NapiEvent {
public:
bool CheckIsRegister(const std::string& type);
void EventNotify(AsyncEventData *asyncEvent);
template<typename T>
void CheckAndNotify(const std::string& type, const T& obj) {
std::shared_lock<std::shared_mutex> guard(g_regInfoMutex);
if (!CheckIsRegister(type)) {
return;
}
std::vector<RegObj>& vecObj = g_eventRegisterInfo[type];
for (auto& each : vecObj) {
napi_value result;
napi_create_int32(each.m_regEnv, obj, &result);
AsyncEventData *asyncEvent = new AsyncEventData(each.m_regEnv, each.m_regHanderRef, result);
if (asyncEvent == nullptr) {
return;
}
EventNotify(asyncEvent);
}
}
};
class EventRegister {
public:
EventRegister() {
}
~EventRegister() {
}
static EventRegister& GetInstance();
void Register(const napi_env& env, const std::string& type, napi_value handler);
void Unregister(const napi_env& env, const std::string& type, napi_value handler);
private:
ErrCode RegisterNfcEvents();
bool IsEventSupport(const std::string& type);
void DeleteRegisterObj(std::vector<RegObj>& vecRegObjs, napi_value& handler);
void DeleteAllRegisterObj(std::vector<RegObj>& vecRegObjs);
static bool isEventRegistered;
};
napi_value On(napi_env env, napi_callback_info cbinfo);
napi_value Off(napi_env env, napi_callback_info cbinfo);
} // namespace ConnectedTag
} // namespace OHOS
#endif
@@ -0,0 +1,308 @@
/*
* 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 "nfc_napi_utils.h"
#include "securec.h"
#include "log.h"
namespace OHOS {
namespace ConnectedTag {
TraceFuncCall::TraceFuncCall(const std::string funcName): m_funcName(funcName)
{
if (m_isTrace) {
m_startTime = std::chrono::steady_clock::now();
HILOGD("Call func: %{public}s (start)", m_funcName.c_str());
}
}
TraceFuncCall::~TraceFuncCall()
{
if (m_isTrace) {
auto us = std::chrono::duration_cast<std::chrono::microseconds>
(std::chrono::steady_clock::now() - m_startTime).count();
constexpr int usForPerMs = 1000;
HILOGD("Call func: %{public}s (end), time cost:%{public}lldus, %{public}lldms",
m_funcName.c_str(), us, us / usForPerMs);
}
}
napi_value UndefinedNapiValue(const napi_env& env)
{
napi_value result;
napi_get_undefined(env, &result);
return result;
}
napi_value JsObjectToInt(const napi_env& env, const napi_value& object, const char* fieldStr, int& fieldRef)
{
bool hasProperty = false;
NAPI_CALL(env, napi_has_named_property(env, object, fieldStr, &hasProperty));
if (hasProperty) {
napi_value field;
napi_valuetype valueType;
napi_get_named_property(env, object, fieldStr, &field);
NAPI_CALL(env, napi_typeof(env, field, &valueType));
NAPI_ASSERT(env, valueType == napi_number, "Wrong argument type. Number expected.");
napi_get_value_int32(env, field, &fieldRef);
} else {
HILOGW("Js to int no property: %{public}s", fieldStr);
}
return UndefinedNapiValue(env);
}
napi_value JsObjectToBool(const napi_env& env, const napi_value& object, const char* fieldStr, bool& fieldRef)
{
bool hasProperty = false;
NAPI_CALL(env, napi_has_named_property(env, object, fieldStr, &hasProperty));
if (hasProperty) {
napi_value field;
napi_valuetype valueType;
napi_get_named_property(env, object, fieldStr, &field);
NAPI_CALL(env, napi_typeof(env, field, &valueType));
NAPI_ASSERT(env, valueType == napi_boolean, "Wrong argument type. Bool expected.");
napi_get_value_bool(env, field, &fieldRef);
} else {
HILOGW("Js to bool no property: %{public}s", fieldStr);
}
return UndefinedNapiValue(env);
}
napi_status SetValueUtf8String(const napi_env& env, const char* fieldStr, const char* str, napi_value& result)
{
napi_value value;
napi_status status = napi_create_string_utf8(env, str, NAPI_AUTO_LENGTH, &value);
if (status != napi_ok) {
HILOGE("Set value create utf8 string error! field: %{public}s", fieldStr);
return status;
}
status = napi_set_named_property(env, result, fieldStr, value);
if (status != napi_ok) {
HILOGE("Set utf8 string named property error! field: %{public}s", fieldStr);
}
return status;
}
napi_status SetValueInt32(const napi_env& env, const char* fieldStr, const int intValue, napi_value& result)
{
napi_value value;
napi_status status = napi_create_int32(env, intValue, &value);
if (status != napi_ok) {
HILOGE("Set value create int32 error! field: %{public}s", fieldStr);
return status;
}
status = napi_set_named_property(env, result, fieldStr, value);
if (status != napi_ok) {
HILOGE("Set int32 named property error! field: %{public}s", fieldStr);
}
return status;
}
napi_status SetValueUnsignedInt32(const napi_env& env, const char* fieldStr, const int intValue, napi_value& result)
{
napi_value value;
napi_status status = napi_create_uint32(env, intValue, &value);
if (status != napi_ok) {
HILOGE("Set value create unsigned int32 error! field: %{public}s", fieldStr);
return status;
}
status = napi_set_named_property(env, result, fieldStr, value);
if (status != napi_ok) {
HILOGE("Set unsigned int32 named property error! field: %{public}s", fieldStr);
}
return status;
}
napi_status SetValueInt64(const napi_env& env, const char* fieldStr, const int64_t intValue, napi_value& result)
{
napi_value value;
napi_status status = napi_create_int64(env, intValue, &value);
if (status != napi_ok) {
HILOGE("Set value create int64 error! field: %{public}s", fieldStr);
return status;
}
status = napi_set_named_property(env, result, fieldStr, value);
if (status != napi_ok) {
HILOGE("Set int64 named property error! field: %{public}s", fieldStr);
}
return status;
}
napi_status SetValueBool(const napi_env& env, const char* fieldStr, const bool boolvalue, napi_value& result)
{
napi_value value;
napi_status status = napi_get_boolean(env, boolvalue, &value);
if (status != napi_ok) {
HILOGE("Set value create boolean error! field: %{public}s", fieldStr);
return status;
}
status = napi_set_named_property(env, result, fieldStr, value);
if (status != napi_ok) {
HILOGE("Set boolean named property error! field: %{public}s", fieldStr);
}
return status;
}
static napi_value InitAsyncCallBackEnv(const napi_env& env, AsyncContext *asyncContext,
const size_t argc, const napi_value *argv, const size_t nonCallbackArgNum)
{
for (size_t i = nonCallbackArgNum; i != argc; ++i) {
napi_valuetype valuetype;
NAPI_CALL(env, napi_typeof(env, argv[i], &valuetype));
NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected.");
napi_create_reference(env, argv[i], 1, &asyncContext->callback[i - nonCallbackArgNum]);
}
return nullptr;
}
static napi_value InitAsyncPromiseEnv(const napi_env& env, AsyncContext *asyncContext, napi_value& promise)
{
napi_deferred deferred;
NAPI_CALL(env, napi_create_promise(env, &deferred, &promise));
asyncContext->deferred = deferred;
return nullptr;
}
static napi_value DoCallBackAsyncWork(const napi_env& env, AsyncContext *asyncContext)
{
napi_create_async_work(
env,
nullptr,
asyncContext->resourceName,
[](napi_env env, void* data) {
if (data == nullptr) {
HILOGE("Async data parameter is null");
return;
}
AsyncContext *context = static_cast<AsyncContext *>(data);
context->executeFunc(context);
},
[](napi_env env, napi_status status, void* data) {
if (data == nullptr) {
HILOGE("Async data parameter is null");
return;
}
AsyncContext *context = static_cast<AsyncContext *>(data);
napi_value undefine;
napi_get_undefined(env, &undefine);
napi_value callback;
context->completeFunc(data);
constexpr int ARGS_TWO = 2;
napi_value result[ARGS_TWO] = {nullptr};
napi_create_uint32(env, context->errorCode, &result[0]);
result[1] = context->result;
if (context->errorCode == ERR_CODE_SUCCESS) {
napi_get_reference_value(env, context->callback[0], &callback);
napi_call_function(env, nullptr, callback, ARGS_TWO, result, &undefine);
} else {
if (context->callback[1]) {
napi_get_reference_value(env, context->callback[1], &callback);
napi_call_function(env, nullptr, callback, ARGS_TWO, result, &undefine);
} else {
HILOGE("Get callback func[1] is null");
}
}
if (context->callback[0] != nullptr) {
napi_delete_reference(env, context->callback[0]);
}
if (context->callback[1] != nullptr) {
napi_delete_reference(env, context->callback[1]);
}
napi_delete_async_work(env, context->work);
delete context;
},
(void *)asyncContext,
&asyncContext->work);
NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work));
return UndefinedNapiValue(env);
}
static napi_value DoPromiseAsyncWork(const napi_env& env, AsyncContext *asyncContext)
{
napi_create_async_work(
env,
nullptr,
asyncContext->resourceName,
[](napi_env env, void *data) {
if (data == nullptr) {
HILOGE("Async data parameter is null");
return;
}
AsyncContext *context = static_cast<AsyncContext *>(data);
context->executeFunc(context);
},
[](napi_env env, napi_status status, void *data) {
if (data == nullptr) {
HILOGE("Async data parameter is null");
return;
}
AsyncContext *context = static_cast<AsyncContext *>(data);
context->completeFunc(data);
if (context->errorCode == ERR_CODE_SUCCESS) {
napi_resolve_deferred(context->env, context->deferred, context->result);
} else {
napi_reject_deferred(context->env, context->deferred, context->result);
}
napi_delete_async_work(env, context->work);
delete context;
},
(void *)asyncContext,
&asyncContext->work);
napi_queue_async_work(env, asyncContext->work);
return UndefinedNapiValue(env);
}
napi_value DoAsyncWork(const napi_env& env, AsyncContext *asyncContext,
const size_t argc, const napi_value *argv, const size_t nonCallbackArgNum)
{
if (argc > nonCallbackArgNum) {
InitAsyncCallBackEnv(env, asyncContext, argc, argv, nonCallbackArgNum);
return DoCallBackAsyncWork(env, asyncContext);
} else {
napi_value promise;
InitAsyncPromiseEnv(env, asyncContext, promise);
DoPromiseAsyncWork(env, asyncContext);
return promise;
}
}
bool ParseString(napi_env env, std::string &param, napi_value args) {
napi_valuetype valuetype;
napi_typeof(env, args, &valuetype);
HILOGI("param=%{public}d.", valuetype);
if(valuetype != napi_string) {
HILOGE("Wrong argument type. String expected.");
return false;
}
size_t size = 0;
if (napi_get_value_string_utf8(env, args, nullptr, 0, &size) != napi_ok) {
HILOGE("can not get string size");
param = "";
return false;
}
param.reserve(size + 1);
param.resize(size);
if (napi_get_value_string_utf8(env, args, param.data(), (size + 1), &size) != napi_ok) {
HILOGE("can not get string value");
param = "";
return false;
}
return true;
}
} // namespace ConnectedTag
} // namespace OHOS
@@ -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 NFC_NAPI_UTILS_H_
#define NFC_NAPI_UTILS_H_
#include <string>
#include <chrono>
#include "napi/native_api.h"
#include "napi/native_node_api.h"
namespace OHOS {
namespace ConnectedTag {
class TraceFuncCall final {
public:
TraceFuncCall(std::string funcName);
TraceFuncCall() = delete;
~TraceFuncCall();
private:
std::string m_funcName;
std::chrono::steady_clock::time_point m_startTime;
bool m_isTrace = true;
};
#define TRACE_FUNC_CALL TraceFuncCall func(__func__)
#define TRACE_FUNC_CALL_NAME(name) TraceFuncCall funcName(name)
constexpr int ERR_CODE_SUCCESS = 0;
class AsyncContext {
public:
napi_env env;
napi_async_work work;
napi_deferred deferred;
napi_ref callback[2] = { 0 };
std::function<void(void*)> executeFunc;
std::function<void(void*)> completeFunc;
napi_value resourceName;
napi_value result;
int errorCode;
AsyncContext(napi_env e, napi_async_work w = nullptr, napi_deferred d = nullptr)
{
env = e;
work = w;
deferred = d;
executeFunc = nullptr;
completeFunc = nullptr;
result = nullptr;
errorCode = ERR_CODE_SUCCESS;
}
AsyncContext() = delete;
virtual ~AsyncContext()
{
}
};
napi_value UndefinedNapiValue(const napi_env& env);
napi_value JsObjectToString(const napi_env& env, const napi_value& object,
const char* fieldStr, const int bufLen, std::string& fieldRef);
napi_value JsObjectToInt(const napi_env& env, const napi_value& object, const char* fieldStr, int& fieldRef);
napi_value JsObjectToBool(const napi_env& env, const napi_value& object, const char* fieldStr, bool& fieldRef);
napi_status SetValueUtf8String(const napi_env& env, const char* fieldStr, const char* str, napi_value& result);
napi_status SetValueInt32(const napi_env& env, const char* fieldStr, const int intValue, napi_value& result);
napi_status SetValueUnsignedInt32(const napi_env& env, const char* fieldStr, const int intValue, napi_value& result);
napi_status SetValueInt64(const napi_env& env, const char* fieldStr, const int64_t intValue, napi_value& result);
napi_status SetValueBool(const napi_env& env, const char* fieldStr, const bool boolValue, napi_value& result);
napi_value DoAsyncWork(const napi_env& env, AsyncContext *asyncContext,
const size_t argc, const napi_value *argv, const size_t nonCallbackArgNum);
bool ParseString(napi_env env, std::string &param, napi_value args);
enum class SecTypeJs {
SEC_TYPE_INVALID = 0, /* Invalid security type */
SEC_TYPE_OPEN = 1, /* Open */
SEC_TYPE_WEP = 2, /* Wired Equivalent Privacy (WEP) */
SEC_TYPE_PSK = 3, /* Pre-shared key (PSK) */
SEC_TYPE_SAE = 4, /* Simultaneous Authentication of Equals (SAE) */
};
} // namespace ConnectedTag
} // namespace OHOS
#endif
+27
View File
@@ -0,0 +1,27 @@
<?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>nfc_connected_tag_service</process>
<systemability> <!-- Declare a system ability and its profile -->
<name>1140</name> <!-- Declare the id of system ability. Must be same with system_ability_definition.h -->
<libpath>libnfc_connected_tag_service.z.so</libpath> <!-- Declare the path of .so file which includes the system ability; Note: 1 .so file can have 1 to N system abilities. -->
<!--<depend></depend> --> <!-- Declare the name of system abilities which the system ability depends on, using ";" as separator among names. If there are dependencies, it needs to check if all those dependencies are available in service manager before starting the system ability. -->
<!--<depend-time-out></depend-time-out> --> <!-- Check all dependencies are available before the timeout period ended. The MAX_DEPENDENCY_TIMEOUT is 60s. -->
<run-on-create>true</run-on-create> <!-- "true" means the system ability would start immediately, "false" means the system ability would start on demand. -->
<distributed>false</distributed> <!-- "true" means the system ability supports distributed scheduling while "false" is not. -->
<dump-level>1</dump-level> <!-- Declare the dump level. 1-high; 2-media; 3-low -->
</systemability>
</info>
+20
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("//build/ohos/sa_profile/sa_profile.gni")
ohos_sa_profile("connected_tag_profile") {
sources = [ "1140.xml" ]
part_name = "nfc_connected_tag"
}
+50
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("//build/ohos.gni")
import("//build/ohos_var.gni")
ROOT = "//foundation/communication/nfc/services/connected_tag"
ohos_shared_library("nfc_connected_tag_service") {
include_dirs = [
"//foundation/communication/nfc/interfaces/kits/native_cpp/connected_tag_base/interfaces",
"//foundation/communication/nfc/interfaces/kits/native_cpp/connected_tag_base/include",
"$ROOT/src/hardware/include",
"include",
]
sources = [
"src/connected_tag_session_stub.cpp",
"src/connected_tag_service_impl.cpp",
"src/connected_tag_callback_proxy.cpp",
]
deps = [
"$ROOT/src/hardware:connected_tag_hdi_adapter",
"$ROOT/etc/init:etc",
"//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//utils/native/base:utils",
]
external_deps = [
"hisysevent_native:libhisysevent",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core"
]
part_name = "nfc_connected_tag"
subsystem_name = "communication"
}
+29
View File
@@ -0,0 +1,29 @@
# 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_var.gni")
group("etc") {
deps = [
":nfc_connected_tag_service.rc",
]
}
ohos_prebuilt_etc("nfc_connected_tag_service.rc") {
source = "nfc_connected_tag_service.cfg"
relative_install_dir = "init"
part_name = "nfc_connected_tag"
subsystem_name = "communication"
}
@@ -0,0 +1,17 @@
{
"jobs" : [{
"name" : "post-fs-data",
"cmds" : [
"mkdir /data/nfc_connected_tag",
"start nfc_connected_tag_service"
]
}
],
"services" : [{
"name" : "nfc_connected_tag_service",
"path" : ["/system/bin/sa_main", "/system/profile/nfc_connected_tag_service.xml"],
"uid" : "root",
"gid" : ["root", "shell"]
}
]
}
@@ -0,0 +1,23 @@
# 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.
on post-fs-data
mkdir /data/nfc_connected_tag
start nfc_connected_tag_service
service nfc_connected_tag_service /system/bin/sa_main /system/profile/nfc_connected_tag_service.xml
class z_core
user root
group root shell
seclabel u:r:nfc_connected_tag_service:s0
@@ -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 OHOS_CONNECTED_TAG_CALLBACK_PROXY_H
#define OHOS_CONNECTED_TAG_CALLBACK_PROXY_H
#include "iconnected_tag_callback.h"
#include "iremote_proxy.h"
#include "ipc_cmd.h"
namespace OHOS {
namespace ConnectedTag {
class ConnectedTagCallBackProxy : public IRemoteProxy<IConnectedTagCallBack> {
public:
explicit ConnectedTagCallBackProxy(const sptr<IRemoteObject> &remote);
virtual ~ConnectedTagCallBackProxy() {}
void OnNotify(int nfcRfState) override;
private:
static inline BrokerDelegator<ConnectedTagCallBackProxy> g_delegator;
};
} // namespace ConnectedTag
} // namespace OHOS
#endif
@@ -0,0 +1,63 @@
/*
* 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_NFC_CONNECTED_TAG_SERVICE_IMPL_H
#define OHOS_NFC_CONNECTED_TAG_SERVICE_IMPL_H
#include "system_ability.h"
#include "connected_tag_session_stub.h"
#include "iremote_object.h"
#include "error_code.h"
namespace OHOS {
namespace ConnectedTag {
enum ServiceRunningState {
STATE_NOT_START,
STATE_RUNNING
};
class NfcConnectedTagServiceImpl : public SystemAbility, public TagSessionStub {
DECLARE_SYSTEM_ABILITY(NfcConnectedTagServiceImpl);
public:
NfcConnectedTagServiceImpl();
virtual ~NfcConnectedTagServiceImpl();
static sptr<NfcConnectedTagServiceImpl> GetInstance();
void OnStart() override;
void OnStop() override;
ErrCode Init() override;
ErrCode Uninit() override;
ErrCode ReadNdefTag(std::string &response) override;
ErrCode WriteNdefTag(std::string data) override;
ErrCode RegListener(const sptr<IConnectedTagCallBack> &callback) override;
ErrCode UnregListener(const sptr<IConnectedTagCallBack> &callback) override;
private:
bool ServiceInit();
private:
static sptr<NfcConnectedTagServiceImpl> g_instance;
static std::mutex g_instanceLock;
bool mPublishFlag;
ServiceRunningState mState;
};
} // namespace OHOS_NFC_CONNECTED_TAG_SERVICE_IMPL_H
} // namespace OHOS
#endif
@@ -0,0 +1,47 @@
/*
* 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_TAG_SESSION_STUB_H
#define OHOS_TAG_SESSION_STUB_H
#include <map>
#include "i_tag_session.h"
#include "iremote_stub.h"
#include <stdint.h>
#include <string>
namespace OHOS {
namespace ConnectedTag {
class TagSessionStub: public IRemoteStub<ITagSession> {
public:
TagSessionStub();
virtual ~TagSessionStub();
using handleFunc = void (TagSessionStub::*)(uint32_t code, MessageParcel &data, MessageParcel &reply);
using HandleFuncMap = std::map<int, handleFunc>;
virtual int OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
private:
void InitHandleMap();
void OnInit(uint32_t code, MessageParcel &data, MessageParcel &reply);
void OnUninit(uint32_t code, MessageParcel &data, MessageParcel &reply);
void OnReadNdefTag(uint32_t code, MessageParcel &data, MessageParcel &reply);
void OnWriteNdefTag(uint32_t code, MessageParcel &data, MessageParcel &reply);
private:
HandleFuncMap handleFuncMap;
};
} // namespace Nfc_Connected_Tag
} // namespace OHOS
#endif
@@ -0,0 +1,46 @@
/*
* 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 "connected_tag_callback_proxy.h"
#include "ipc_cmd.h"
#include "log.h"
namespace OHOS {
namespace ConnectedTag {
ConnectedTagCallBackProxy::ConnectedTagCallBackProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<IConnectedTagCallBack>(impl)
{}
void ConnectedTagCallBackProxy::OnNotify(int nfcRfState)
{
HILOGD("ConnectedTagCallBackProxy::OnNotify");
MessageOption option;
MessageParcel data;
MessageParcel reply;
data.WriteInt32(0);
data.WriteInt32(nfcRfState);
int error = Remote()->SendRequest(CMD_ON_NOTIFY, data, reply, option);
if (error != ERR_NONE) {
HILOGE("Set Attr(%{public}d) failed,error code is %{public}d", CMD_ON_NOTIFY, error);
return;
}
int exception = reply.ReadInt32();
if (exception) {
HILOGE("notify CMD_ON_NOTIFY state change failed!");
}
return;
}
} // namespace ConnectedTag
} // namespace OHOS
+126
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 "connected_tag_service_impl.h"
#include "error_code.h"
#include "connected_tag_hdi_adapter.h"
#include "ipc_cmd.h"
#include "log.h"
namespace OHOS {
namespace ConnectedTag {
std::mutex NfcConnectedTagServiceImpl::g_instanceLock;
sptr<NfcConnectedTagServiceImpl> NfcConnectedTagServiceImpl::g_instance;
const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(NfcConnectedTagServiceImpl::GetInstance().GetRefPtr());
sptr<NfcConnectedTagServiceImpl> NfcConnectedTagServiceImpl::GetInstance()
{
if (g_instance == nullptr) {
std::lock_guard<std::mutex> autoLock(g_instanceLock);
if (g_instance == nullptr) {
auto service = new (std::nothrow) NfcConnectedTagServiceImpl;
g_instance = service;
}
}
return g_instance;
}
NfcConnectedTagServiceImpl::NfcConnectedTagServiceImpl()
: SystemAbility(NFC_CONNECTED_TAG_ABILITY_ID, true), mPublishFlag(false), mState(ServiceRunningState::STATE_NOT_START)
{
}
NfcConnectedTagServiceImpl::~NfcConnectedTagServiceImpl()
{
}
void NfcConnectedTagServiceImpl::OnStart()
{
HILOGI("NfcConnectedTagServiceImpl::OnStart() in");
if (mState == ServiceRunningState::STATE_RUNNING) {
HILOGI("Service has already started.");
return;
}
if (!ServiceInit()) {
HILOGE("Failed to init service");
OnStop();
return;
}
mState = ServiceRunningState::STATE_RUNNING;
HILOGI("Start service!");
}
void NfcConnectedTagServiceImpl::OnStop()
{
HILOGI("NfcConnectedTagServiceImpl::OnStop() in");
mState = ServiceRunningState::STATE_NOT_START;
mPublishFlag = false;
HILOGI("Stop service!");
}
bool NfcConnectedTagServiceImpl::ServiceInit()
{
HILOGI("NfcConnectedTagServiceImpl::ServiceInit() in!");
if (!mPublishFlag) {
bool ret = Publish(NfcConnectedTagServiceImpl::GetInstance());
if (!ret) {
HILOGE("Failed to publish service!");
return false;
}
mPublishFlag = true;
}
return true;
}
ErrCode NfcConnectedTagServiceImpl::Init()
{
HILOGE("NfcConnectedTagServiceImpl:Init() in!");
if (NfcHdiAdapter::GetInstance().Init() == 0) {
return NFC_OPT_SUCCESS;
}
return NFC_OPT_FAILED;
}
ErrCode NfcConnectedTagServiceImpl::Uninit()
{
if (NfcHdiAdapter::GetInstance().Uninit() == 0) {
return NFC_OPT_SUCCESS;
}
return NFC_OPT_FAILED;
}
ErrCode NfcConnectedTagServiceImpl::ReadNdefTag(std::string &response)
{
response = NfcHdiAdapter::GetInstance().ReadNdefTag();
return NFC_OPT_SUCCESS;
}
ErrCode NfcConnectedTagServiceImpl::WriteNdefTag(std::string data)
{
if (NfcHdiAdapter::GetInstance().WriteNdefTag(data) == 0) {
return NFC_OPT_SUCCESS;
}
return NFC_OPT_FAILED;
}
ErrCode NfcConnectedTagServiceImpl::RegListener(const sptr<IConnectedTagCallBack> &callback)
{
return NFC_OPT_SUCCESS;
}
ErrCode NfcConnectedTagServiceImpl::UnregListener(const sptr<IConnectedTagCallBack> &callback)
{
return NFC_OPT_SUCCESS;
}
} // namespace ConnectedTag
} // namespace OHOS
+89
View File
@@ -0,0 +1,89 @@
/*
* 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 "i_tag_session.h"
#include "log.h"
#include "error_code.h"
#include "ipc_cmd.h"
#include "connected_tag_session_stub.h"
namespace OHOS {
namespace ConnectedTag {
TagSessionStub::TagSessionStub()
{
HILOGI("TagSessionStub: TagSessionStub called.");
InitHandleMap();
}
TagSessionStub::~TagSessionStub()
{}
void TagSessionStub::InitHandleMap()
{
handleFuncMap[NFC_SVR_CMD_INIT] = &TagSessionStub::OnInit;
handleFuncMap[NFC_SVR_CMD_UNINIT] = &TagSessionStub::OnUninit;
handleFuncMap[NFC_SVR_CMD_READ_NDEF_TAG] = &TagSessionStub::OnReadNdefTag;
handleFuncMap[NFC_SVR_CMD_WRITE_NDEF_TAG] = &TagSessionStub::OnWriteNdefTag;
}
int TagSessionStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
int exception = data.ReadInt32();
if (exception) {
return NFC_OPT_FAILED;
}
HandleFuncMap::iterator iter = handleFuncMap.find(code);
if (iter == handleFuncMap.end()) {
HILOGW("not find function to deal, code %{public}u", code);
reply.WriteInt32(0);
reply.WriteInt32(NFC_OPT_NOT_SUPPORTED);
} else {
(this->*(iter->second))(code, data, reply);
return NFC_OPT_SUCCESS;
}
HILOGW("TagSessionStub::OnRemoteRequest, default case, need check.");
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
void TagSessionStub::OnInit(uint32_t code, MessageParcel &data, MessageParcel &reply)
{
HILOGI("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize());
ErrCode ret = Init();
reply.WriteInt32(0);
reply.WriteInt32(ret);
}
void TagSessionStub::OnUninit(uint32_t code, MessageParcel &data, MessageParcel &reply)
{
HILOGI("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize());
ErrCode ret = Uninit();
reply.WriteInt32(0);
reply.WriteInt32(ret);
}
void TagSessionStub::OnReadNdefTag(uint32_t code, MessageParcel &data, MessageParcel &reply)
{
HILOGI("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize());
std::string response;
ReadNdefTag(response);
reply.WriteInt32(0);
reply.WriteString(response);
}
void TagSessionStub::OnWriteNdefTag(uint32_t code, MessageParcel &data, MessageParcel &reply)
{
std::string dataToWrite = data.ReadString();
HILOGI("run %{public}s datasize %{public}zu, str = %{public}s, len = %{public}d",
__func__, data.GetRawDataSize(), dataToWrite.c_str(), dataToWrite.length());
ErrCode ret = WriteNdefTag(dataToWrite);
reply.WriteInt32(0);
reply.WriteInt32(ret);
}
} // namespace ConnectedTag
} // namespace OHOS
+55
View File
@@ -0,0 +1,55 @@
# 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("//drivers/adapter/uhdf2/uhdf.gni")
ohos_shared_library("connected_tag_hdi_adapter") {
include_dirs = [
"include",
"//foundation/communication/nfc/interfaces/kits/native_cpp/connected_tag_base/include",
"//drivers/peripheral/nfc/connected_tag/v1_0/client",
]
cflags = [ "-fPIC" ]
sources = [
"src/connected_tag_hdi_adapter.cpp",
]
deps = [
"$hdf_uhdf_path/hdi:libhdi",
"$hdf_uhdf_path/host:libhdf_host",
"$hdf_uhdf_path/ipc:libhdf_ipc_adapter",
"$hdf_uhdf_path/utils:libhdf_utils",
"//utils/native/base:utils",
"//utils/native/base:utilsecurec_shared",
]
if (is_standard_system) {
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"connected_tag_device_driver:connected_tag_client",
]
} else {
external_deps = [
"hilog:libhilog",
"ipc:ipc_core",
"connected_tag_device_driver:connected_tag_client",
]
}
subsystem_name = "communication"
part_name = "nfc_connected_tag"
}
@@ -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.
*/
#include <stdint.h>
#include <string>
namespace OHOS {
namespace ConnectedTag {
class NfcHdiAdapter {
public:
~NfcHdiAdapter();
static NfcHdiAdapter &GetInstance();
int32_t Init();
int32_t Uninit();
std::string ReadNdefTag();
int32_t WriteNdefTag(std::string data);
private:
NfcHdiAdapter();
};
} // namespace Nfc_Connected_Tag
} // namespace OHOS
@@ -0,0 +1,81 @@
/*
* 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 "connected_tag_hdi_adapter.h"
#include "log.h"
#include "connected_tag_proxy.h"
namespace OHOS {
namespace ConnectedTag {
static sptr<ohos::hardware::nfc::v1_0::IConnectedTagHdi> g_iConnectedTagHdi;
NfcHdiAdapter::NfcHdiAdapter()
{
HILOGI("NfcHdiAdapter: NfcHdiAdapter called.");
sptr<ohos::hardware::nfc::v1_0::IConnectedTagHdi> nfcHdi = ohos::hardware::nfc::v1_0::IConnectedTagHdi::Get();
if (nfcHdi == nullptr)
{
HILOGE("NfcHdiAdapter: IConnectedTagHdi::Get failed.");
}
g_iConnectedTagHdi = nfcHdi;
}
NfcHdiAdapter::~NfcHdiAdapter()
{
HILOGI("NfcHdiAdapter: ~NfcHdiAdapter called.");
}
NfcHdiAdapter &NfcHdiAdapter::GetInstance()
{
static NfcHdiAdapter instance;
return instance;
}
int32_t NfcHdiAdapter::Init()
{
HILOGI("NfcHdiAdapter::Init() starts");
if (g_iConnectedTagHdi != nullptr)
{
g_iConnectedTagHdi->Init();
}
return 0;
}
int32_t NfcHdiAdapter::Uninit()
{
HILOGI("NfcHdiAdapter::Uninit() starts");
if (g_iConnectedTagHdi != nullptr)
{
g_iConnectedTagHdi->Uninit();
}
return 0;
}
std::string NfcHdiAdapter::ReadNdefTag()
{
HILOGI("NfcHdiAdapter::ReadNdefTag() starts");
std::string resp = "";
if (g_iConnectedTagHdi != nullptr)
{
resp = g_iConnectedTagHdi->ReadNdefTag();
HILOGI("NfcHdiAdapter::ReadNdefTag() resp = %{public}s", resp.c_str());
}
return resp;
}
int32_t NfcHdiAdapter::WriteNdefTag(std::string data)
{
HILOGI("NfcHdiAdapter::WriteNdefTag() starts data = %{public}s", data.c_str());
if (g_iConnectedTagHdi != nullptr)
{
g_iConnectedTagHdi->WriteNdefTag(data);
}
return 0;
}
} // namespace ConnectedTag
} // namespace OHOS