Remote the nfc_core and keep the connected nfc tag.

Signed-off-by: zhangxiuping <zhangxiuping@huawei.com>
This commit is contained in:
zhangxiuping
2022-09-01 17:06:36 +08:00
parent a71eee784a
commit df144b2904
207 changed files with 614 additions and 20401 deletions
Executable → Regular
View File
Executable → Regular
+18 -24
View File
@@ -1,4 +1,4 @@
# NFC<a name="EN-US_TOPIC_0000001133207781"></a>
# Connected NFC Tag<a name="EN-US_TOPIC_0000001133207781"></a>
- [Introduction](#section13587125816351)
- [Architecture](#section13587185873516)
@@ -11,47 +11,41 @@
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.
For the devices has connected nfc tag chip, this component provides tag reading and writing.
## Architecture<a name="section13587185873516"></a>
**Figure 1** NFC architecture<a name="fig4460722185514"></a>
**Figure 1** Connected NFC Tag Architecture<a name="fig4460722185514"></a>
![](figures/en-us_image_0000001086731550.gif)
![](figures/en-us_image_0000001086731550.png)
## Directory Structure<a name="section161941989596"></a>
The main code directory structure of Intelligent Soft Bus is as follows:
```
/foundation/communication
├── interfaces # Interface code
│ └── kits
│ └── native_cpp # Native SDK
└── connected_tag_base # NFC connected tag SDK
└── napi # Native api
│ └── connected_tag # Native api of NFC connected tag
── sa_profile # Declare of sub system attribute
│ └── connected_tag # Declare of NFC connected tag attribute
└── services # Sub system service code folder
└── connected_tag # NFC connected tag folder
├── etc # System service config
├── include # Include code
└── src # Source code
/foundation/communication/connected_nfc_tag
├── interfaces # Interface
│ └── inner_api # System inner interface
├── frameworks # Framework interface
└── js # Implementation of JS API
│ └── napi # Napi implementation of JS API
├── services # Service implementation
── test # Test code
├── BUILD.gn # Build entry
└── bundle.json # Component description
```
## Constraints<a name="section119744591305"></a>
- Devices must has the connected tag chip.
- Devices must has the connected nfc tag chip.
## Usage<a name="section1312121216216"></a>
- connected tag reading and writing.
- connected nfc tag reading and writing.
Devices must has the connected tag chip to connected tag reading and writing. Please reference "js-apis-connectedTag.md”。
Please reference: docs/zh-cn/application-dev/reference/apis/js-apis-connectedTag.md
## Repositories Involved<a name="section1371113476307"></a>
hmf/communication/nfc
hmf/communication/connected_nfc_tag
Executable → Regular
+17 -22
View File
@@ -1,4 +1,4 @@
# NFC组件<a name="ZH-CN_TOPIC_0000001124412109"></a>
# 有源NFC标签组件<a name="ZH-CN_TOPIC_0000001124412109"></a>
- [简介](#section11660541593)
- [系统架构](#section342962219551)
@@ -12,11 +12,11 @@
近距离无线通信技术\(Near Field CommunicationNFC\) ,是一种非接触式识别和互联技术,可以在移动设备、消费类电子产品、PC和智能设备间进行近距离无线通信。
OpenHarmony中NFC服务提供有源标签读写能力。
针对具备有源NFC标签的产品,本组件提供有源NFC标签的读和写能力。
## 系统架构<a name="section342962219551"></a>
**图 1** NFC组件架构图<a name="fig444313176464"></a>
**图 1** 有源NFC标签架构图<a name="fig444313176464"></a>
![](figures/zh-cn_image_0000001124327253.png)
@@ -29,36 +29,31 @@ OpenHarmony中NFC服务提供有源标签读写能力。
## 目录<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 # 源文件
/foundation/communication/connected_nfc_tag
├── interfaces # 接口
│ └── inner_api # 系统内部件间接口
├── frameworks # 框架层接口
└── js # JS API的实现
│ └── napi # 通过napi封装的JS接口代码实现
├── services # NFC有源标签服务进程的实现
── test # 测试代码
├── BUILD.gn # 编译入口
└── bundle.json # 部件描述文件
```
## 约束<a name="section119744591305"></a>
设备必须具备有源标签芯片,才能使用有源标签的读写服务。
设备必须具备有源NFC标签芯片,才能使用有源NFC标签的读写服务。
## 说明<a name="section1312121216216"></a>
### 使用说明<a name="section129654513264"></a>
- 有源标签的读写
设备必须具备有源标签芯片,才能使用有源标签的读写服务,参考“js-apis-connectedTag.md”有源标签开发指南。
- 有源NFC标签的读写
参考开发指南: docs/zh-cn/application-dev/reference/apis/js-apis-connectedTag.md。
## 相关仓<a name="section1371113476307"></a>
hmf/communication/nfc
hmf/communication/connected_nfc_tag
+13 -12
View File
@@ -1,10 +1,10 @@
{
"name": "@ohos/communication_nfc",
"name": "@ohos/communication_connected_nfc_tag",
"version": "3.1",
"description": "nfc service",
"homePage": "https://gitee.com/openharmony",
"license": "Apache License 2.0",
"repository": "https://gitee.com/openharmony/communication_nfc",
"repository": "https://gitee.com/openharmony/communication_connected_nfc_tag",
"domain": "os",
"language": "",
"publishAs": "code-segment",
@@ -15,7 +15,8 @@
],
"keywords": [
"communication",
"nfc"
"nfc",
"tag"
],
"envs": [],
"dirs": [],
@@ -32,10 +33,10 @@
}
],
"segment": {
"destPath": "foundation/communication/nfc/connected_tag"
"destPath": "foundation/communication/connected_nfc_tag"
},
"component": {
"name": "connected_tag",
"name": "connected_nfc_tag",
"subsystem": "communication",
"syscap": [
"SystemCapability.Communication.ConnectedTag"
@@ -55,20 +56,20 @@
},
"build": {
"sub_component": [
"//foundation/communication/nfc/connected_tag/sa_profile:connected_tag_profile",
"//foundation/communication/nfc/connected_tag/interfaces/innerkits:connected_tag_base",
"//foundation/communication/nfc/connected_tag/services:nfc_connected_tag_service",
"//foundation/communication/nfc/connected_tag/interfaces/js/napi:connectedtag"
"//foundation/communication/connected_nfc_tag/sa_profile:nfc_tag_profile",
"//foundation/communication/connected_nfc_tag/interfaces/inner_api:nfc_tag_inner_kits",
"//foundation/communication/connected_nfc_tag/services:nfc_tag_service",
"//foundation/communication/connected_nfc_tag/frameworks/js/napi:nfc_tag_napi"
],
"inner_kits": [
{
"type": "so",
"name": "//foundation/communication/nfc/connected_tag/interfaces/innerkits:connected_tag_base",
"name": "//foundation/communication/connected_nfc_tag/interfaces/inner_api:nfc_tag_inner_kits",
"header": {
"header_files": [
"connected_tag_impl.h"
"nfc_tag_impl.h"
],
"header_base": "//foundation/communication/nfc/connected_tag/interfaces/innerkits/include"
"header_base": "//foundation/communication/connected_nfc_tag/interfaces/inner_api/include"
}
}
],
@@ -1,29 +0,0 @@
/*
* 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
-27
View File
@@ -1,27 +0,0 @@
<?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
@@ -1,20 +0,0 @@
# 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"
}
-27
View File
@@ -1,27 +0,0 @@
# 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"
}
@@ -1,18 +0,0 @@
{
"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" : "nfc",
"gid" : ["nfc", "shell"],
"caps" : ["CAP_NET_BIND_SERVICE", "CAP_NET_RAW"]
}
]
}
@@ -1,23 +0,0 @@
# 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
@@ -1,153 +0,0 @@
/*
* 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"
#include "permission_tools.h"
namespace OHOS {
namespace ConnectedTag {
std::mutex ConnectedTagServiceImpl::g_instanceLock;
sptr<ConnectedTagServiceImpl> ConnectedTagServiceImpl::g_instance;
const bool REGISTER_RESULT =
SystemAbility::MakeAndRegisterAbility(ConnectedTagServiceImpl::GetInstance().GetRefPtr());
sptr<ConnectedTagServiceImpl> ConnectedTagServiceImpl::GetInstance()
{
if (g_instance == nullptr) {
std::lock_guard<std::mutex> autoLock(g_instanceLock);
if (g_instance == nullptr) {
auto service = new (std::nothrow) ConnectedTagServiceImpl;
g_instance = service;
}
}
return g_instance;
}
ConnectedTagServiceImpl::ConnectedTagServiceImpl()
: SystemAbility(NFC_CONNECTED_TAG_ABILITY_ID, true), mPublishFlag(false),
mState(ServiceRunningState::STATE_NOT_START)
{
}
ConnectedTagServiceImpl::~ConnectedTagServiceImpl()
{
}
void ConnectedTagServiceImpl::OnStart()
{
HILOGI("ConnectedTagServiceImpl::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 ConnectedTagServiceImpl::OnStop()
{
HILOGI("ConnectedTagServiceImpl::OnStop() in");
mState = ServiceRunningState::STATE_NOT_START;
mPublishFlag = false;
HILOGI("Stop service!");
}
bool ConnectedTagServiceImpl::ServiceInit()
{
HILOGI("ConnectedTagServiceImpl::ServiceInit() in!");
if (!mPublishFlag) {
bool ret = Publish(ConnectedTagServiceImpl::GetInstance());
if (!ret) {
HILOGE("Failed to publish service!");
return false;
}
mPublishFlag = true;
}
return true;
}
ErrCode ConnectedTagServiceImpl::Init()
{
HILOGE("ConnectedTagServiceImpl:Init() in!");
if (!PermissionTools::IsGranted(OHOS::ConnectedTag::TAG_PERMISSION)) {
HILOGE("ConnectedTagServiceImpl:Init() IsGranted failed!");
return NFC_OPT_FAILED;
}
if (ConnectedTagHdiAdapter::GetInstance().Init() == 0) {
return NFC_OPT_SUCCESS;
}
return NFC_OPT_FAILED;
}
ErrCode ConnectedTagServiceImpl::Uninit()
{
if (!PermissionTools::IsGranted(OHOS::ConnectedTag::TAG_PERMISSION)) {
HILOGE("ConnectedTagServiceImpl:Uninit() IsGranted failed!");
return NFC_OPT_FAILED;
}
if (ConnectedTagHdiAdapter::GetInstance().Uninit() == 0) {
return NFC_OPT_SUCCESS;
}
return NFC_OPT_FAILED;
}
ErrCode ConnectedTagServiceImpl::ReadNdefTag(std::string &response)
{
if (!PermissionTools::IsGranted(OHOS::ConnectedTag::TAG_PERMISSION)) {
HILOGE("ConnectedTagServiceImpl:ReadNdefTag() IsGranted failed!");
return NFC_OPT_FAILED;
}
response = ConnectedTagHdiAdapter::GetInstance().ReadNdefTag();
return NFC_OPT_SUCCESS;
}
ErrCode ConnectedTagServiceImpl::WriteNdefTag(std::string data)
{
if (!PermissionTools::IsGranted(OHOS::ConnectedTag::TAG_PERMISSION)) {
HILOGE("ConnectedTagServiceImpl:WriteNdefTag() IsGranted failed!");
return NFC_OPT_FAILED;
}
if (ConnectedTagHdiAdapter::GetInstance().WriteNdefTag(data) == 0) {
return NFC_OPT_SUCCESS;
}
return NFC_OPT_FAILED;
}
ErrCode ConnectedTagServiceImpl::RegListener(const sptr<IConnectedTagCallBack> &callback)
{
if (!PermissionTools::IsGranted(OHOS::ConnectedTag::TAG_PERMISSION)) {
HILOGE("ConnectedTagServiceImpl:RegListener() IsGranted failed!");
return NFC_OPT_FAILED;
}
return NFC_OPT_SUCCESS;
}
ErrCode ConnectedTagServiceImpl::UnregListener(const sptr<IConnectedTagCallBack> &callback)
{
if (!PermissionTools::IsGranted(OHOS::ConnectedTag::TAG_PERMISSION)) {
HILOGE("ConnectedTagServiceImpl:UnregListener() IsGranted failed!");
return NFC_OPT_FAILED;
}
return NFC_OPT_SUCCESS;
}
} // namespace ConnectedTag
} // namespace OHOS
@@ -1,76 +0,0 @@
/*
* 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::HDI::NFC::V1_0::IConnectedTagHdi> g_iConnectedTagHdi;
ConnectedTagHdiAdapter::ConnectedTagHdiAdapter()
{
HILOGI("ConnectedTagHdiAdapter: ConnectedTagHdiAdapter called.");
sptr<OHOS::HDI::NFC::V1_0::IConnectedTagHdi> nfcHdi = OHOS::HDI::NFC::V1_0::IConnectedTagHdi::Get();
if (nfcHdi == nullptr) {
HILOGE("ConnectedTagHdiAdapter: IConnectedTagHdi::Get failed.");
}
g_iConnectedTagHdi = nfcHdi;
}
ConnectedTagHdiAdapter::~ConnectedTagHdiAdapter()
{
HILOGI("ConnectedTagHdiAdapter: ~ConnectedTagHdiAdapter called.");
}
ConnectedTagHdiAdapter &ConnectedTagHdiAdapter::GetInstance()
{
static ConnectedTagHdiAdapter instance;
return instance;
}
int32_t ConnectedTagHdiAdapter::Init()
{
HILOGI("ConnectedTagHdiAdapter::Init() starts");
if (g_iConnectedTagHdi != nullptr) {
g_iConnectedTagHdi->Init();
}
return 0;
}
int32_t ConnectedTagHdiAdapter::Uninit()
{
HILOGI("ConnectedTagHdiAdapter::Uninit() starts");
if (g_iConnectedTagHdi != nullptr) {
g_iConnectedTagHdi->Uninit();
}
return 0;
}
std::string ConnectedTagHdiAdapter::ReadNdefTag()
{
HILOGI("ConnectedTagHdiAdapter::ReadNdefTag() starts");
std::string resp = "";
if (g_iConnectedTagHdi != nullptr) {
resp = g_iConnectedTagHdi->ReadNdefTag();
HILOGI("ConnectedTagHdiAdapter::ReadNdefTag() resp = %{public}s", resp.c_str());
}
return resp;
}
int32_t ConnectedTagHdiAdapter::WriteNdefTag(std::string data)
{
HILOGI("ConnectedTagHdiAdapter::WriteNdefTag() starts data = %{public}s", data.c_str());
if (g_iConnectedTagHdi != nullptr) {
g_iConnectedTagHdi->WriteNdefTag(data);
}
return 0;
}
} // namespace ConnectedTag
} // namespace OHOS
Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 54 KiB

@@ -13,17 +13,10 @@
import("//build/ohos.gni")
ohos_shared_library("connectedtag") {
ohos_shared_library("nfc_tag_napi") {
install_enable = true
include_dirs = [
"//third_party/node/src",
"//native_engine",
"//commonlibrary/c_utils/base/include",
"//utils/system/safwk/native/include",
"//foundation/communication/nfc/connected_tag/interfaces/innerkits/include",
"//foundation/communication/nfc/connected_tag/interfaces/innerkits/interfaces",
"//base/hiviewdfx/hilog/interfaces/native/innerkits/include",
"//base/notification/common_event_service/frameworks/core/include",
"//foundation/communication/connected_nfc_tag/interfaces/inner_api/include",
]
sources = [
@@ -32,19 +25,16 @@ ohos_shared_library("connectedtag") {
"nfc_napi_event.cpp",
"nfc_napi_utils.cpp",
]
deps = [ "//foundation/communication/nfc/connected_tag/interfaces/innerkits:connected_tag_base" ]
deps = [ "//foundation/communication/connected_nfc_tag/interfaces/inner_api:nfc_tag_inner_kits" ]
external_deps = [
"ability_base:want",
"c_utils:utils",
"common_event_service:cesfwk_core",
"common_event_service:cesfwk_innerkits",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"napi:ace_napi",
]
relative_install_dir = "module"
part_name = "nfc_connected_tag"
part_name = "connected_nfc_tag"
subsystem_name = "communication"
}
@@ -12,34 +12,33 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "nfc_napi_adapter.h"
#include <vector>
#include <functional>
#include "error_code.h"
#include "connected_tag_impl.h"
#include "define.h"
#include "log.h"
#include "nfc_napi_adapter.h"
#include "nfc_tag_impl.h"
namespace OHOS {
namespace ConnectedTag {
namespace NFC {
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();
NfcTagImpl nfcTagPtr = OHOS::NFC::NfcTagImpl::GetInstance();
ErrCode ret = nfcTagPtr.Init();
napi_value result;
napi_get_boolean(env, ret == NFC_OPT_SUCCESS, &result);
napi_get_boolean(env, ret == NFC_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();
NfcTagImpl nfcTagPtr = OHOS::NFC::NfcTagImpl::GetInstance();
ErrCode ret = nfcTagPtr.Uninit();
napi_value result;
napi_get_boolean(env, ret == NFC_OPT_SUCCESS, &result);
napi_get_boolean(env, ret == NFC_SUCCESS, &result);
return result;
}
@@ -58,9 +57,9 @@ napi_value ReadNdefTag(napi_env env, napi_callback_info info)
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);
TRACE_FUNC_CALL_NAME("nfcTagPtr->ReadNdefTag");
NfcTagImpl nfcTagPtr = OHOS::NFC::NfcTagImpl::GetInstance();
context->errorCode = nfcTagPtr.ReadNdefTag(context->respNdefData);
HILOGI("ReadNdefTag end errorCode = %{public}d", context->errorCode);
};
@@ -95,10 +94,10 @@ napi_value WriteNdefTag(napi_env env, napi_callback_info info)
asyncContext->executeFunc = [&](void* data) -> void {
WriteAsyncContext *context = static_cast<WriteAsyncContext *>(data);
TRACE_FUNC_CALL_NAME("connectedTagPtr->WriteNdefTag");
ConnectedTagImpl connectedTagPtr = OHOS::ConnectedTag::ConnectedTagImpl::GetInstance();
TRACE_FUNC_CALL_NAME("nfcTagPtr->WriteNdefTag");
NfcTagImpl nfcTagPtr = OHOS::NFC::NfcTagImpl::GetInstance();
HILOGI("WriteNdefTag start ndefData = %{public}s", context->writtenNdefData.c_str());
context->errorCode = connectedTagPtr.WriteNdefTag(context->writtenNdefData);
context->errorCode = nfcTagPtr.WriteNdefTag(context->writtenNdefData);
HILOGI("WriteNdefTag end errorCode = %{public}d", context->errorCode);
};
@@ -109,5 +108,5 @@ napi_value WriteNdefTag(napi_env env, napi_callback_info info)
size_t nonCallbackArgNum = 1;
return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum);
}
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
@@ -12,13 +12,13 @@
* 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 {
namespace NFC {
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);
@@ -27,7 +27,7 @@ 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)
explicit ReadAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr)
: AsyncContext(env, work, deferred) {}
ReadAsyncContext() = delete;
@@ -38,7 +38,7 @@ public:
class WriteAsyncContext : public AsyncContext {
public:
std::string writtenNdefData;
WriteAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr)
explicit WriteAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr)
: AsyncContext(env, work, deferred)
{
writtenNdefData = "";
@@ -48,7 +48,7 @@ public:
~WriteAsyncContext() override {}
};
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
#endif
@@ -12,13 +12,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "log.h"
#include "nfc_napi_adapter.h"
#include "nfc_napi_event.h"
#include "log.h"
namespace OHOS {
namespace ConnectedTag {
namespace NFC {
/*
* Module initialization function
*/
@@ -44,7 +43,7 @@ static napi_module nfcConnectedTagModule = {
.nm_flags = 0,
.nm_filename = NULL,
.nm_register_func = InitJs,
.nm_modname = "connectedTag",
.nm_modname = "connectedTag", // modname MUST matched with the file name of connectedTag.d.ts of js apis.
.nm_priv = ((void *)0),
.reserved = { 0 }
};
@@ -53,5 +52,5 @@ extern "C" __attribute__((constructor)) void RegisterModule(void)
{
napi_module_register(&nfcConnectedTagModule);
}
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
@@ -16,12 +16,12 @@
#include "nfc_napi_event.h"
#include <uv.h>
#include "nfc_napi_utils.h"
#include "infc_tag_callback.h"
#include "log.h"
#include "iconnected_tag_callback.h"
#include "connected_tag_impl.h"
#include "nfc_tag_impl.h"
namespace OHOS {
namespace ConnectedTag {
namespace NFC {
const std::string EVENT_NOTIFY = "notify";
static std::set<std::string> g_supportEventList = {
@@ -90,7 +90,7 @@ bool NapiEvent::CheckIsRegister(const std::string& type)
return NFC::g_eventRegisterInfo.find(type) != NFC::g_eventRegisterInfo.end();
}
class NfcListenerEvent : public IConnectedTagCallBack, public NapiEvent {
class NfcListenerEvent : public INfcTagCallback, public NapiEvent {
public:
NfcListenerEvent() {
}
@@ -184,9 +184,9 @@ napi_value Off(napi_env env, napi_callback_info cbinfo)
ErrCode EventRegister::RegisterNfcEvents()
{
ConnectedTagImpl connectedTag = OHOS::ConnectedTag::ConnectedTagImpl::GetInstance();
ErrCode ret = connectedTag.RegListener(nfcListenerEvent);
if (ret != NFC_OPT_SUCCESS) {
NfcTagImpl nfcTagImpl = OHOS::NFC::NfcTagImpl::GetInstance();
ErrCode ret = nfcTagImpl.RegListener(nfcListenerEvent);
if (ret != NFC_SUCCESS) {
HILOGE("RegisterNfcEvents nfcListenerEvent failed!");
return ret;
}
@@ -214,7 +214,7 @@ void EventRegister::Register(const napi_env& env, const std::string& type, napi_
}
std::unique_lock<std::shared_mutex> guard(NFC::g_regInfoMutex);
if (!isEventRegistered) {
if (RegisterNfcEvents() != NFC_OPT_SUCCESS) {
if (RegisterNfcEvents() != NFC_SUCCESS) {
return;
}
isEventRegistered = true;
@@ -281,5 +281,5 @@ void EventRegister::Unregister(const napi_env& env, const std::string& type, nap
NFC::g_eventRegisterInfo.erase(iter);
}
}
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
@@ -19,11 +19,11 @@
#include <map>
#include <vector>
#include <shared_mutex>
#include "define.h"
#include "napi/native_api.h"
#include "error_code.h"
namespace OHOS {
namespace ConnectedTag {
namespace NFC {
class AsyncEventData {
public:
napi_env env;
@@ -114,7 +114,7 @@ private:
napi_value On(napi_env env, napi_callback_info cbinfo);
napi_value Off(napi_env env, napi_callback_info cbinfo);
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
#endif
@@ -12,13 +12,12 @@
* 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 {
namespace NFC {
TraceFuncCall::TraceFuncCall(const std::string funcName): m_funcName(funcName)
{
if (m_isTrace) {
@@ -305,5 +304,5 @@ bool ParseString(napi_env env, std::string &param, napi_value args)
}
return true;
}
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
@@ -12,7 +12,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NFC_NAPI_UTILS_H_
#define NFC_NAPI_UTILS_H_
@@ -22,7 +21,7 @@
#include "napi/native_node_api.h"
namespace OHOS {
namespace ConnectedTag {
namespace NFC {
class TraceFuncCall final {
public:
explicit TraceFuncCall(const std::string funcName);
@@ -54,7 +53,7 @@ public:
napi_value result;
int errorCode;
AsyncContext(napi_env e, napi_async_work w = nullptr, napi_deferred d = nullptr)
explicit AsyncContext(napi_env e, napi_async_work w = nullptr, napi_deferred d = nullptr)
{
env = e;
work = w;
@@ -93,7 +92,7 @@ enum class SecTypeJs {
SEC_TYPE_PSK = 3, /* Pre-shared key (PSK) */
SEC_TYPE_SAE = 4, /* Simultaneous Authentication of Equals (SAE) */
};
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
#endif
@@ -14,30 +14,28 @@
import("//build/ohos.gni")
import("//build/ohos_var.gni")
config("connected_tag_base_config") {
config("nfc_tag_config") {
cflags_cc = [
"-fPIC",
"-Wno-unused-parameter",
"-Wunused-private-field",
]
include_dirs = [
"//utils/system/safwk/native/include",
"//foundation/communication/nfc/connected_tag/interfaces/innerkits/interfaces",
"//foundation/communication/nfc/connected_tag/interfaces/innerkits/include",
"//foundation/communication/connected_nfc_tag/interfaces/inner_api/include",
]
}
config("connected_tag_base_public_config") {
config("nfc_tag_public_config") {
include_dirs = []
}
ohos_shared_library("connected_tag_base") {
configs = [ ":connected_tag_base_config" ]
public_configs = [ ":connected_tag_base_public_config" ]
ohos_shared_library("nfc_tag_inner_kits") {
configs = [ ":nfc_tag_config" ]
public_configs = [ ":nfc_tag_public_config" ]
sources = [
"src/connected_tag_callback_stub.cpp",
"src/connected_tag_impl.cpp",
"src/tag_session_proxy.cpp",
"src/nfc_tag_callback_stub.cpp",
"src/nfc_tag_impl.cpp",
"src/nfc_tag_session_proxy.cpp",
]
deps = []
@@ -50,5 +48,5 @@ ohos_shared_library("connected_tag_base") {
]
subsystem_name = "communication"
part_name = "nfc_connected_tag"
part_name = "connected_nfc_tag"
}
@@ -12,18 +12,29 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_IPC_CMD_H
#define OHOS_IPC_CMD_H
#ifndef OHOS_NFC_DEFINE_H
#define OHOS_NFC_DEFINE_H
/* ------------connected tag module message define--------- */
namespace OHOS {
namespace NFC {
/* nfc tag error code defines */
enum ErrCode {
NFC_SUCCESS = 0, /* successfully */
NFC_FAILED, /* failed */
NFC_NOT_SUPPORTED, /* not supported */
};
/* ---------Feature service ability id--------- */
#define NFC_CONNECTED_TAG_ABILITY_ID 1140
/* ------------connected nfc 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
#define CMD_ON_NFC_TAG_NOTIFY 0x2001
} // namespace NFC
} // namespace OHOS
#endif
@@ -12,18 +12,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NAPI_ICONNECTED_TAG_H_
#define NAPI_ICONNECTED_TAG_H_
#ifndef NAPI_INFC_TAG_H_
#define NAPI_INFC_TAG_H_
#include "define.h"
#include "infc_tag_callback.h"
#include "iremote_object.h"
#include "error_code.h"
#include "iconnected_tag_callback.h"
namespace OHOS {
namespace ConnectedTag {
class IConnectedTag {
namespace NFC {
class INfcTag {
public:
virtual ~IConnectedTag() = default;
virtual ~INfcTag() = default;
virtual ErrCode Init() = 0;
@@ -33,10 +33,10 @@ public:
virtual ErrCode WriteNdefTag(std::string data) = 0;
virtual ErrCode RegListener(const sptr<IConnectedTagCallBack> &callback) = 0;
virtual ErrCode RegListener(const sptr<INfcTagCallback> &callback) = 0;
virtual ErrCode UnregListener(const sptr<IConnectedTagCallBack> &callback) = 0;
virtual ErrCode UnregListener(const sptr<INfcTagCallback> &callback) = 0;
};
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
#endif /* NAPI_ICONNECTED_TAG_H_ */
#endif
@@ -12,18 +12,19 @@
* 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
#ifndef NFC_INFC_TAG_CALLBACK_H
#define NFC_INFC_TAG_CALLBACK_H
#include <iremote_stub.h>
namespace OHOS {
namespace ConnectedTag {
class IConnectedTagCallBack : public IRemoteBroker {
namespace NFC {
class INfcTagCallback : public IRemoteBroker {
public:
virtual void OnNotify(int nfcRfState) = 0;
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.connected_tag.IConnectedTagCallBack");
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.nfc.INfcTagCallback");
};
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
#endif // NFC_ICONNECTED_TAG_CALLBACK_H
#endif
@@ -12,27 +12,28 @@
* 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
#ifndef OHOS_INFC_TAG_SESSION_H
#define OHOS_INFC_TAG_SESSION_H
#include "define.h"
#include "infc_tag_callback.h"
#include "iremote_broker.h"
#include "error_code.h"
#include "iconnected_tag_callback.h"
namespace OHOS {
namespace ConnectedTag {
class ITagSession : public IRemoteBroker {
namespace NFC {
class INfcTagSession : public IRemoteBroker {
public:
virtual ~ITagSession() {}
virtual ~INfcTagSession() {}
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;
virtual ErrCode RegListener(const sptr<INfcTagCallback> &callback) = 0;
virtual ErrCode UnregListener(const sptr<INfcTagCallback> &callback) = 0;
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.nfc.INfcConnectedTagService");
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.nfc.IConnectedNfcTagService");
};
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
#endif
@@ -12,23 +12,23 @@
* 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
#ifndef OHOS_NFC_TAG_CALLBACK_STUB_H
#define OHOS_NFC_TAG_CALLBACK_STUB_H
#include <shared_mutex>
#include "iremote_stub.h"
#include "define.h"
#include "infc_tag_callback.h"
#include "iremote_object.h"
#include "iconnected_tag_callback.h"
#include "error_code.h"
#include "iremote_stub.h"
namespace OHOS {
namespace ConnectedTag {
class ConnectedTagCallBackStub : public IRemoteStub<IConnectedTagCallBack> {
namespace NFC {
class NfcTagCallbackStub : public IRemoteStub<INfcTagCallback> {
public:
ConnectedTagCallBackStub();
virtual ~ConnectedTagCallBackStub();
static ConnectedTagCallBackStub& GetInstance();
ErrCode RegisterUserCallBack(const sptr<IConnectedTagCallBack> &callBack);
NfcTagCallbackStub();
virtual ~NfcTagCallbackStub();
static NfcTagCallbackStub& GetInstance();
ErrCode RegisterUserCallBack(const sptr<INfcTagCallback> &callBack);
virtual int OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
@@ -37,10 +37,10 @@ public:
private:
int RemoteOnNotify(MessageParcel &data, MessageParcel &reply);
sptr<IConnectedTagCallBack> callback_;
sptr<INfcTagCallback> callback_;
std::shared_mutex callbackMutex;
bool mRemoteDied;
};
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
#endif
@@ -12,22 +12,22 @@
* 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_
#ifndef NAPI_NFC_TAG_IMPL_H_
#define NAPI_NFC_TAG_IMPL_H_
#include "tag_session_proxy.h"
#include "error_code.h"
#include "iconnected_tag.h"
#include "iconnected_tag_callback.h"
#include "define.h"
#include "infc_tag.h"
#include "infc_tag_callback.h"
#include "nfc_tag_session_proxy.h"
namespace OHOS {
namespace ConnectedTag {
class ConnectedTagImpl : public IConnectedTag {
namespace NFC {
class NfcTagImpl : public INfcTag {
public:
explicit ConnectedTagImpl();
virtual ~ConnectedTagImpl();
explicit NfcTagImpl();
virtual ~NfcTagImpl();
static ConnectedTagImpl& GetInstance();
static NfcTagImpl& GetInstance();
ErrCode Init() override;
@@ -37,12 +37,12 @@ public:
ErrCode WriteNdefTag(std::string data) override;
ErrCode RegListener(const sptr<IConnectedTagCallBack> &callback) override;
ErrCode RegListener(const sptr<INfcTagCallback> &callback) override;
ErrCode UnregListener(const sptr<IConnectedTagCallBack> &callback) override;
ErrCode UnregListener(const sptr<INfcTagCallback> &callback) override;
private:
sptr<ITagSession> tagSessionProxy_;
sptr<INfcTagSession> tagSessionProxy_;
};
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
#endif /* NAPI_CONNECTED_TAG_IMPL_H_ */
#endif
@@ -14,16 +14,17 @@
*/
#ifndef OHOS_NFC_TAG_SESSION_PROXY_H
#define OHOS_NFC_TAG_SESSION_PROXY_H
#include <stdint.h>
#include "i_tag_session.h"
#include "infc_tag_session.h"
#include "iremote_proxy.h"
namespace OHOS {
namespace ConnectedTag {
class TagSessionProxy : public IRemoteProxy<ITagSession>, public IRemoteObject::DeathRecipient {
namespace NFC {
class NfcTagSessionProxy : public IRemoteProxy<INfcTagSession>, public IRemoteObject::DeathRecipient {
public:
explicit TagSessionProxy(const sptr<IRemoteObject> &impl);
~TagSessionProxy();
explicit NfcTagSessionProxy(const sptr<IRemoteObject> &impl);
~NfcTagSessionProxy();
ErrCode Init() override;
@@ -33,9 +34,9 @@ public:
ErrCode WriteNdefTag(std::string data) override;
ErrCode RegListener(const sptr<IConnectedTagCallBack> &callback) override;
ErrCode RegListener(const sptr<INfcTagCallback> &callback) override;
ErrCode UnregListener(const sptr<IConnectedTagCallBack> &callback) override;
ErrCode UnregListener(const sptr<INfcTagCallback> &callback) override;
/**
* @Description Handle remote object died event.
@@ -46,6 +47,6 @@ public:
private:
bool mRemoteDied;
};
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
#endif
@@ -12,49 +12,48 @@
* 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 "nfc_tag_callback_stub.h"
#include "define.h"
#include "log.h"
namespace OHOS {
namespace ConnectedTag {
ConnectedTagCallBackStub::ConnectedTagCallBackStub() : callback_(nullptr), mRemoteDied(false)
namespace NFC {
NfcTagCallbackStub::NfcTagCallbackStub() : callback_(nullptr), mRemoteDied(false)
{}
ConnectedTagCallBackStub::~ConnectedTagCallBackStub()
NfcTagCallbackStub::~NfcTagCallbackStub()
{}
ConnectedTagCallBackStub& ConnectedTagCallBackStub::GetInstance()
NfcTagCallbackStub& NfcTagCallbackStub::GetInstance()
{
static ConnectedTagCallBackStub sConnectedTagCallBackStub;
static NfcTagCallbackStub sConnectedTagCallBackStub;
return sConnectedTagCallBackStub;
}
void ConnectedTagCallBackStub::OnNotify(int nfcRfState)
void NfcTagCallbackStub::OnNotify(int nfcRfState)
{
HILOGD("ConnectedTagCallBackStub::OnNotify");
HILOGD("NfcTagCallbackStub::OnNotify");
if (callback_) {
callback_->OnNotify(nfcRfState);
}
}
int ConnectedTagCallBackStub::OnRemoteRequest(
int NfcTagCallbackStub::OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
HILOGD("ConnectedTagCallBackStub::OnRemoteRequest!");
HILOGD("NfcTagCallbackStub::OnRemoteRequest!");
if (mRemoteDied) {
HILOGE("Failed to `%{public}s`,Remote service is died!", __func__);
return NFC_OPT_FAILED;
return NFC_FAILED;
}
int exception = data.ReadInt32();
if (exception) {
HILOGE("ConnectedTagCallBackStub::OnRemoteRequest, got exception: %{public}d!", exception);
return NFC_OPT_FAILED;
HILOGE("NfcTagCallbackStub::OnRemoteRequest, got exception: %{public}d!", exception);
return NFC_FAILED;
}
int ret = NFC_OPT_FAILED;
int ret = NFC_FAILED;
switch (code) {
case CMD_ON_NOTIFY: {
case CMD_ON_NFC_TAG_NOTIFY: {
ret = RemoteOnNotify(data, reply);
break;
}
@@ -66,17 +65,17 @@ int ConnectedTagCallBackStub::OnRemoteRequest(
return ret;
}
ErrCode ConnectedTagCallBackStub::RegisterUserCallBack(const sptr<IConnectedTagCallBack> &callBack)
ErrCode NfcTagCallbackStub::RegisterUserCallBack(const sptr<INfcTagCallback> &callBack)
{
std::shared_lock<std::shared_mutex> guard(callbackMutex);
if (callBack == nullptr) {
HILOGW("RegisterUserCallBack:callBack is nullptr!");
}
callback_ = callBack;
return NFC_OPT_SUCCESS;
return NFC_SUCCESS;
}
int ConnectedTagCallBackStub::RemoteOnNotify(MessageParcel &data, MessageParcel &reply)
int NfcTagCallbackStub::RemoteOnNotify(MessageParcel &data, MessageParcel &reply)
{
HILOGD("run %{public}s datasize %{public}zu", __func__, data.GetRawDataSize());
int state = data.ReadInt32();
@@ -84,8 +83,8 @@ int ConnectedTagCallBackStub::RemoteOnNotify(MessageParcel &data, MessageParcel
if (callback_) {
callback_->OnNotify(state);
}
reply.WriteInt32(NFC_OPT_SUCCESS); /* Reply 0 to indicate that no exception occurs. */
return NFC_OPT_SUCCESS;
reply.WriteInt32(NFC_SUCCESS); /* Reply 0 to indicate that no exception occurs. */
return NFC_SUCCESS;
}
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
@@ -12,16 +12,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "connected_tag_impl.h"
#include "nfc_tag_impl.h"
#include "define.h"
#include "iservice_registry.h"
#include "ipc_cmd.h"
#include "log.h"
namespace OHOS {
namespace ConnectedTag {
ConnectedTagImpl::ConnectedTagImpl()
namespace NFC {
NfcTagImpl::NfcTagImpl()
{
HILOGI("ConnectedTagImpl() in");
HILOGI("NfcTagImpl() in");
sptr<ISystemAbilityManager> sa_mgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sa_mgr == nullptr) {
HILOGE("failed to get SystemAbilityManager");
@@ -30,50 +30,50 @@ ConnectedTagImpl::ConnectedTagImpl()
sptr<IRemoteObject> object = sa_mgr->GetSystemAbility(NFC_CONNECTED_TAG_ABILITY_ID);
if (object == nullptr) {
HILOGE("failed to get connected tag SERVICE");
HILOGE("failed to get connected nfc tag SERVICE");
return;
}
tagSessionProxy_ = iface_cast<ITagSession>(object);
tagSessionProxy_ = iface_cast<INfcTagSession>(object);
if (tagSessionProxy_ == nullptr) {
tagSessionProxy_ = new (std::nothrow) TagSessionProxy(object);
tagSessionProxy_ = new (std::nothrow) NfcTagSessionProxy(object);
}
if (tagSessionProxy_ == nullptr) {
HILOGE("TagSessionProxy init failed!");
HILOGE("NfcTagSessionProxy init failed!");
}
}
ConnectedTagImpl::~ConnectedTagImpl()
NfcTagImpl::~NfcTagImpl()
{
}
ConnectedTagImpl& ConnectedTagImpl::GetInstance()
NfcTagImpl& NfcTagImpl::GetInstance()
{
static ConnectedTagImpl tagImplSingleton;
static NfcTagImpl tagImplSingleton;
return tagImplSingleton;
}
ErrCode ConnectedTagImpl::Init()
ErrCode NfcTagImpl::Init()
{
return tagSessionProxy_->Init();
}
ErrCode ConnectedTagImpl::Uninit()
ErrCode NfcTagImpl::Uninit()
{
return tagSessionProxy_->Uninit();
}
ErrCode ConnectedTagImpl::ReadNdefTag(std::string &response)
ErrCode NfcTagImpl::ReadNdefTag(std::string &response)
{
return tagSessionProxy_->ReadNdefTag(response);
}
ErrCode ConnectedTagImpl::WriteNdefTag(std::string data)
ErrCode NfcTagImpl::WriteNdefTag(std::string data)
{
return tagSessionProxy_->WriteNdefTag(data);
}
ErrCode ConnectedTagImpl::RegListener(const sptr<IConnectedTagCallBack> &callback)
ErrCode NfcTagImpl::RegListener(const sptr<INfcTagCallback> &callback)
{
return tagSessionProxy_->RegListener(callback);
}
ErrCode ConnectedTagImpl::UnregListener(const sptr<IConnectedTagCallBack> &callback)
ErrCode NfcTagImpl::UnregListener(const sptr<INfcTagCallback> &callback)
{
return tagSessionProxy_->UnregListener(callback);
}
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
@@ -12,16 +12,17 @@
* 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 "nfc_tag_session_proxy.h"
#include "define.h"
#include "log.h"
#include "tag_session_proxy.h"
#include "nfc_tag_callback_stub.h"
namespace OHOS {
namespace ConnectedTag {
TagSessionProxy::TagSessionProxy(const sptr<IRemoteObject> &impl) : IRemoteProxy<ITagSession>(impl), mRemoteDied(false)
namespace NFC {
NfcTagSessionProxy::NfcTagSessionProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<INfcTagSession>(impl), mRemoteDied(false)
{
HILOGI("TagSessionProxy() in!");
HILOGI("NfcTagSessionProxy() in!");
if (impl) {
if ((impl->IsProxyObject()) && (!impl->AddDeathRecipient(this))) {
HILOGD("AddDeathRecipient!");
@@ -30,130 +31,130 @@ TagSessionProxy::TagSessionProxy(const sptr<IRemoteObject> &impl) : IRemoteProxy
}
}
}
TagSessionProxy::~TagSessionProxy()
NfcTagSessionProxy::~NfcTagSessionProxy()
{
}
ErrCode TagSessionProxy::Init()
ErrCode NfcTagSessionProxy::Init()
{
if (mRemoteDied) {
HILOGD("failed to `%{public}s`,remote service is died!", __func__);
return NFC_OPT_FAILED;
HILOGE("failed to `%{public}s`,remote service is died!", __func__);
return NFC_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return NFC_OPT_FAILED;
return NFC_FAILED;
}
data.WriteInt32(NFC_OPT_SUCCESS);
data.WriteInt32(NFC_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;
return NFC_FAILED;
}
int exception = reply.ReadInt32();
if (exception) {
return NFC_OPT_FAILED;
return NFC_FAILED;
}
return ErrCode(reply.ReadInt32());
}
ErrCode TagSessionProxy::Uninit()
ErrCode NfcTagSessionProxy::Uninit()
{
if (mRemoteDied) {
HILOGD("failed to `%{public}s`,remote service is died!", __func__);
return NFC_OPT_FAILED;
HILOGE("failed to `%{public}s`,remote service is died!", __func__);
return NFC_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return NFC_OPT_FAILED;
return NFC_FAILED;
}
data.WriteInt32(NFC_OPT_SUCCESS);
data.WriteInt32(NFC_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;
return NFC_FAILED;
}
int exception = reply.ReadInt32();
if (exception) {
return NFC_OPT_FAILED;
return NFC_FAILED;
}
return ErrCode(reply.ReadInt32());
}
ErrCode TagSessionProxy::ReadNdefTag(std::string &response)
ErrCode NfcTagSessionProxy::ReadNdefTag(std::string &response)
{
if (mRemoteDied) {
HILOGD("failed to `%{public}s`,remote service is died!", __func__);
return NFC_OPT_FAILED;
HILOGE("failed to `%{public}s`,remote service is died!", __func__);
return NFC_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return NFC_OPT_FAILED;
return NFC_FAILED;
}
data.WriteInt32(NFC_OPT_SUCCESS);
data.WriteInt32(NFC_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;
return NFC_FAILED;
}
int exception = reply.ReadInt32();
if (exception) {
return NFC_OPT_FAILED;
return NFC_FAILED;
}
response = reply.ReadString();
return ErrCode(NFC_OPT_SUCCESS);
return ErrCode(NFC_SUCCESS);
}
ErrCode TagSessionProxy::WriteNdefTag(std::string tagData)
ErrCode NfcTagSessionProxy::WriteNdefTag(std::string tagData)
{
if (mRemoteDied) {
HILOGD("failed to `%{public}s`,remote service is died!", __func__);
return NFC_OPT_FAILED;
HILOGE("failed to `%{public}s`,remote service is died!", __func__);
return NFC_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return NFC_OPT_FAILED;
return NFC_FAILED;
}
data.WriteInt32(NFC_OPT_SUCCESS);
data.WriteInt32(NFC_SUCCESS);
data.WriteString(tagData);
HILOGE("TagSessionProxy WriteNdefTag tagData is %{public}s", tagData.c_str());
HILOGD("NfcTagSessionProxy 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;
return NFC_FAILED;
}
int exception = reply.ReadInt32();
if (exception) {
return NFC_OPT_FAILED;
return NFC_FAILED;
}
return ErrCode(reply.ReadInt32());
}
ErrCode TagSessionProxy::RegListener(const sptr<IConnectedTagCallBack> &callback)
ErrCode NfcTagSessionProxy::RegListener(const sptr<INfcTagCallback> &callback)
{
return OHOS::ConnectedTag::ConnectedTagCallBackStub::GetInstance().RegisterUserCallBack(callback);
return OHOS::NFC::NfcTagCallbackStub::GetInstance().RegisterUserCallBack(callback);
}
ErrCode TagSessionProxy::UnregListener(const sptr<IConnectedTagCallBack> &callback)
ErrCode NfcTagSessionProxy::UnregListener(const sptr<INfcTagCallback> &callback)
{
return OHOS::ConnectedTag::ConnectedTagCallBackStub::GetInstance().RegisterUserCallBack(nullptr);
return OHOS::NFC::NfcTagCallbackStub::GetInstance().RegisterUserCallBack(nullptr);
}
void TagSessionProxy::OnRemoteDied(const wptr<IRemoteObject> &remoteObject)
void NfcTagSessionProxy::OnRemoteDied(const wptr<IRemoteObject> &remoteObject)
{
HILOGD("Remote service is died!");
mRemoteDied = true;
}
} // namespace ConnectedTag
} // namespace NFC
} // namespace OHOS
-86
View File
@@ -1,86 +0,0 @@
{
"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/nfc_core"
},
"component": {
"name": "nfc",
"subsystem": "communication",
"syscap": [
"SystemCapability.Communication.NFC.Core"
],
"features": [],
"adapted_system_type": [
],
"rom": "",
"ram": "",
"deps": {
"components": [
"ipc",
"hiviewdfx_hilog_native",
"bundle_framework"
],
"third_party": [
"nfc-nci"
]
},
"build": {
"sub_component": [
"//third_party/libnfc-nci/SN100x:nfc-nci",
"//foundation/communication/nfc/nfc_core/sa_profile:nfc_profile",
"//foundation/communication/nfc/nfc_core/interfaces/innerkits:nfc_inner_kits",
"//foundation/communication/nfc/nfc_core/interfaces/js/napi/controller:controller",
"//foundation/communication/nfc/nfc_core/interfaces/js/napi/tag:tag",
"//foundation/communication/nfc/nfc_core/services:nfc_service"
],
"inner_kits": [
{
"type": "so",
"name": "//foundation/communication/nfc/nfc_core/interfaces/innerkits:nfc_inner_kits",
"header": {
"header_files": [
"nfc_controller.h"
],
"header_base": "//foundation/communication/nfc/nfc_core/interfaces/innerkits/include/controller"
}
}
],
"test": [
"//foundation/communication/nfc/nfc_core/test:test_nfc_service"
]
},
"hisysevent_config": [
]
}
}
-73
View File
@@ -1,73 +0,0 @@
# 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("nfc_inner_kits_config") {
visibility = [ ":*" ]
defines = [ "DEBUG" ]
cflags_cc = [ "-fexceptions" ]
include_dirs = []
}
config("nfc_inner_kits_public_config") {
visibility = [ ":*" ]
include_dirs = [
"include",
"include/controller",
"include/tags",
]
}
ohos_shared_library("nfc_inner_kits") {
sources = [
"src/controller/nfc_controller.cpp",
"src/controller/nfc_controller_callback_stub.cpp",
"src/controller/nfc_controller_proxy.cpp",
"src/nfc_basic_proxy.cpp",
"src/nfc_sdk_common.cpp",
"src/tags/basic_tag_session.cpp",
"src/tags/iso15693_tag.cpp",
"src/tags/isodep_tag.cpp",
"src/tags/mifare_classic_tag.cpp",
"src/tags/mifare_ultralight_tag.cpp",
"src/tags/ndef_formatable_tag.cpp",
"src/tags/ndef_message.cpp",
"src/tags/ndef_tag.cpp",
"src/tags/nfca_tag.cpp",
"src/tags/nfcb_tag.cpp",
"src/tags/nfcf_tag.cpp",
"src/tags/tag_session_proxy.cpp",
"src/tags/taginfo.cpp",
]
configs = [ ":nfc_inner_kits_config" ]
public_configs = [ ":nfc_inner_kits_public_config" ]
deps = []
external_deps = [
"ability_base:want",
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr:samgr_proxy",
]
part_name = "nfc"
subsystem_name = "communication"
}
@@ -1,38 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_NFC_CONTROLLER_CALLBACK_H
#define OHOS_I_NFC_CONTROLLER_CALLBACK_H
#include <string>
#include <string_ex.h>
#include <iremote_broker.h>
#include "message_parcel.h"
#include "message_option.h"
namespace OHOS {
namespace NFC {
class INfcControllerCallback : public IRemoteBroker {
public:
virtual void OnNfcStateChanged(int nfcState) = 0;
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.nfc.kits.INfcControllerCallback");
};
} // namespace NFC
} // namespace OHOS
#endif
@@ -1,58 +0,0 @@
/*
* 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 I_NFC_CONTROLLER_SERVICE_H
#define I_NFC_CONTROLLER_SERVICE_H
#include "nfc_sdk_common.h"
#include "infc_controller_callback.h"
#include "iremote_broker.h"
namespace OHOS {
namespace NFC {
class INfcControllerService : public OHOS::IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.nfc.INfcControllerService");
virtual ~INfcControllerService() {}
/**
* @brief Get the NFC state
* @return The NFC State
*/
virtual int GetState() = 0;
/**
* @brief Turn On NFC
* @return true - turn on; the other
*/
virtual bool TurnOn() = 0;
/**
* @brief Turn Off NFC
* @return true - turn off; the other
*/
virtual bool TurnOff() = 0;
/**
* @brief NFC enable
* @return true - NFC enabled; the other
*/
virtual bool IsNfcOpen() = 0;
virtual KITS::NfcErrorCode RegisterCallBack(const sptr<INfcControllerCallback> &callback,
const std::string& type) = 0;
virtual KITS::NfcErrorCode UnRegisterCallBack(const std::string& type) = 0;
private:
};
} // namespace NFC
} // namespace OHOS
#endif // I_NFC_CONTROLLER_SERVICE_H
@@ -1,98 +0,0 @@
/*
* 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_CONTROLLER_H
#define NFC_CONTROLLER_H
#include "nfc_controller_callback_stub.h"
#include "nfc_controller_proxy.h"
#include "nfc_sdk_common.h"
#include "infc_controller_callback.h"
#include "infc_controller_service.h"
namespace OHOS {
namespace NFC {
namespace KITS {
static const std::string NFC_SERVICE_NAME = "nfc";
const std::string NFC_EXTRA_STATE = "ohos.nfc.extra.ADAPTER_STATE";
const std::string COMMON_EVENT_NFC_ACTION_STATE_CHANGED = "usual.event.nfc.action.ADAPTER_STATE_CHANGED";
class NfcController final {
public:
explicit NfcController();
~NfcController();
/**
* @Description Get an object of nfc controller.
* @param void
* @return an object of nfc controller
*/
static NfcController &GetInstance();
/**
* @Description Turn on Nfc of the device.
* @param void
* @return Errorcode of turn on nfc. if return 0, means successful.
*/
int TurnOn();
/**
* @Description Turn off Nfc of the device.
* @param void
* @return Errorcode of turn off nfc. if return 0, means successful.
*/
int TurnOff();
/**
* @Description Get nfc state of device.
* @param void
* @return nfc state.
*/
int GetNfcState();
/**
* @Checks whether a device supports NFC.
* @param void
* @return If the device supports NFC return 1; otherwise return 0.
*/
int IsNfcAvailable();
/**
* @Description Checks whether NFC is enabled.
* @param void
* @return If NFC is enabled return 1; otherwise return 0.
*/
int IsNfcOpen();
/**
* @Description Registers the callback for nfc state changed notification.
* @param callback the callback to be registered.
* @param type the type for this callback, it's "nfcStateChange"
* @return The status code for register operation.
*/
NfcErrorCode RegListener(const sptr<INfcControllerCallback> &callback, const std::string& type);
/**
* @Description Unregisters the callback for nfc state changed notification.
* @param type the type for this callback, it's "nfcStateChange"
* @return The status code for unregister operation.
*/
NfcErrorCode UnregListener(const std::string& type);
private:
static void InitNfcController();
private:
static bool initialized_;
static std::shared_ptr<NfcControllerProxy> nfcControllerProxy_;
static std::weak_ptr<OHOS::NFC::INfcControllerService> nfcControllerService_;
static std::mutex mutex_;
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif // NFC_CONTROLLER_H
@@ -1,49 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_CONTROLLER_CALLBACK_STUB_H
#define OHOS_NFC_CONTROLLER_CALLBACK_STUB_H
#include <shared_mutex>
#include "nfc_sdk_common.h"
#include "infc_controller_callback.h"
#include "iremote_object.h"
#include "iremote_stub.h"
namespace OHOS {
namespace NFC {
class NfcControllerCallBackStub : public IRemoteStub<INfcControllerCallback> {
public:
NfcControllerCallBackStub();
virtual ~NfcControllerCallBackStub();
static NfcControllerCallBackStub& GetInstance();
KITS::NfcErrorCode RegisterCallBack(const sptr<INfcControllerCallback> &callBack);
virtual int OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
void OnNfcStateChanged(int nfcRfState) override;
private:
int RemoteNfcStateChanged(MessageParcel &data, MessageParcel &reply);
sptr<INfcControllerCallback> callback_;
std::shared_mutex callbackMutex;
bool mRemoteDied;
};
} // namespace NFC
} // namespace OHOS
#endif
@@ -1,48 +0,0 @@
/*
* 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_CONTROLLER_PROXY_H
#define NFC_CONTROLLER_PROXY_H
#include "nfc_basic_proxy.h"
#include "nfc_sdk_common.h"
#include "infc_controller_callback.h"
#include "infc_controller_service.h"
#include "iremote_proxy.h"
#include "iremote_object.h"
namespace OHOS {
namespace NFC {
class NfcControllerProxy final : public OHOS::IRemoteProxy<INfcControllerService>, public NfcBasicProxy {
public:
explicit NfcControllerProxy(const OHOS::sptr<OHOS::IRemoteObject>& remote)
: OHOS::IRemoteProxy<INfcControllerService>(remote), NfcBasicProxy(remote)
{
}
~NfcControllerProxy() override;
bool TurnOn() override;
bool TurnOff() override;
int GetState() override;
bool IsNfcOpen() override;
KITS::NfcErrorCode RegisterCallBack(const sptr<INfcControllerCallback> &callback,
const std::string& type) override;
KITS::NfcErrorCode UnRegisterCallBack(const std::string& type) override;
private:
};
} // namespace NFC
} // namespace OHOS
#endif // NFC_CONTROLLER_PROXY_H
@@ -1,81 +0,0 @@
/*
* 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 LOG_HELPER_H
#define LOG_HELPER_H
#ifdef DEBUG
#include "hilog/log.h"
#ifdef FatalLog
#undef FatalLog
#endif
#ifdef ErrorLog
#undef ErrorLog
#endif
#ifdef WarnLog
#undef WarnLog
#endif
#ifdef InfoLog
#undef InfoLog
#endif
#ifdef DebugLog
#undef DebugLog
#endif
#ifndef NFC_LOG_DOMAIN
#define NFC_LOG_DOMAIN 0xD000301
#endif
#ifndef NFC_LOG_TAG
#define NFC_LOG_TAG "Nfc_Core"
#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 FatalLog(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Fatal( \
LOG_LABEL, "[%{public}s(%{public}s:%{public}d)]" fmt, FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define ErrorLog(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Error( \
LOG_LABEL, "[%{public}s(%{public}s:%{public}d)]" fmt, FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define WarnLog(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Warn( \
LOG_LABEL, "[%{public}s(%{public}s:%{public}d)]" fmt, FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define InfoLog(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Info( \
LOG_LABEL, "[%{public}s(%{public}s:%{public}d)]" fmt, FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define DebugLog(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Debug( \
LOG_LABEL, "[%{public}s(%{public}s:%{public}d)]" fmt, FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define FatalLog(...)
#define ErrorLog(...)
#define WarnLog(...)
#define InfoLog(...)
#define DebugLog(...)
#endif // DEBUG
#endif // LOG_HELPER_H
@@ -1,42 +0,0 @@
/*
* 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_BASIC_PROXY_H
#define NFC_BASIC_PROXY_H
#include "iremote_object.h"
#include "message_parcel.h"
#include "message_option.h"
namespace OHOS {
namespace NFC {
class NfcBasicProxy {
public:
explicit NfcBasicProxy(const OHOS::sptr<OHOS::IRemoteObject>& obj) : remoteObj_(obj) {}
virtual ~NfcBasicProxy() {}
int ProcessIntRes(int cmd, OHOS::MessageParcel& data, OHOS::MessageOption& option, int& result);
int ProcessBoolRes(int cmd, OHOS::MessageParcel& data, OHOS::MessageOption& option, bool& result);
int ProcessCommand(int cmd, OHOS::MessageParcel& data, OHOS::MessageOption& option);
int ProcessCallBackCommand(int cmd,
OHOS::MessageParcel& data,
OHOS::MessageParcel& reply,
OHOS::MessageOption& option);
private:
OHOS::sptr<OHOS::IRemoteObject> remoteObj_ {};
};
} // namespace NFC
} // namespace OHOS
#endif // NFC_BASIC_PROXY_H
@@ -1,107 +0,0 @@
/*
* 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_SDK_COMMON_H
#define NFC_SDK_COMMON_H
#include <string>
#include <vector>
namespace OHOS {
namespace NFC {
namespace KITS {
// the command id defined for IPC, from kits to system ability.
constexpr int COMMAND_ID = 100;
constexpr int COMMAND_GET_STATE = COMMAND_ID + 1;
constexpr int COMMAND_TURN_ON = COMMAND_ID + 2;
constexpr int COMMAND_TURN_OFF = COMMAND_ID + 3;
constexpr int COMMAND_ON_NOTIFY = COMMAND_ID + 4;
constexpr int COMMAND_REGISTER_CALLBACK = COMMAND_ID + 5;
constexpr int COMMAND_UNREGISTER_CALLBACK = COMMAND_ID + 6;
constexpr int COMMAND_IS_NFC_OPEN = COMMAND_ID + 7;
constexpr int TAG_SESSION_START_ID = 200;
constexpr int COMMAND_CONNECT = TAG_SESSION_START_ID + 1;
constexpr int COMMAND_RECONNECT = TAG_SESSION_START_ID + 2;
constexpr int COMMAND_DISCONNECT = TAG_SESSION_START_ID + 3;
constexpr int COMMAND_GET_TECHLIST = TAG_SESSION_START_ID + 4;
constexpr int COMMAND_IS_PRESENT = TAG_SESSION_START_ID + 5;
constexpr int COMMAND_IS_NDEF = TAG_SESSION_START_ID + 6;
constexpr int COMMAND_SEND_RAW_FRAME = TAG_SESSION_START_ID + 7;
constexpr int COMMAND_NDEF_READ = TAG_SESSION_START_ID + 8;
constexpr int COMMAND_NDEF_WRITE = TAG_SESSION_START_ID + 9;
constexpr int COMMAND_NDEF_MAKE_READ_ONLY = TAG_SESSION_START_ID + 10;
constexpr int COMMAND_FORMAT_NDEF = TAG_SESSION_START_ID + 11;
constexpr int COMMAND_CAN_MAKE_READ_ONLY = TAG_SESSION_START_ID + 12;
constexpr int COMMAND_GET_MAX_TRANSCEIVE_LENGTH = TAG_SESSION_START_ID + 13;
constexpr int COMMAND_IS_SUPPORTED_APDUS_EXTENDED = TAG_SESSION_START_ID + 14;
enum NfcErrorCode : const int {
NFC_SUCCESS = 0,
NFC_FAILED,
// SDK ERROR CODE
NFC_SDK_ERROR_NOT_INITIALIZED = 0x00000100,
NFC_SDK_ERROR_INVALID_PARAM,
NFC_SDK_ERROR_TAG_NOT_CONNECT,
NFC_SDK_ERROR_TAG_INVALID,
NFC_SDK_ERROR_NOT_NDEF_TAG,
NFC_SDK_ERROR_NFC_STATE_INVALID,
NFC_SDK_ERROR_DEVICE_NOT_SUPPORT_NFC,
NFC_SDK_ERROR_DISABLE_MAKE_READONLY,
NFC_SDK_ERROR_UNKOWN,
NFC_SDK_ERROR_PERMISSION,
NFC_SDK_ERROR_CARDEMULATION_CONTROLLER_NOT_INITIALIZED,
NFC_SDK_ERROR_CARDEMULATION_HANDLER_IS_NULL,
// SERVICE ERROR CODE
NFC_SER_ERROR_NOT_INITIALIZED = 0x00000200,
NFC_SER_ERROR_DISCONNECT,
NFC_SER_ERROR_IO,
NFC_SER_ERROR_INVALID_PARAM
};
enum NfcState { STATE_OFF = 1, STATE_TURNING_ON = 2, STATE_ON = 3, STATE_TURNING_OFF = 4 };
enum NfcTask { TASK_TURN_ON = 101, TASK_TURN_OFF, TASK_INITIALIZE };
enum class TagTechnology {
NFC_INVALID_TECH = 0,
NFC_A_TECH = 1,
NFC_B_TECH = 2,
NFC_ISODEP_TECH = 3,
NFC_F_TECH = 4, // Felica
NFC_V_TECH = 5, // ISO15693
NFC_NDEF_TECH = 6,
NFC_MIFARE_CLASSIC_TECH = 8,
NFC_MIFARE_ULTRALIGHT_TECH = 9,
NFC_NDEF_FORMATABLE_TECH = 10
};
class NfcSdkCommon final {
public:
static const int SHIFT_SIZE = 8;
static const int SHIFT_TIME = 4;
public:
static bool IsLittleEndian();
static std::string UnsignedCharArrayToString(const unsigned char* charArray, uint32_t length);
static void StringToUnsignedCharArray(std::string &src, std::vector<unsigned char> &dst);
static std::string IntToString(uint32_t num, bool bLittleEndian = true);
static uint32_t StringToInt(std::string src, bool bLittleEndian = true);
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif // NFC_SDK_COMMON_H
@@ -1,50 +0,0 @@
/*
* 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 BASIC_TAG_SESSION_H
#define BASIC_TAG_SESSION_H
#include "itag_session.h"
#include "taginfo.h"
namespace OHOS {
namespace NFC {
namespace KITS {
class BasicTagSession {
public:
explicit BasicTagSession(std::weak_ptr<TagInfo> tagInfo, KITS::TagTechnology technology);
virtual ~BasicTagSession() {}
int Connect();
bool IsConnected() const;
int Close();
std::string GetTagUid();
std::string SendCommand(std::string& data, bool raw, int& response);
int GetMaxSendCommandLength() const;
protected:
OHOS::sptr<TAG::ITagSession> GetRemoteTagSession() const;
int GetTagRfDiscId() const;
void SetConnectedTagTech(KITS::TagTechnology tech) const;
KITS::TagTechnology GetConnectedTagTech() const;
private:
std::weak_ptr<TagInfo> tagInfo_;
KITS::TagTechnology tagTechnology_;
bool isConnected_;
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif // BASIC_TAG_SESSION_H
@@ -1,115 +0,0 @@
/*
* 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 ISO15693_TAG_H
#define ISO15693_TAG_H
#include "basic_tag_session.h"
namespace OHOS {
namespace NFC {
namespace KITS {
class Iso15693Tag final : public BasicTagSession {
public:
static const int ISO15693_MAX_BLOCK_INDEX = 256;
static const int ISO15693_MAX_FLAG_COUNT = 256;
static const int CMD_READ_SINGLE_BLOCK = 0x20;
static const int CMD_WRITE_SINGLE_BLOCK = 0x21;
static const int CMD_LOCK_SINGLE_BLOCK = 0x22;
static const int CMD_READ_MULTIPLE_BLOCK = 0x23;
static const int CMD_WRITE_MULTIPLE_BLOCK = 0x24;
public:
explicit Iso15693Tag(std::weak_ptr<TagInfo> tag);
~Iso15693Tag();
/**
* @Description Get an object of Iso15693 for the given tag
* @param tag compatible with all types of tag
* @return std::shared_ptr<Iso15693Tag>
*/
static std::shared_ptr<Iso15693Tag> GetTag(std::weak_ptr<TagInfo> tag);
/**
* @Description Read a block
* @param flag If the Option_flag is not set, the VICC shall return its response when it has completed the lock
* operation. If it is set, the VICC shall wait for the reception of an EOF from the VCD and upon such reception
* shall return its response.
* @param blockIndex index of block to read
* @return the block data
*/
std::string ReadSingleBlock(uint32_t flag, uint32_t blockIndex);
/**
* @Description Write a block
* @param flag If the Option_flag is not set, the VICC shall return its response when it has completed the lock
* operation. If it is set, the VICC shall wait for the reception of an EOF from the VCD and upon such reception
* shall return its response.
* @param blockIndex index of block to write
* @param data block data to write
* @return Errorcode of write. if return 0, means successful.
*/
int WriteSingleBlock(uint32_t flag, uint32_t blockIndex, const std::string& data);
/**
* @Description Lock a block. A locked block can only be read, not written.
* @param flag If the Option_flag is not set, the VICC shall return its response when it has completed the lock
* operation. If it is set, the VICC shall wait for the reception of an EOF from the VCD and upon such reception
* shall return its response.
* @param blockIndex index of block to lock
* @return Errorcode of lock. if return 0, means successful.
*/
int LockSingleBlock(uint32_t flag, uint32_t blockIndex);
/**
* @Description Read multiple blocks
* @param flag If the Option_flag is not set, the VICC shall return its response when it has completed the lock
* operation. If it is set, the VICC shall wait for the reception of an EOF from the VCD and upon such reception
* shall return its response.
* @param blockIndex index of block to read
* @param blockNum num of block to read
* @return multiple block data
*/
std::string ReadMultipleBlock(uint32_t flag, uint32_t blockIndex, uint32_t blockNum);
/**
* @Description Write multiple blocks
* @param flag If the Option_flag is not set, the VICC shall return its response when it has completed the lock
* operation. If it is set, the VICC shall wait for the reception of an EOF from the VCD and upon such reception
* shall return its response.
* @param blockIndex index of block to write
* @param blockNum num of block to write
* @param data block data to write
* @param data data of multiple blocks to write
* @param dataLen total data length to write
* @return Errorcode of write. if return 0, means successful.
*/
int WriteMultipleBlock(uint32_t flag, uint32_t blockIndex, uint32_t blockNum, const std::string& data);
/**
* @Description Get DsfId bytes of the tag.
* @param void
* @return DsfId bytes
*/
char GetDsfId() const;
/**
* @Description Get RespFlags bytes of the tag.
* @param void
* @return RespFlags bytes
*/
char GetRespFlags() const;
private:
char respFlags_ {};
char dsfId_ {};
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif // ISO15693_TAG_H
@@ -1,62 +0,0 @@
/*
* 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 ISODEP_TAG_H
#define ISODEP_TAG_H
#include "basic_tag_session.h"
namespace OHOS {
namespace NFC {
namespace KITS {
class IsoDepTag final : public BasicTagSession {
public:
explicit IsoDepTag(std::weak_ptr<TagInfo> tag);
~IsoDepTag() {}
/**
* @Description Get an object of IsoDep for the given tag. It corresponding T1T(14443A-3) and T4T(14443A-4,
* 14443B-4(Type-B)) defined by NFC Forum.
* @param tag compatible with all types of tag
* @return std::shared_ptr<IsoDepTag>
*/
static std::shared_ptr<IsoDepTag> GetTag(std::weak_ptr<TagInfo> tag);
/**
* @Description Get Historical bytes of the tag.
* @param void
* @return Historical bytes
*/
std::string GetHistoricalBytes() const;
/**
* @Description Get HiLayerResponse bytes of the tag.
* @param void
* @return HiLayerResponse bytes
*/
std::string GetHiLayerResponse() const;
/**
* @Description is supported for 3 bytes length APUDs to send, the max length is 65535 bytes.
* @param void
* @return true supported for max APUDs, otherwise unsupported.
*/
bool IsExtendedApduSupported() const;
private:
std::string historicalBytes_ {};
std::string hiLayerResponse_ {};
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif // ISODEP_TAG_H
@@ -1,166 +0,0 @@
/*
* 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 I_TAG_SESSION_H
#define I_TAG_SESSION_H
#include "iremote_broker.h"
#include "nfc_sdk_common.h"
#include "parcel.h"
namespace OHOS {
namespace NFC {
namespace TAG {
class ResResult : public OHOS::Parcelable {
public:
ResResult() : result(RESULT_FAILURE), resData("") {}
virtual ~ResResult() {}
bool Marshalling(OHOS::Parcel &parcel) const override
{
parcel.WriteInt32(result);
parcel.WriteString(resData);
return true;
}
static ResResult* Unmarshalling(OHOS::Parcel &parcel)
{
ResResult* res = new ResResult();
res->SetResult(parcel.ReadInt32());
res->SetResData(parcel.ReadString());
return res;
}
void SetResult(int32_t r)
{
result = r;
}
int32_t GetResult() const
{
return result;
}
void SetResData(const std::string data)
{
resData = data;
}
std::string GetResData() const
{
return resData;
}
enum ResponseResult { RESULT_SUCCESS = 0, RESULT_EXCEEDED_LENGTH, RESULT_TAGLOST, RESULT_FAILURE };
private:
int32_t result;
std::string resData;
};
class ITagSession : public OHOS::IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.nfc.TAG.ITagSession");
virtual ~ITagSession() {}
/**
* @brief To connect the tagRfDiscId by technology.
* @param tagRfDiscId the rf disc id of tag
* @param technology the tag technology
* @return the result to connect the tag
*/
virtual int Connect(int tagRfDiscId, int technology) = 0;
/**
* @brief To reconnect the tagRfDiscId.
* @param tagRfDiscId the rf disc id of tag
* @return the result to reconnect the tag
*/
virtual int Reconnect(int tagRfDiscId) = 0;
/**
* @brief To disconnect the tagRfDiscId.
* @param tagRfDiscId the rf disc id of tag
*/
virtual void Disconnect(int tagRfDiscId) = 0;
/**
* @brief Get the TechList of the tagRfDiscId.
* @param tagRfDiscId the rf disc id of tag
* @return TechList
*/
virtual std::vector<int> GetTechList(int tagRfDiscId) = 0;
/**
* @brief Checking the tagRfDiscId is field on.
* @param tagRfDiscId the rf disc id of tag
* @return true - Presnet; the other - No Presnet
*/
virtual bool IsTagFieldOn(int tagRfDiscId) = 0;
/**
* @brief Checking the tagRfDiscId is a Ndef Tag.
* @param tagRfDiscId the rf disc id of tag
* @return true - Ndef Tag; the other - No Ndef Tag
*/
virtual bool IsNdef(int tagRfDiscId) = 0;
/**
* @brief To send the data to the tagRfDiscId.
* @param tagRfDiscId the rf disc id of tag
* @param data the sent data
* @param raw to send whether original data or un-original data
* @return The response result from the host tag
*/
virtual std::unique_ptr<ResResult> SendRawFrame(int tagRfDiscId, std::string data, bool raw) = 0;
/**
* @brief Reading from the host tag
* @param tagRfDiscId the rf disc id of tag
* @return the read data
*/
virtual std::string NdefRead(int tagRfDiscId) = 0;
/**
* @brief Writing the data into the host tag.
* @param tagRfDiscId the rf disc id of tag
* @param msg the wrote data
* @return the Writing Result
*/
virtual int NdefWrite(int tagRfDiscId, std::string msg) = 0;
/**
* @brief Making the host tag to read only.
* @param tagRfDiscId the rf disc id of tag
* @return the making result
*/
virtual int NdefMakeReadOnly(int tagRfDiscId) = 0;
/**
* @brief format the tag by Ndef
* @param tagRfDiscId the rf disc id of tag
* @param key the format key
* @return the format result
*/
virtual int FormatNdef(int tagRfDiscId, const std::string& key) = 0;
/**
* @brief Checking the host tag is Read only
* @param technology the tag technology
* @return true - ReadOnly; false - No Read Only
*/
virtual bool CanMakeReadOnly(int technology) = 0;
/**
* @brief Get Max Transceive Length
* @param technology the tag technology
* @return Max Transceive Length
*/
virtual int GetMaxTransceiveLength(int technology) = 0;
/**
* @brief Checking the NfccHost whether It supported the extended Apdus
* @return true - yes; false - no
*/
virtual bool IsSupportedApdusExtended() = 0;
private:
};
} // namespace TAG
} // namespace NFC
} // namespace OHOS
#endif // I_TAG_SESSION_H
@@ -1,177 +0,0 @@
/*
* 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 MIFARE_CLASSIC_TAG_H
#define MIFARE_CLASSIC_TAG_H
#include "basic_tag_session.h"
namespace OHOS {
namespace NFC {
namespace KITS {
class MifareClassicTag final : public BasicTagSession {
public:
enum EmMifareTagType { TYPE_UNKNOWN = -1, TYPE_CLASSIC = 0, TYPE_PLUS = 1, TYPE_PRO = 2 };
static const int SAK01 = 0x01;
static const int SAK08 = 0x08;
static const int SAK09 = 0x09;
static const int SAK10 = 0x10;
static const int SAK11 = 0x11;
static const int SAK18 = 0x18;
static const int SAK28 = 0x28;
static const int SAK38 = 0x38;
static const int SAK88 = 0x88;
static const int SAK98 = 0x98;
static const int SAKB8 = 0xB8;
static const int MC_BLOCK_SIZE = 16;
static const int MC_MAX_BLOCK_INDEX = 256;
static const int MC_KEY_LEN = 6;
static const char MC_KEY_DEFAULT[MC_KEY_LEN]; // 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
static const char MC_KEY_MIFARE_APPLICATION_DIRECTORY[MC_KEY_LEN]; // 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5
static const char MC_KEY_NFC_FORUM[MC_KEY_LEN]; // 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7
// sector 0-324 blocks per sector sector 33-40, 16 blocks per sector
static const int MC_BLOCK_COUNT = 4;
static const int MC_BLOCK_COUNT_OF_4K = 16;
// 5 sectors per tag 4 blocks per sector
static const int MC_SIZE_MINI = 320;
static const int MC_SECTOR_COUNT_OF_SIZE_MINI = 5;
// 16 sectors per tag 4 blocks per sector
static const int MC_SIZE_1K = 1024;
static const int MC_SECTOR_COUNT_OF_SIZE_1K = 16;
// 32 sectors per tag 4 blocks per sector
static const int MC_SIZE_2K = 2048;
static const int MC_SECTOR_COUNT_OF_SIZE_2K = 32;
// 40 sectors per tag 4 blocks per sector
static const int MC_SIZE_4K = 4096;
static const int MC_MAX_SECTOR_COUNT = 40;
static const char AUTHENTICATION_WITH_KEY_A = 0x60;
static const char AUTHENTICATION_WITH_KEY_B = 0x61;
static const char MIFARE_READ = 0x30;
static const char MIFARE_WRITE = 0xA0;
static const char MIFARE_TRANSFER = 0xB0;
static const char MIFARE_DECREMENT = 0xC0;
static const char MIFARE_INCREMENT = 0xC1;
static const char MIFARE_RESTORE = 0xC2;
public:
explicit MifareClassicTag(std::weak_ptr<TagInfo> tag);
~MifareClassicTag() {}
/**
* @Description Get an object of MifareClassicTag for the given tag.
* @param tag compatible with all types of tag
* @return std::shared_ptr<MifareClassicTag>
*/
static std::shared_ptr<MifareClassicTag> GetTag(std::weak_ptr<TagInfo> tag);
/**
* @Description Authenticate a sector with the key.Only successful authentication sector can be operated.
* @param sectorIndex Index of sector to authenticate
* @param key key(6-byte) to authenticate
* @param bIsKeyA KeyA flag. true means KeyA, otherwise KeyB
* @return Result of authenticattion. if return true, means successful.
*/
bool AuthenticateSector(int sectorIndex, const std::string& key, bool bIsKeyA);
/**
* @Description Read a block
* @param blockIndex index of block to read
* @return the block data
*/
std::string ReadSingleBlock(uint32_t blockIndex);
/**
* @Description Write a block
* @param blockIndex index of block to write
* @param data block data to write
* @return Errorcode of write. if return 0, means successful.
*/
int WriteSingleBlock(uint32_t blockIndex, const std::string& data);
/**
* @Description Increment a value block
* @param blockIndex index of block to increment
* @param value value to increment, none-negative
* @return Errorcode of increment. if return 0, means successful.
*/
int IncrementBlock(uint32_t blockIndex, int value);
/**
* @Description Decrement a value block
* @param blockIndex index of block to decrement
* @param value value to increment, none-negative
* @return Errorcode of decrement. if return 0, means successful.
*/
int DecrementBlock(uint32_t blockIndex, int value);
/**
* @Description Copy from the value of register to the value block
* @param blockIndex index of value block to copy to
* @return Errorcode of operation. if return 0, means successful.
*/
int TransferToBlock(uint32_t blockIndex);
/**
* @Description Copy from the value block to the register
* @param blockIndex index of value block to copy from
* @return Errorcode of operation. if return 0, means successful.
*/
int RestoreFromBlock(uint32_t blockIndex);
/**
* @Description Get the number of sectors in mifareclassic tag
* @param void
* @return the number of sectors.
*/
int GetSectorCount() const;
/**
* @Description Get the number of blocks in the sector.
* @param sectorIndex index of sector
* @return the number of blocks.
*/
int GetBlockCountInSector(int sectorIndex) const;
/**
* @Description Get the type of the MifareClassic tag in bytes.
* @param void
* @return type of MifareClassic tag.
*/
size_t GetMifareTagType() const;
/**
* @Description Get size of the tag in bytes.
* @param void
* @return size of the tag
*/
int GetSize() const;
/**
* @Description check if if tag is emulated
* @param void
* @return return true if tag is emulated, otherwise return false.
*/
bool IsEmulated() const;
/**
* @Description Get the first block of the sector.
* @param sectorIndex index of sector
* @return index of first block in the sector
*/
int GetBlockIndexFromSector(int sectorIndex) const;
private:
void SetSakSize(int sak);
size_t mifareTagType_ {};
int size_ {};
bool isEmulated_ {};
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif // MIFARE_CLASSIC_TAG_H
@@ -1,70 +0,0 @@
/*
* 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 MIFARE_ULTRALIGHT_TAG_H
#define MIFARE_ULTRALIGHT_TAG_H
#include "basic_tag_session.h"
namespace OHOS {
namespace NFC {
namespace KITS {
class MifareUltralightTag final : public BasicTagSession {
public:
static const int NXP_MANUFACTURER_ID = 0x04;
static const int MU_MAX_PAGE_COUNT = 256;
static const int MU_PAGE_SIZE = 4;
static const char MIFARE_ULTRALIGHT_READ = 0x30;
static const char MIFARE_ULTRALIGHT_WRITE = 0xA2;
enum EmMifareUltralightType { TYPE_UNKOWN = -1, TYPE_ULTRALIGHT = 1, TYPE_ULTRALIGHT_C = 2 };
public:
explicit MifareUltralightTag(std::weak_ptr<TagInfo> tag);
~MifareUltralightTag();
/**
* @Description Get an object of MifareUltralightTag for the given tag.
* @param tag compatible with all types of tag
* @return std::shared_ptr<MifareUltralightTag>
*/
static std::shared_ptr<MifareUltralightTag> GetTag(std::weak_ptr<TagInfo> tag);
/**
* @Description Read 4 pages(16 bytes).
* @param pageIndex index of page to read
* @return 4 pages data
*/
std::string ReadMultiplePages(uint32_t pageIndex);
/**
* @Description Write a page
* @param pageIndex index of page to write
* @param data page data to write
* @return Errorcode of write. if return 0, means successful.
*/
int WriteSinglePages(uint32_t pageIndex, const std::string& data);
/**
* @Description Get the type of the MifareUltralight tag in bytes.
* @param void
* @return type of MifareUltralight tag.
*/
EmMifareUltralightType GetType() const;
private:
EmMifareUltralightType type_ {EmMifareUltralightType::TYPE_UNKOWN};
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif // MIFARE_ULTRALIGHT_TAG_H
@@ -1,56 +0,0 @@
/*
* 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 NDEF_FORMATABLE_TAG_H
#define NDEF_FORMATABLE_TAG_H
#include "basic_tag_session.h"
#include "ndef_message.h"
namespace OHOS {
namespace NFC {
namespace KITS {
class NdefFormatableTag final : public BasicTagSession {
public:
explicit NdefFormatableTag(std::weak_ptr<TagInfo> tag);
~NdefFormatableTag() {}
/**
* @Description Get an object of NdefFormatableTag for the given tag.
* @param tag compatible with all types of tag
* @return std::shared_ptr<NdefFormatableTag>
*/
static std::shared_ptr<NdefFormatableTag> GetTag(std::weak_ptr<TagInfo> tag);
/**
* @Description format a tag as NDEF tag, then write Ndef message into the Ndef Tag
* @param firstMessage Ndef message to write while format successful. it can be null, then only format the tag, not
* write tag
* @return Errorcode of operation. if return 0, means successful.
*/
int Format(std::weak_ptr<NdefMessage> firstMessage);
/**
* @Description format a tag as NDEF tag, then write Ndef message into the Ndef Tag, then set the tag readonly
* @param firstMessage Ndef message to write while format successful. it can be null, then only format the tag, not
* write tag
* @return Errorcode of operation. if return 0, means successful.
*/
int FormatReadOnly(std::weak_ptr<NdefMessage> firstMessage);
private:
int Format(std::weak_ptr<NdefMessage> firstMessage, bool bMakeReadOnly);
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif // NDEF_FORMATABLE_TAG_H
@@ -1,229 +0,0 @@
/*
* 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 NDEF_MESSAGE_H
#define NDEF_MESSAGE_H
#include <array>
#include <string>
#include <vector>
namespace OHOS {
namespace NFC {
namespace KITS {
// record data, see NFC Data Exchange Format (NDEF) Technical Specification.
struct NdefRecord {
size_t tnf_;
std::string id_;
std::string payload_;
std::string tagRtdType_;
};
// layout, see NFC Data Exchange Format (NDEF) Technical Specification.
struct RecordLayout {
bool mb; // message begin
bool me; // message end
bool cf; // chunk flag
bool sr; // short record
bool il; // id length
char tnf; // type name format
uint8_t typeLength;
uint32_t payloadLength;
uint8_t idLength;
};
// URI charactor code defined by NFC Forum
static const size_t MAX_URI_CODE_NUM = 0x24;
static std::array<std::string, MAX_URI_CODE_NUM> gUriPrefix = {
"", // NFC Forum define value: 0x00
"http://www.", // NFC Forum define value: 0x01
"https://www.", // NFC Forum define value: 0x02
"http://", // NFC Forum define value: 0x03
"https://", // NFC Forum define value: 0x04
"tel:", // NFC Forum define value: 0x05
"mailto:", // NFC Forum define value: 0x06
"ftp://anonymous:anonymous@", // NFC Forum define value: 0x07
"ftp://ftp.", // NFC Forum define value: 0x08
"ftps://", // NFC Forum define value: 0x09
"sftp://", // NFC Forum define value: 0x0A
"smb://", // NFC Forum define value: 0x0B
"nfs://", // NFC Forum define value: 0x0C
"ftp://", // NFC Forum define value: 0x0D
"dav://", // NFC Forum define value: 0x0E
"news:", // NFC Forum define value: 0x0F
"telnet://", // NFC Forum define value: 0x10
"imap:", // NFC Forum define value: 0x11
"rtsp://", // NFC Forum define value: 0x12
"urn:", // NFC Forum define value: 0x13
"pop:", // NFC Forum define value: 0x14
"sip:", // NFC Forum define value: 0x15
"sips:", // NFC Forum define value: 0x16
"tftp:", // NFC Forum define value: 0x17
"btspp://", // NFC Forum define value: 0x18
"btl2cap://", // NFC Forum define value: 0x19
"btgoep://", // NFC Forum define value: 0x1A
"tcpobex://", // NFC Forum define value: 0x1B
"irdaobex://", // NFC Forum define value: 0x1C
"file://", // NFC Forum define value: 0x1D
"urn:epc:id:", // NFC Forum define value: 0x1E
"urn:epc:tag:", // NFC Forum define value: 0x1F
"urn:epc:pat:", // NFC Forum define value: 0x20
"urn:epc:raw:", // NFC Forum define value: 0x21
"urn:epc:", // NFC Forum define value: 0x22
"urn:nfc:", // NFC Forum define value: 0x23
};
class NdefMessage final {
public:
const int MAX_RTD_TYPE_LEN = 2;
static const long int MAX_PAYLOAD_SIZE = 10 * (1 << 20); // 10MB
static const int SHORT_RECORD_SIZE = 256;
// TNF Type define
enum EmTnfType {
TNF_EMPTY = 0x00,
TNF_WELL_KNOWN = 0x01,
TNF_MIME_MEDIA = 0x02,
TNF_ABSOLUTE_URI = 0x03,
TNF_EXTERNAL_TYPE = 0x04,
TNF_UNKNOWN = 0x05,
TNF_UNCHANGED = 0x06,
TNF_RESERVED = 0x07
};
// record Flag
enum EmRecordFlag {
FLAG_MB = 0x80,
FLAG_ME = 0x40,
FLAG_CF = 0x20,
FLAG_SR = 0x10,
FLAG_IL = 0x08,
FLAG_TNF = 0x07
};
enum EmRtdType {
RTD_INVALID,
RTD_TEXT,
RTD_URI,
RTD_SMART_POSTER,
RTD_ALTERNATIVE_CARRIER,
RTD_HANDOVER_CARRIER,
RTD_HANDOVER_REQUEST,
RTD_HANDOVER_SELECT,
RTD_OHOS_APP
};
public:
NdefMessage(std::vector<std::shared_ptr<NdefRecord>> ndefRecords);
~NdefMessage();
/**
* @Description constructe a ndef message with raw bytes.
* @param data raw bytes to parse ndef message
* @return std::shared_ptr<NdefMessage>
*/
static std::shared_ptr<NdefMessage> GetNdefMessage(const std::string& data);
/**
* @Description constructe a ndef message with record list.
* @param ndefRecords record list to parse ndef message
* @return std::shared_ptr<NdefMessage>
*/
static std::shared_ptr<NdefMessage> GetNdefMessage(std::vector<std::shared_ptr<NdefRecord>> ndefRecords);
/**
* @Description convert the rtd bytes into byte array defined in Nfc forum.
* @param rtdtype rtd type of a record
* @return rtd byte array
*/
static std::string GetTagRtdType(EmRtdType rtdtype);
/**
* @Description Create a ndef record with uri data.
* @param uriString uri data for new a ndef record
* @return std::shared_ptr<NdefRecord>
*/
static std::shared_ptr<NdefRecord> MakeUriRecord(const std::string& uriString);
/**
* @Description Create a ndef record with text data.
* @param text text data for new a ndef record
* @param locale language code for the ndef record . if locale is null, use default locale
* @return std::shared_ptr<NdefRecord>
*/
static std::shared_ptr<NdefRecord> MakeTextRecord(const std::string& text, const std::string& locale);
/**
* @Description Create a ndef record with mime data.
* @param mimeType type of mime data for new a ndef record
* @param mimeData mime data for new a ndef record
* @return std::shared_ptr<NdefRecord>
*/
static std::shared_ptr<NdefRecord> MakeMimeRecord(const std::string& mimeType, const std::string& mimeData);
/**
* @Description Create a ndef record with external data.
* @param domainName domain name of issuing organization for the external data
* @param serviceName domain specific type of data for the external data
* @param externalData data payload of a ndef record
* @return std::shared_ptr<NdefRecord>
*/
static std::shared_ptr<NdefRecord> MakeExternalRecord(const std::string& domainName,
const std::string& serviceName,
const std::string& externalData);
/**
* @Description parse a ndef message into raw bytes.
* @param ndefMessage a ndef message to parse
* @return raw bytes of a ndef message
*/
static std::string MessageToString(std::weak_ptr<NdefMessage> ndefMessage);
/**
* @Description parse a ndef record into raw bytes.
* @param record a ndef record to parse
* @param buffer raw bytes of a ndef record
* @param bIsMB the flag of begin record
* @param bIsME the flag of end record
* @return void
*/
static void NdefRecordToString(std::weak_ptr<NdefRecord> record, std::string& buffer, bool bIsMB, bool bIsME);
/**
* @Description Get all records of a ndef message.
* @param void
* @return record list of a ndef message
*/
std::vector<std::shared_ptr<NdefRecord>> GetNdefRecords() const;
private:
static std::shared_ptr<NdefRecord> CreateNdefRecord(size_t tnf, const std::string& id,
const std::string& payload, const std::string& tagRtdType);
static bool CheckTnf(size_t tnf, const std::string& tagRtdType,
const std::string& id, const std::string& payload);
static std::vector<std::shared_ptr<NdefRecord>> ParseRecord(const std::string& data, bool isMbMeIgnored);
static void ParseRecordLayoutHead(RecordLayout& layout, char head);
static bool IsInvalidRecordLayoutHead(RecordLayout& layout, bool isChunkFound,
uint32_t parsedRecordSize, bool isMbMeIgnored);
static void ParseRecordLayoutLength(RecordLayout& layout, bool isChunkFound,
const std::string& data, uint32_t& parsedDataIndex);
static bool IsRecordLayoutLengthInvalid(RecordLayout& layout, bool isChunkFound);
static std::string ParseRecordType(RecordLayout& layout, const std::string& data, uint32_t& parsedDataIndex);
static std::string ParseRecordId(RecordLayout& layout, const std::string& data, uint32_t& parsedDataIndex);
static std::string ParseRecordPayload(RecordLayout& layout, const std::string& data, uint32_t& parsedDataIndex);
static void SaveRecordChunks(RecordLayout& layout, bool isChunkFound, std::vector<std::string>& chunks,
char& chunkTnf, const std::string& payload);
static std::string MergePayloadByChunks(RecordLayout& layout, bool isChunkFound, std::vector<std::string>& chunks,
char chunkTnf, const std::string& payload);
private:
std::vector<std::shared_ptr<NdefRecord>> ndefRecordList_ {};
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif // NDEF_MESSAGE_H
@@ -1,118 +0,0 @@
/*
* 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 NDEF_TAG_H
#define NDEF_TAG_H
#include "basic_tag_session.h"
#include "ndef_message.h"
namespace OHOS {
namespace NFC {
namespace KITS {
class NdefTag final : public BasicTagSession {
public:
enum EmNfcForumType {
NFC_FORUM_TYPE_1_OTHER = -1,
NFC_FORUM_TYPE_1 = 1,
NFC_FORUM_TYPE_2 = 2,
NFC_FORUM_TYPE_3 = 3,
NFC_FORUM_TYPE_4 = 4,
MIFARE_CLASSIC = 101,
ICODE_SLI = 102
};
const std::string STRING_NFC_FORUM_TYPE_1 = "org.nfcforum.ndef.type1";
const std::string STRING_NFC_FORUM_TYPE_2 = "org.nfcforum.ndef.type2";
const std::string STRING_NFC_FORUM_TYPE_3 = "org.nfcforum.ndef.type3";
const std::string STRING_NFC_FORUM_TYPE_4 = "org.nfcforum.ndef.type4";
const std::string STRING_MIFARE_CLASSIC = "com.nxp.ndef.mifareclassic";
const std::string STRING_ICODE_SLI = "com.nxp.ndef.icodesli";
enum EmNdefTagMode { MODE_INVALID, MODE_READ_ONLY, MODE_READ_WRITE, MODE_UNKNOW };
public:
explicit NdefTag(std::weak_ptr<TagInfo> tag);
~NdefTag() {}
/**
* @Description Get an object of NdefTag for the given tag.
* @param tag compatible with all types of tag
* @return std::shared_ptr<NdefTag>
*/
static std::shared_ptr<NdefTag> GetTag(std::weak_ptr<TagInfo> tag);
/**
* @Description Get the type of the Ndef tag in bytes.
* @param void
* @return type of Ndef tag.
*/
EmNfcForumType GetNdefTagType() const;
/**
* @Description Get the mode of the Ndef tag in bytes.(readonly, read/write, unknown)
* @param void
* @return mode of Ndef tag.
*/
EmNdefTagMode GetNdefTagMode() const;
/**
* @Description Get the ndef message that was read from ndef tag when tag discovery.
* @param void
* @return ndef message.
*/
std::shared_ptr<NdefMessage> GetCachedNdefMsg() const;
/**
* @Description Check ndef tag is writable
* @param void
* @return return true if the tag is writable, otherwise return false.
*/
bool IsNdefWritable() const;
/**
* @Description Read ndef tag
* @param void
* @return ndef message in tag.
*/
std::shared_ptr<NdefMessage> ReadNdef();
/**
* @Description write ndef tag
* @param msg ndef message to write
* @return Errorcode of write. if return 0, means successful.
*/
int WriteNdef(std::shared_ptr<NdefMessage> msg);
/**
* @Description check ndef tag can be set read-only
* @param void
* @return return true if the tag can be set readonly, otherwise return false.
*/
bool IsEnableReadOnly();
/**
* @Description set ndef tag read-only
* @param void
* @return Errorcode of write. if return 0, means successful.
*/
int EnableReadOnly();
/**
* @Description convert the Nfc forum type into byte array defined in Nfc forum.
* @param emNfcForumType Nfc forum type of ndef tag
* @return Nfc forum type byte array
*/
std::string GetNdefTagTypeString(EmNfcForumType emNfcForumType);
private:
EmNfcForumType nfcForumType_ {};
EmNdefTagMode ndefTagMode_ {};
std::string ndefMsg_ {};
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif // NDEF_TAG_H
@@ -1,55 +0,0 @@
/*
* 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_A_TAG_H
#define NFC_A_TAG_H
#include "basic_tag_session.h"
namespace OHOS {
namespace NFC {
namespace KITS {
class NfcATag final : public BasicTagSession {
public:
explicit NfcATag(std::weak_ptr<TagInfo> tag);
~NfcATag() {}
/**
* @Description Get an object of IsoDep for the given tag. It corresponding T1T(14443A-3) and T4T(14443A-4,
* 14443B-4(Type-B)) defined by NFC Forum.
* @param tag compatible with all types of tag
* @return std::shared_ptr<NfcATag>
*/
static std::shared_ptr<NfcATag> GetTag(std::weak_ptr<TagInfo> tag);
/**
* @Description Get SAK bytes of the tag.
* @param void
* @return SAK bytes
*/
int GetSak() const;
/**
* @Description Get ATQA bytes of the tag.
* @param void
* @return ATQA bytes
*/
std::string GetAtqa() const;
private:
int sak_ {};
std::string atqa_ {};
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif // NFC_A_TAG_H
@@ -1,55 +0,0 @@
/*
* 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_B_TAG_H
#define NFC_B_TAG_H
#include "basic_tag_session.h"
namespace OHOS {
namespace NFC {
namespace KITS {
class NfcBTag final : public BasicTagSession {
public:
explicit NfcBTag(std::weak_ptr<TagInfo> tag);
~NfcBTag() {}
/**
* @Description Get an object of IsoDep for the given tag. It corresponding T1T(14443A-3) and T4T(14443A-4,
* 14443B-4(Type-B)) defined by NFC Forum.
* @param tag compatible with all types of tag
* @return std::shared_ptr<NfcBTag>
*/
static std::shared_ptr<NfcBTag> GetTag(std::weak_ptr<TagInfo> tag);
/**
* @Description Get AppData bytes of the tag.
* @param void
* @return AppData bytes
*/
std::string GetAppData() const;
/**
* @Description Get ProtocolInfo bytes of the tag.
* @param void
* @return ProtocolInfo bytes
*/
std::string GetProtocolInfo() const;
private:
std::string appData_ {};
std::string protocolInfo_ {};
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif // NFC_B_TAG_H
@@ -1,53 +0,0 @@
/*
* 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 NFCF_TAG_H
#define NFCF_TAG_H
#include "basic_tag_session.h"
namespace OHOS {
namespace NFC {
namespace KITS {
class NfcFTag final : public BasicTagSession {
public:
explicit NfcFTag(std::weak_ptr<TagInfo> tag);
~NfcFTag() {}
/**
* @Description Get an object of NfcFTag for the given tag.
* @param tag compatible with all types of tag
* @return std::shared_ptr<NfcFTag>
*/
static std::shared_ptr<NfcFTag> GetTag(std::weak_ptr<TagInfo> tag);
/**
* @Description Obtains the system code from this {@code NfcFTag} instance.
* @param void
* @return The system code
*/
std::vector<unsigned char> getSystemCode() const;
/**
* @Description Obtains the PMm (consisting of the IC code and manufacturer parameters).
* @param void
* @return THe PMm
*/
std::vector<unsigned char> getPmm() const;
private:
std::vector<unsigned char> systemCode_;
std::vector<unsigned char> pmm_;
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif // NFCF_TAG_H
@@ -1,53 +0,0 @@
/*
* 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 TAG_SESSION_PROXY_H
#define TAG_SESSION_PROXY_H
#include "iremote_proxy.h"
#include "itag_session.h"
#include "nfc_basic_proxy.h"
namespace OHOS {
namespace NFC {
namespace TAG {
class TagSessionProxy final : public OHOS::IRemoteProxy<ITagSession>, public NfcBasicProxy {
public:
explicit TagSessionProxy(const OHOS::sptr<OHOS::IRemoteObject>& remote)
: OHOS::IRemoteProxy<ITagSession>(remote), NfcBasicProxy(remote)
{
}
~TagSessionProxy() override {}
int Connect(int tagRfDiscId, int technology) override;
int Reconnect(int tagRfDiscId) override;
void Disconnect(int tagRfDiscId) override;
std::vector<int> GetTechList(int tagRfDiscId) override;
bool IsTagFieldOn(int tagRfDiscId) override;
bool IsNdef(int tagRfDiscId) override;
std::unique_ptr<ResResult> SendRawFrame(int tagRfDiscId, std::string data, bool raw) override;
std::string NdefRead(int tagRfDiscId) override;
int NdefWrite(int tagRfDiscId, std::string msg) override;
int NdefMakeReadOnly(int tagRfDiscId) override;
int FormatNdef(int tagRfDiscId, const std::string& key) override;
bool CanMakeReadOnly(int technology) override;
int GetMaxTransceiveLength(int technology) override;
bool IsSupportedApdusExtended() override;
private:
};
} // namespace TAG
} // namespace NFC
} // namespace OHOS
#endif // TAG_SESSION_PROXY_H
@@ -1,98 +0,0 @@
/*
* 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 TAG_INFO_H
#define TAG_INFO_H
#include "itag_session.h"
#include "nfc_basic_proxy.h"
#include "nfc_sdk_common.h"
#include "pac_map.h"
#include "parcel.h"
namespace OHOS {
namespace NFC {
namespace KITS {
class TagInfo final : public Parcelable {
public:
static const int MAX_TAG_TECH_NUM = 10;
static const int SEND_COMMAND_HEAD_LEN_2 = 2;
static const int SEND_COMMAND_MAX_LEN = 256;
// define TagExternData Name
static constexpr const auto TECH_EXTRA_DATA_PREFIX = "Tech_Extra_Data_";
// ISODEP
static constexpr const auto HISTORICAL_BYTES = "HistoricalBytes";
static constexpr const auto HILAYER_RESPONSE = "HiLayerResponse";
// iso 14443-3a
static constexpr const auto SAK = "Sak";
static constexpr const auto ATQA = "Atqa";
// iso 14443-3b
static constexpr const auto APP_DATA = "AppData";
static constexpr const auto PROTOCOL_INFO = "ProtocolInfo";
// NDEF
static constexpr const auto NDEF_MSG = "NdefMsg";
static constexpr const auto NDEF_FORUM_TYPE = "NdefForumType";
static constexpr const auto NDEF_TAG_MODE = "NdefTagMode";
// MifareUltralight
static constexpr const auto MIFARE_ULTRALIGHT_C_TYPE = "MifareUltralightC";
// Iso15693
static constexpr const auto RESPONSE_FLAGS = "ResponseFlags";
static constexpr const auto DSF_ID = "DsfId";
// NfcF, Feilica
static constexpr const auto NFCF_SC = "SystemCode";
static constexpr const auto NFCF_PMM = "Pmm";
public:
TagInfo(std::vector<int> tagTechList,
std::weak_ptr<AppExecFwk::PacMap> tagTechExtrasData,
std::string& tagUid,
int tagRfDiscId,
OHOS::sptr<TAG::ITagSession> tagSession);
~TagInfo();
std::string GetTagUid() const;
std::vector<int> GetTagTechList() const;
bool Marshalling(Parcel& parcel) const override;
static std::shared_ptr<TagInfo> Unmarshalling(Parcel& parcel);
std::string GetStringExtrasData(AppExecFwk::PacMap& extrasData, const std::string& extrasName);
int GetIntExtrasData(AppExecFwk::PacMap& extrasData, const std::string& extrasName);
std::weak_ptr<AppExecFwk::PacMap> GetTagExtrasData() const;
AppExecFwk::PacMap GetTechExtrasData(KITS::TagTechnology tech);
bool IsTechSupported(KITS::TagTechnology tech);
int GetTagRfDiscId() const;
KITS::TagTechnology GetConnectedTagTech() const;
void SetConnectedTagTech(KITS::TagTechnology connectedTagTech);
private:
OHOS::sptr<TAG::ITagSession> GetRemoteTagSession() const;
private:
int tagRfDiscId_;
KITS::TagTechnology connectedTagTech_;
std::string tagUid_;
std::vector<int> tagTechList_;
OHOS::sptr<TAG::ITagSession> remoteTagSession_;
std::shared_ptr<AppExecFwk::PacMap> tagTechExtrasData_;
friend class BasicTagSession;
friend class NdefTag;
friend class NdefFormatableTag;
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif // TAG_INFO_H
@@ -1,133 +0,0 @@
/*
* 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_controller.h"
#include "loghelper.h"
#include "nfc_controller_callback_stub.h"
#include "nfc_sdk_common.h"
#include "infc_controller_callback.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace NFC {
namespace KITS {
std::shared_ptr<OHOS::NFC::NfcControllerProxy> NfcController::nfcControllerProxy_;
std::weak_ptr<INfcControllerService> NfcController::nfcControllerService_;
bool NfcController::initialized_ = false;
std::mutex NfcController::mutex_;
NfcController::NfcController()
{
DebugLog("[NfcController::NfcController] new ability manager");
}
NfcController::~NfcController()
{
DebugLog("destruct NfcController");
}
void NfcController::InitNfcController()
{
DebugLog("NfcController::InitNfcController in.");
std::lock_guard<std::mutex> guard(mutex_);
if (!initialized_ || nfcControllerService_.expired()) {
sptr<ISystemAbilityManager> systemAbilityMgr =
SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
OHOS::sptr<OHOS::IRemoteObject> obj = systemAbilityMgr->GetSystemAbility(NFC_MANAGER_SYS_ABILITY_ID);
if (obj == nullptr) {
DebugLog("Nfc Controller Is Unexist.");
return;
}
nfcControllerProxy_ = std::make_shared<NfcControllerProxy>(obj);
nfcControllerService_ = nfcControllerProxy_;
initialized_ = true;
}
DebugLog("NfcController::InitNfcController success.");
}
NfcController &NfcController::GetInstance()
{
InfoLog("NfcController::GetInstance in.");
InitNfcController();
static NfcController instance;
return instance;
}
// Open NFC
int NfcController::TurnOn()
{
DebugLog("NfcController::TurnOn in.");
if (nfcControllerService_.expired()) {
return NfcErrorCode::NFC_SDK_ERROR_NOT_INITIALIZED;
}
return nfcControllerService_.lock()->TurnOn();
}
// Close NFC
int NfcController::TurnOff()
{
DebugLog("NfcController::TurnOff in.");
if (nfcControllerService_.expired()) {
return NfcErrorCode::NFC_SDK_ERROR_NOT_INITIALIZED;
}
return nfcControllerService_.lock()->TurnOff();
}
// get NFC state
int NfcController::GetNfcState()
{
if (nfcControllerService_.expired()) {
return NfcState::STATE_OFF;
}
return nfcControllerService_.lock()->GetState();
}
// check whether NFC is supported
int NfcController::IsNfcAvailable()
{
DebugLog("NfcController::IsNfcAvailable");
return true;
}
// check whether NFC is enabled
int NfcController::IsNfcOpen()
{
if (nfcControllerService_.expired()) {
return NfcErrorCode::NFC_SDK_ERROR_NOT_INITIALIZED;
}
DebugLog("NfcController::IsNfcOpen");
return nfcControllerService_.lock()->IsNfcOpen();
}
// register NFC state change callback
NfcErrorCode NfcController::RegListener(const sptr<INfcControllerCallback> &callback,
const std::string& type)
{
DebugLog("NfcController::RegListener");
return nfcControllerService_.lock()->RegisterCallBack(callback, type);
}
// unregister NFC state change
NfcErrorCode NfcController::UnregListener(const std::string& type)
{
DebugLog("NfcController::UnregListener");
return nfcControllerService_.lock()->UnRegisterCallBack(type);
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,96 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_controller_callback_stub.h"
#include "nfc_sdk_common.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
NfcControllerCallBackStub::NfcControllerCallBackStub() : callback_(nullptr), mRemoteDied(false)
{}
NfcControllerCallBackStub::~NfcControllerCallBackStub()
{}
NfcControllerCallBackStub& NfcControllerCallBackStub::GetInstance()
{
static NfcControllerCallBackStub NfcControllerCallBackStub;
return NfcControllerCallBackStub;
}
void NfcControllerCallBackStub::OnNfcStateChanged(int nfcRfState)
{
if (callback_) {
DebugLog("NfcControllerCallBackStub callback_");
callback_->OnNfcStateChanged(nfcRfState);
}
}
int NfcControllerCallBackStub::OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
DebugLog("NfcControllerCallBackStub::OnRemoteRequest,code = %{public}d", code);
if (mRemoteDied) {
return KITS::NFC_FAILED;
}
if (data.ReadInterfaceToken() != GetDescriptor()) {
InfoLog("nfc callback stub token verification error");
return KITS::NFC_FAILED;
}
int exception = data.ReadInt32();
if (exception) {
InfoLog("ConnectedTagCallBackStub::OnRemoteRequest, got exception: (%{public}d))", exception);
return KITS::NFC_FAILED;
}
int ret = KITS::NFC_FAILED;
switch (code) {
case KITS::COMMAND_ON_NOTIFY: {
ret = RemoteNfcStateChanged(data, reply);
break;
}
default: {
ret = IPCObjectStub::OnRemoteRequest(code, data, reply, option);
break;
}
}
return ret;
}
KITS::NfcErrorCode NfcControllerCallBackStub::RegisterCallBack(const sptr<INfcControllerCallback> &callBack)
{
DebugLog("NfcControllerCallBackStub RegisterCallBack");
std::shared_lock<std::shared_mutex> guard(callbackMutex);
if (callBack == nullptr) {
DebugLog("RegisterUserCallBack:callBack is nullptr!");
callback_ = callBack;
return KITS::NFC_FAILED;
}
callback_ = callBack;
return KITS::NFC_SUCCESS;
}
int NfcControllerCallBackStub::RemoteNfcStateChanged(MessageParcel &data, MessageParcel &reply)
{
InfoLog("run %{public}zu datasize ", data.GetRawDataSize());
int state = data.ReadInt32();
std::shared_lock<std::shared_mutex> guard(callbackMutex);
OnNfcStateChanged(state);
reply.WriteInt32(KITS::NFC_SUCCESS); /* Reply 0 to indicate that no exception occurs. */
return KITS::NFC_SUCCESS;
}
} // namespace NFC
} // namespace OHOS
@@ -1,166 +0,0 @@
/*
* 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_controller_proxy.h"
#include "loghelper.h"
#include "nfc_controller_callback_stub.h"
#include "nfc_sdk_common.h"
namespace OHOS {
namespace NFC {
const std::string NFC_INTERFACE_TOKEN = "ohos.nfc.INfcController";
static NfcControllerCallBackStub* g_nfcControllerCallbackStub = new NfcControllerCallBackStub;
NfcControllerProxy ::~NfcControllerProxy() {}
bool NfcControllerProxy::TurnOn()
{
DebugLog("NfcControllerProxy::TurnOn in.");
bool result = false;
MessageParcel data;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
DebugLog("Write interface token error");
return KITS::NFC_FAILED;
}
int32_t res = ProcessBoolRes(KITS::COMMAND_TURN_ON, data, option, result);
DebugLog("NfcControllerProxy::TurnOn res=%{public}d", res);
if (res != ERR_NONE) {
DebugLog("NfcControllerProxy::TurnOn error.");
return false;
}
DebugLog("NfcControllerProxy::TurnOn result=%{public}d", result);
return result;
}
bool NfcControllerProxy::TurnOff()
{
DebugLog("NfcControllerProxy::TurnOff in.");
bool result = false;
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor())) {
DebugLog("Write interface token error");
return KITS::NFC_FAILED;
}
MessageOption option;
int res = ProcessBoolRes(KITS::COMMAND_TURN_OFF, data, option, result);
if (res != ERR_NONE) {
DebugLog("NfcControllerProxy::TurnOff error.");
return false;
}
return result;
}
int NfcControllerProxy::GetState()
{
int state = NFC::KITS::STATE_OFF;
MessageParcel data;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
DebugLog("Write interface token error");
return KITS::NFC_FAILED;
}
int res = ProcessIntRes(KITS::COMMAND_GET_STATE, data, option, state);
if (res != ERR_NONE) {
InfoLog("It is failed To Get State with Res(%{public}d).", res);
return NFC::KITS::STATE_OFF;
}
return state;
}
bool NfcControllerProxy::IsNfcOpen()
{
DebugLog("NfcControllerProxy::IsNfcOpen.");
bool result = true;
MessageParcel data;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
DebugLog("Write interface token error");
return KITS::NFC_FAILED;
}
data.WriteInt32(0);
int res = ProcessBoolRes(KITS::COMMAND_IS_NFC_OPEN, data, option, result);
if (res != ERR_NONE) {
DebugLog("NfcControllerProxy::IsNfcOpen error.");
return false;
}
DebugLog("NfcControllerProxy::IsNfcOpen result=%{public}d", result);
return result;
}
KITS::NfcErrorCode NfcControllerProxy::RegisterCallBack(
const sptr<INfcControllerCallback> &callback,
const std::string& type)
{
DebugLog("RegisterCallBack start!");
MessageParcel data;
MessageParcel reply;
MessageOption option(MessageOption::TF_ASYNC);
g_nfcControllerCallbackStub->RegisterCallBack(callback);
if (!data.WriteInterfaceToken(GetDescriptor())) {
DebugLog("Write interface token error");
return KITS::NFC_FAILED;
}
if (!data.WriteString(type)) {
DebugLog("Write type error");
return KITS::NFC_FAILED;
}
data.WriteInt32(0);
if (!data.WriteRemoteObject(g_nfcControllerCallbackStub->AsObject())) {
DebugLog("RegisterCallBack WriteRemoteObject failed!");
return KITS::NFC_FAILED;
}
int error = ProcessCallBackCommand(KITS::COMMAND_REGISTER_CALLBACK, data, reply, option);
if (error != ERR_NONE) {
InfoLog("RegisterCallBack failed, error code is %{public}d", error);
return KITS::NFC_FAILED;
}
int exception = reply.ReadInt32();
if (exception) {
return KITS::NFC_FAILED;
}
return KITS::NFC_SUCCESS;
}
KITS::NfcErrorCode NfcControllerProxy::UnRegisterCallBack(const std::string& type)
{
DebugLog("UnRegisterCallBack start!");
MessageParcel data;
MessageParcel reply;
MessageOption option(MessageOption::TF_ASYNC);
if (!data.WriteInterfaceToken(GetDescriptor())) {
DebugLog("Write interface token error");
return KITS::NFC_FAILED;
}
if (!data.WriteString(type)) {
DebugLog("Write type error");
return KITS::NFC_FAILED;
}
data.WriteInt32(0);
int error = ProcessCallBackCommand(KITS::COMMAND_UNREGISTER_CALLBACK, data, reply, option);
if (error != ERR_NONE) {
InfoLog("RegisterCallBack failed, error code is %{public}d", error);
return KITS::NFC_FAILED;
}
int exception = reply.ReadInt32();
if (exception) {
return KITS::NFC_FAILED;
}
return KITS::NFC_SUCCESS;
}
} // namespace NFC
} // namespace OHOS
@@ -1,60 +0,0 @@
/*
* 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_basic_proxy.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
int NfcBasicProxy::ProcessIntRes(int cmd, MessageParcel& data, MessageOption& option, int& result)
{
MessageParcel reply;
int res = remoteObj_->SendRequest(cmd, data, reply, option);
if (res == ERR_NONE) {
result = reply.ReadInt32();
InfoLog("It is successful To send request %{public}d with Res %{public}d.", cmd, res);
} else {
InfoLog("It is failed To send request(%{public}d) with Res(%{public}d).", cmd, res);
}
return res;
}
int NfcBasicProxy::ProcessBoolRes(int cmd, MessageParcel& data, MessageOption& option, bool& result)
{
MessageParcel reply;
int32_t res = remoteObj_->SendRequest(cmd, data, reply, option);
if (res == ERR_NONE) {
result = reply.ReadInt32();
InfoLog("It is successful To send request(%{public}d) with Res(%{public}d) result(%{public}d).",
cmd, res, result);
} else {
InfoLog("It is failed To send request(%{public}d) with Res(%{public}d).", cmd, res);
}
return res;
}
int NfcBasicProxy::ProcessCommand(int cmd, MessageParcel& data, MessageOption& option)
{
MessageParcel reply;
return remoteObj_->SendRequest(cmd, data, reply, option);
}
int NfcBasicProxy::ProcessCallBackCommand(int cmd, MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
InfoLog("ProcessCommand To send request %{public}d", cmd);
return remoteObj_->SendRequest(cmd, data, reply, option);
}
} // namespace NFC
} // namespace OHOS
@@ -1,90 +0,0 @@
/*
* Copyright (C) 2021 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_sdk_common.h"
#include <sstream>
namespace OHOS {
namespace NFC {
namespace KITS {
bool NfcSdkCommon::IsLittleEndian()
{
const char LAST_DATA_BYTE = 0x78;
union CheckData {
int x;
char y;
};
union CheckData data;
data.x = 0x12345678;
if (data.y == LAST_DATA_BYTE) {
return true;
}
return false;
}
std::string NfcSdkCommon::UnsignedCharArrayToString(const unsigned char* charArray, uint32_t length)
{
std::string result = "";
for (uint32_t i = 0; i < length; i++) {
result += charArray[i];
}
return result;
}
void NfcSdkCommon::StringToUnsignedCharArray(std::string &src, std::vector<unsigned char> &dst)
{
if (src.empty()) {
return;
}
uint32_t len = src.length();
for (uint32_t i = 0; i < len; i++) {
dst.push_back((unsigned char) src[i]);
}
}
std::string NfcSdkCommon::IntToString(uint32_t num, bool bLittleEndian)
{
std::stringstream ss;
if (bLittleEndian) {
for (size_t i = 0; i < SHIFT_TIME; i++) {
ss << char((num >> (i * SHIFT_SIZE)) & 0xFF);
}
} else {
for (size_t i = SHIFT_TIME; i > 0; i--) {
ss << char((num >> (i * SHIFT_SIZE - SHIFT_SIZE)) & 0xFF);
}
}
return ss.str();
}
uint32_t NfcSdkCommon::StringToInt(std::string src, bool bLittleEndian)
{
uint32_t value = 0;
if (bLittleEndian) {
for (size_t i = SHIFT_TIME; i > 0; i--) {
value += (uint32_t)(src.at(SHIFT_TIME - i)) << (i * SHIFT_SIZE - SHIFT_SIZE);
}
} else {
for (size_t i = 0; i < SHIFT_TIME; i++) {
value += (uint32_t)(src.at(i)) << (i * SHIFT_SIZE);
}
}
return value;
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,154 +0,0 @@
/*
* 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 "basic_tag_session.h"
#include "loghelper.h"
#include "nfc_sdk_common.h"
namespace OHOS {
namespace NFC {
namespace KITS {
BasicTagSession::BasicTagSession(std::weak_ptr<TagInfo> tagInfo, KITS::TagTechnology technology)
: tagInfo_(tagInfo), tagTechnology_(technology), isConnected_(false)
{
}
int BasicTagSession::Connect()
{
if (tagInfo_.expired()) {
return NfcErrorCode::NFC_SDK_ERROR_TAG_INVALID;
}
OHOS::sptr<TAG::ITagSession> tagSession = tagInfo_.lock()->GetRemoteTagSession();
if (!tagSession) {
return NfcErrorCode::NFC_SDK_ERROR_NOT_INITIALIZED;
}
int tagRfDiscId = GetTagRfDiscId();
int res = tagSession->Connect(tagRfDiscId, static_cast<int>(tagTechnology_));
DebugLog("connect tag.%{public}d tech.%{public}d res.%{public}d. ", tagRfDiscId, tagTechnology_, res);
if (res == NfcErrorCode::NFC_SUCCESS) {
isConnected_ = true;
SetConnectedTagTech(tagTechnology_);
}
return res;
}
bool BasicTagSession::IsConnected() const
{
KITS::TagTechnology connectedTagTech = GetConnectedTagTech();
if ((connectedTagTech != tagTechnology_) || (connectedTagTech == KITS::TagTechnology::NFC_INVALID_TECH)) {
return false;
}
return true;
}
int BasicTagSession::Close()
{
/* Note that we don't want to physically disconnect the tag,
* but just reconnect to it to reset its state
*/
OHOS::sptr<TAG::ITagSession> tagSession = GetRemoteTagSession();
if (tagInfo_.expired() || !tagSession) {
return NfcErrorCode::NFC_SDK_ERROR_NOT_INITIALIZED;
}
if (tagSession->Reconnect(GetTagRfDiscId()) != NfcErrorCode::NFC_SUCCESS) {
DebugLog("[BasicTagSession::Close] Reconnect fail!");
}
isConnected_ = false;
tagInfo_.lock()->SetConnectedTagTech(KITS::TagTechnology::NFC_INVALID_TECH);
return NfcErrorCode::NFC_SUCCESS;
}
std::string BasicTagSession::GetTagUid()
{
if (tagInfo_.expired()) {
return "";
}
return tagInfo_.lock()->GetTagUid();
}
std::string BasicTagSession::SendCommand(std::string& data, bool raw, int& response)
{
DebugLog("BasicTagSession::SendCommand in");
std::string result = "";
OHOS::sptr<TAG::ITagSession> tagSession = GetRemoteTagSession();
if (!tagSession) {
DebugLog("BasicTagSession::SendCommand tagSession invalid");
return result;
}
std::unique_ptr<TAG::ResResult> res = tagSession->SendRawFrame(GetTagRfDiscId(), data, raw);
if (res) {
response = res->GetResult();
if (res->GetResult() == TAG::ResResult::ResponseResult::RESULT_SUCCESS) {
result = res->GetResData();
}
DebugLog("[BasicTagSession::SendCommand] result.%{public}d", response);
}
return result;
}
int BasicTagSession::GetMaxSendCommandLength() const
{
if (tagInfo_.expired() || (tagTechnology_ == KITS::TagTechnology::NFC_INVALID_TECH)) {
return NfcErrorCode::NFC_SDK_ERROR_INVALID_PARAM;
}
OHOS::sptr<TAG::ITagSession> tagSession = GetRemoteTagSession();
if (!tagSession) {
return NfcErrorCode::NFC_SDK_ERROR_NOT_INITIALIZED;
}
return tagSession->GetMaxTransceiveLength(static_cast<int>(tagTechnology_));
}
OHOS::sptr<TAG::ITagSession> BasicTagSession::GetRemoteTagSession() const
{
DebugLog("BasicTagSession::GetRemoteTagSession in.");
if (!IsConnected() || tagInfo_.expired()) {
DebugLog("[BasicTagSession::GetRemoteTagSession] tag is null.");
return OHOS::sptr<TAG::ITagSession>();
}
return tagInfo_.lock()->GetRemoteTagSession();
}
int BasicTagSession::GetTagRfDiscId() const
{
if (tagInfo_.expired()) {
DebugLog("[BasicTagSession::GetTagRfDiscId] tag is null.");
return NfcErrorCode::NFC_SDK_ERROR_TAG_INVALID;
}
return tagInfo_.lock()->GetTagRfDiscId();
}
void BasicTagSession::SetConnectedTagTech(KITS::TagTechnology tech) const
{
if (tagInfo_.expired()) {
DebugLog("[BasicTagSession::SetConnectedTagTech] tag is null.");
return;
}
tagInfo_.lock()->SetConnectedTagTech(tech);
}
KITS::TagTechnology BasicTagSession::GetConnectedTagTech() const
{
if (tagInfo_.expired()) {
DebugLog("[BasicTagSession::GetConnectedTagTech] tag is null.");
return KITS::TagTechnology::NFC_INVALID_TECH;
}
return tagInfo_.lock()->GetConnectedTagTech();
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,172 +0,0 @@
/*
* 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 "iso15693_tag.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
Iso15693Tag::Iso15693Tag(std::weak_ptr<TagInfo> tag) : BasicTagSession(tag, KITS::TagTechnology::NFC_V_TECH)
{
if (tag.expired()) {
DebugLog("Iso15693Tag::Iso15693Tag tag invalid ");
return;
}
AppExecFwk::PacMap extraData = tag.lock()->GetTechExtrasData(KITS::TagTechnology::NFC_V_TECH);
if (extraData.IsEmpty()) {
DebugLog("Iso15693Tag::Iso15693Tag extra data invalid");
return;
}
dsfId_ = char(tag.lock()->GetIntExtrasData(extraData, TagInfo::DSF_ID));
respFlags_ = char(tag.lock()->GetIntExtrasData(extraData, TagInfo::RESPONSE_FLAGS));
}
Iso15693Tag::~Iso15693Tag()
{
dsfId_ = 0;
respFlags_ = 0;
}
std::shared_ptr<Iso15693Tag> Iso15693Tag::GetTag(std::weak_ptr<TagInfo> tag)
{
if (tag.expired() || !tag.lock()->IsTechSupported(KITS::TagTechnology::NFC_V_TECH)) {
return nullptr;
}
return std::make_shared<Iso15693Tag>(tag);
}
std::string Iso15693Tag::ReadSingleBlock(uint32_t flag, uint32_t blockIndex)
{
InfoLog("Iso15693Tag::ReadSingleBlock in flag= %{public}d blockIndex= %{public}d", flag, blockIndex);
if ((flag < 0 || flag >= ISO15693_MAX_FLAG_COUNT) || (blockIndex < 0 || blockIndex >= ISO15693_MAX_BLOCK_INDEX) ||
!IsConnected()) {
DebugLog("[Iso15693Tag::ReadSingleBlock] flag= %{public}d blockIndex= %{public}d err", flag, blockIndex);
return "";
}
std::string tagUid = GetTagUid();
char command[TagInfo::SEND_COMMAND_HEAD_LEN_2] = {char(flag & 0xFF), CMD_READ_SINGLE_BLOCK};
std::string sendCommand(command, TagInfo::SEND_COMMAND_HEAD_LEN_2);
sendCommand = sendCommand + tagUid + char(blockIndex & 0xFF);
int response = TAG::ResResult::ResponseResult::RESULT_FAILURE;
return SendCommand(sendCommand, false, response);
}
int Iso15693Tag::WriteSingleBlock(uint32_t flag, uint32_t blockIndex, const std::string& data)
{
InfoLog("Iso15693Tag::WriteSingleBlock in");
if (!IsConnected()) {
DebugLog("[Iso15693Tag::WriteSingleBlock] connect tag first!");
return NfcErrorCode::NFC_SDK_ERROR_TAG_NOT_CONNECT;
}
if ((flag < 0 || flag >= ISO15693_MAX_FLAG_COUNT) || (blockIndex < 0 || blockIndex >= ISO15693_MAX_BLOCK_INDEX)) {
DebugLog("[Iso15693Tag::WriteSingleBlock] flag= %{public}d blockIndex= %{public}d err", flag, blockIndex);
return NfcErrorCode::NFC_SDK_ERROR_INVALID_PARAM;
}
std::string tagUid = GetTagUid();
char command[TagInfo::SEND_COMMAND_HEAD_LEN_2] = {char(flag & 0xFF), CMD_WRITE_SINGLE_BLOCK};
std::string sendCommand(command, TagInfo::SEND_COMMAND_HEAD_LEN_2);
sendCommand = sendCommand + tagUid + char(blockIndex & 0xFF) + data;
int response = TAG::ResResult::ResponseResult::RESULT_FAILURE;
std::string res = SendCommand(sendCommand, false, response);
return response;
}
int Iso15693Tag::LockSingleBlock(uint32_t flag, uint32_t blockIndex)
{
InfoLog("Iso15693Tag::LockSingleBlock in");
if (!IsConnected()) {
DebugLog("[Iso15693Tag::LockSingleBlock] connect tag first!");
return NfcErrorCode::NFC_SDK_ERROR_TAG_NOT_CONNECT;
}
if ((flag < 0 || flag >= ISO15693_MAX_FLAG_COUNT) || (blockIndex < 0 || blockIndex >= ISO15693_MAX_BLOCK_INDEX)) {
DebugLog("[Iso15693Tag::LockSingleBlock] flag= %{public}d blockIndex= %{public}d err", flag, blockIndex);
return NfcErrorCode::NFC_SDK_ERROR_INVALID_PARAM;
}
std::string tagUid = GetTagUid();
char command[TagInfo::SEND_COMMAND_HEAD_LEN_2] = {char(flag & 0xFF), CMD_LOCK_SINGLE_BLOCK};
std::string sendCommand(command, TagInfo::SEND_COMMAND_HEAD_LEN_2);
sendCommand = sendCommand + tagUid + char(blockIndex & 0xFF);
int response = TAG::ResResult::ResponseResult::RESULT_FAILURE;
std::string res = SendCommand(sendCommand, false, response);
return response;
}
std::string Iso15693Tag::ReadMultipleBlock(uint32_t flag, uint32_t blockIndex, uint32_t blockNum)
{
InfoLog("Iso15693Tag::ReadMultipleBlock in flag= %{public}d blockIndex= %{public}d blockNum=%{public}d",
flag, blockIndex, blockNum);
if ((flag < 0 || flag >= ISO15693_MAX_FLAG_COUNT) || (blockIndex < 0 || blockIndex >= ISO15693_MAX_BLOCK_INDEX) ||
(blockNum < 0 || blockNum >= ISO15693_MAX_BLOCK_INDEX) || !IsConnected()) {
DebugLog(
"[Iso15693Tag::ReadMultipleBlock] flag= %{public}d blockIndex= %{public}d "
"blockNum=%{public}d err",
flag,
blockIndex,
blockNum);
return "";
}
std::string tagUid = GetTagUid();
char command[TagInfo::SEND_COMMAND_HEAD_LEN_2] = {char(flag & 0xFF), CMD_READ_MULTIPLE_BLOCK};
std::string sendCommand(command, TagInfo::SEND_COMMAND_HEAD_LEN_2);
sendCommand = sendCommand + tagUid + char(blockIndex & 0xFF) + char(blockNum & 0xFF);
int response = TAG::ResResult::ResponseResult::RESULT_FAILURE;
return SendCommand(sendCommand, false, response);
}
int Iso15693Tag::WriteMultipleBlock(uint32_t flag, uint32_t blockIndex, uint32_t blockNum, const std::string& data)
{
InfoLog("Iso15693Tag::WriteMultipleBlock in");
if (!IsConnected()) {
DebugLog("[Iso15693Tag::WriteMultipleBlock] connect tag first!");
return NfcErrorCode::NFC_SDK_ERROR_TAG_NOT_CONNECT;
}
if ((flag < 0 || flag >= ISO15693_MAX_FLAG_COUNT) || (blockIndex < 0 || blockIndex >= ISO15693_MAX_BLOCK_INDEX) ||
(blockNum <= 0 || blockNum > ISO15693_MAX_BLOCK_INDEX)) {
DebugLog("[Iso15693Tag::WriteMultipleBlock] flag=%{public}d blockIndex= %{public}d err", flag, blockIndex);
return NfcErrorCode::NFC_SDK_ERROR_INVALID_PARAM;
}
std::string tagUid = GetTagUid();
char command[TagInfo::SEND_COMMAND_HEAD_LEN_2] = {char(flag & 0xFF), CMD_WRITE_MULTIPLE_BLOCK};
std::string sendCommand(command, TagInfo::SEND_COMMAND_HEAD_LEN_2);
sendCommand = sendCommand + tagUid + char(blockIndex & 0xFF) + char(blockNum & 0xFF) + data;
int response = TAG::ResResult::ResponseResult::RESULT_FAILURE;
std::string res = SendCommand(sendCommand, false, response);
return response;
}
char Iso15693Tag::GetDsfId() const
{
return dsfId_;
}
char Iso15693Tag::GetRespFlags() const
{
return respFlags_;
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,70 +0,0 @@
/*
* 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 "isodep_tag.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
IsoDepTag::IsoDepTag(std::weak_ptr<TagInfo> tag) : BasicTagSession(tag, KITS::TagTechnology::NFC_ISODEP_TECH)
{
if (tag.expired()) {
DebugLog("IsoDepTag::IsoDepTag tag invalid ");
return;
}
AppExecFwk::PacMap extraData = tag.lock()->GetTechExtrasData(KITS::TagTechnology::NFC_ISODEP_TECH);
if (extraData.IsEmpty()) {
DebugLog("IsoDepTag::IsoDepTag extra data invalid");
return;
}
historicalBytes_ = tag.lock()->GetStringExtrasData(extraData, TagInfo::HISTORICAL_BYTES);
hiLayerResponse_ = tag.lock()->GetStringExtrasData(extraData, TagInfo::HILAYER_RESPONSE);
DebugLog("IsoDepTag::IsoDepTag historicalBytes_(%{public}s) hiLayerResponse_(%{public}s)",
historicalBytes_.c_str(), hiLayerResponse_.c_str());
}
std::shared_ptr<IsoDepTag> IsoDepTag::GetTag(std::weak_ptr<TagInfo> tag)
{
DebugLog("IsoDepTag::GetTag in");
if (tag.expired() || !tag.lock()->IsTechSupported(KITS::TagTechnology::NFC_ISODEP_TECH)) {
DebugLog("IsoDepTag::GetTag err");
return nullptr;
}
return std::make_shared<IsoDepTag>(tag);
}
std::string IsoDepTag::GetHistoricalBytes() const
{
return historicalBytes_;
}
std::string IsoDepTag::GetHiLayerResponse() const
{
return hiLayerResponse_;
}
bool IsoDepTag::IsExtendedApduSupported() const
{
OHOS::sptr<TAG::ITagSession> tagSession = GetRemoteTagSession();
if (!tagSession) {
return false;
}
return tagSession->IsSupportedApdusExtended();
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,312 +0,0 @@
/*
* 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 "mifare_classic_tag.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
const char MifareClassicTag::MC_KEY_DEFAULT[MC_KEY_LEN] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
const char MifareClassicTag::MC_KEY_MIFARE_APPLICATION_DIRECTORY[MC_KEY_LEN] = {0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5};
const char MifareClassicTag::MC_KEY_NFC_FORUM[MC_KEY_LEN] = {0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7};
MifareClassicTag::MifareClassicTag(std::weak_ptr<TagInfo> tag)
: BasicTagSession(tag, KITS::TagTechnology::NFC_MIFARE_CLASSIC_TECH)
{
DebugLog("MifareClassicTag::MifareClassicTag in");
if (tag.expired()) {
DebugLog("MifareClassicTag::MifareClassicTag tag invalid");
return;
}
AppExecFwk::PacMap extraData = tag.lock()->GetTechExtrasData(KITS::TagTechnology::NFC_MIFARE_CLASSIC_TECH);
if (extraData.IsEmpty()) {
DebugLog("MifareClassicTag::MifareClassicTag extra data invalid");
return;
}
int sak = tag.lock()->GetIntExtrasData(extraData, TagInfo::SAK);
std::string atqa = tag.lock()->GetStringExtrasData(extraData, TagInfo::ATQA);
DebugLog("MifareClassicTag::MifareClassicTag sak.%{public}d atqa.(%{public}d)%{public}s",
sak, (int)atqa.size(), atqa.c_str());
for (size_t i = 0; i < atqa.size(); i++) {
printf("%02x ", atqa.at(i));
}
printf("\n");
isEmulated_ = false;
mifareTagType_ = EmMifareTagType::TYPE_CLASSIC;
SetSakSize(sak);
}
void MifareClassicTag::SetSakSize(int sak)
{
switch (sak) {
case SAK01:
case SAK08:
case SAK88:
size_ = MC_SIZE_1K;
break;
case SAK09:
size_ = MC_SIZE_MINI;
break;
case SAK10:
size_ = MC_SIZE_2K;
mifareTagType_ = EmMifareTagType::TYPE_PLUS;
break;
case SAK11:
size_ = MC_SIZE_4K;
mifareTagType_ = EmMifareTagType::TYPE_PLUS;
break;
case SAK18:
size_ = MC_SIZE_4K;
break;
case SAK28:
size_ = MC_SIZE_1K;
isEmulated_ = true;
break;
case SAK38:
size_ = MC_SIZE_4K;
isEmulated_ = true;
break;
case SAK98:
case SAKB8:
size_ = MC_SIZE_4K;
mifareTagType_ = EmMifareTagType::TYPE_PRO;
break;
default:
break;
}
}
std::shared_ptr<MifareClassicTag> MifareClassicTag::GetTag(std::weak_ptr<TagInfo> tag)
{
if (tag.expired() || !tag.lock()->IsTechSupported(KITS::TagTechnology::NFC_MIFARE_CLASSIC_TECH)) {
return nullptr;
}
return std::make_shared<MifareClassicTag>(tag);
}
bool MifareClassicTag::AuthenticateSector(int sectorIndex, const std::string& key, bool bIsKeyA)
{
if ((sectorIndex < 0 || sectorIndex >= MC_MAX_SECTOR_COUNT) || !IsConnected() || key.empty()) {
ErrorLog(
"[MifareClassicTag::AuthenticateSector] param err! sectorIndex.%{public}d "
"keyLen.%{public}d",
sectorIndex,
(int)key.size());
return false;
}
char command[TagInfo::SEND_COMMAND_MAX_LEN];
int commandLen = 0;
if (bIsKeyA) {
command[commandLen++] = AUTHENTICATION_WITH_KEY_A;
} else {
command[commandLen++] = AUTHENTICATION_WITH_KEY_B;
}
command[commandLen++] = char(GetBlockIndexFromSector(sectorIndex));
std::string sendCommand(command, commandLen);
std::string tagUid = GetTagUid();
static const int tagSubLen = 4;
// Take the first 4 bytes of the tag as part of command
sendCommand += tagUid.substr(0, tagSubLen) + key;
int response = TAG::ResResult::ResponseResult::RESULT_FAILURE;
SendCommand(sendCommand, false, response);
return (response == TAG::ResResult::ResponseResult::RESULT_SUCCESS);
}
std::string MifareClassicTag::ReadSingleBlock(uint32_t blockIndex)
{
InfoLog("MifareClassicTag::ReadSingleBlock in");
if ((blockIndex < 0 || blockIndex >= MC_MAX_BLOCK_INDEX) || !IsConnected()) {
DebugLog("[MifareClassicTag::ReadSingleBlock] blockIndex= %{public}d err", blockIndex);
return "";
}
char command[TagInfo::SEND_COMMAND_HEAD_LEN_2] = {MIFARE_READ, char(blockIndex & 0xFF)};
std::string sendCommand(command, TagInfo::SEND_COMMAND_HEAD_LEN_2);
int response = TAG::ResResult::ResponseResult::RESULT_FAILURE;
return SendCommand(sendCommand, false, response);
}
int MifareClassicTag::WriteSingleBlock(uint32_t blockIndex, const std::string& data)
{
InfoLog("MifareClassicTag::WriteSingleBlock in");
if (!IsConnected()) {
DebugLog("[MifareClassicTag::WriteSingleBlock] connect tag first!");
return NfcErrorCode::NFC_SDK_ERROR_TAG_NOT_CONNECT;
}
if ((blockIndex < 0 || blockIndex >= MC_MAX_BLOCK_INDEX) || (data.size() != MC_BLOCK_SIZE)) {
DebugLog("[MifareClassicTag::WriteSingleBlock] blockIndex= %{public}d dataLen= %{public}d err",
blockIndex, (int)data.size());
return NfcErrorCode::NFC_SDK_ERROR_INVALID_PARAM;
}
char command[TagInfo::SEND_COMMAND_HEAD_LEN_2] = {MIFARE_WRITE, char(blockIndex & 0xFF)};
std::string sendCommand(command, TagInfo::SEND_COMMAND_HEAD_LEN_2);
sendCommand += data;
int response = TAG::ResResult::ResponseResult::RESULT_FAILURE;
SendCommand(sendCommand, false, response);
return response;
}
int MifareClassicTag::IncrementBlock(uint32_t blockIndex, int value)
{
InfoLog("MifareClassicTag::IncrementBlock in");
if (!IsConnected()) {
DebugLog("[MifareClassicTag::IncrementBlock] connect tag first!");
return NfcErrorCode::NFC_SDK_ERROR_TAG_NOT_CONNECT;
}
if ((blockIndex < 0 || blockIndex >= MC_MAX_BLOCK_INDEX) || value < 0) {
DebugLog("[MifareClassicTag::IncrementBlock] blockIndex= %{public}d value=%{public}d err", blockIndex, value);
return NfcErrorCode::NFC_SDK_ERROR_INVALID_PARAM;
}
char command[TagInfo::SEND_COMMAND_HEAD_LEN_2] = {MIFARE_INCREMENT, char(blockIndex & 0xFF)};
std::string sendCommand(command, TagInfo::SEND_COMMAND_HEAD_LEN_2);
sendCommand += NfcSdkCommon::IntToString(value, NfcSdkCommon::IsLittleEndian());
int response = TAG::ResResult::ResponseResult::RESULT_FAILURE;
SendCommand(sendCommand, false, response);
return response;
}
int MifareClassicTag::DecrementBlock(uint32_t blockIndex, int value)
{
InfoLog("MifareClassicTag::DecrementBlock in");
if (!IsConnected()) {
DebugLog("[MifareClassicTag::DecrementBlock] connect tag first!");
return NfcErrorCode::NFC_SDK_ERROR_TAG_NOT_CONNECT;
}
if (blockIndex < 0 || blockIndex >= MC_MAX_BLOCK_INDEX || value < 0) {
DebugLog("[MifareClassicTag::DecrementBlock] blockIndex= %{public}d value=%{public}d err", blockIndex, value);
return NfcErrorCode::NFC_SDK_ERROR_INVALID_PARAM;
}
char command[TagInfo::SEND_COMMAND_HEAD_LEN_2] = {MIFARE_DECREMENT, char(blockIndex & 0xFF)};
std::string sendCommand(command, TagInfo::SEND_COMMAND_HEAD_LEN_2);
sendCommand += NfcSdkCommon::IntToString(value, NfcSdkCommon::IsLittleEndian());
int response = TAG::ResResult::ResponseResult::RESULT_FAILURE;
SendCommand(sendCommand, false, response);
return response;
}
int MifareClassicTag::TransferToBlock(uint32_t blockIndex)
{
InfoLog("MifareClassicTag::TransferToBlock in");
if (!IsConnected()) {
DebugLog("[MifareClassicTag::TransferToBlock] connect tag first!");
return NfcErrorCode::NFC_SDK_ERROR_TAG_NOT_CONNECT;
}
if (blockIndex < 0 || blockIndex >= MC_MAX_BLOCK_INDEX) {
DebugLog("[MifareClassicTag::TransferToBlock] blockIndex= %{public}d err", blockIndex);
return NfcErrorCode::NFC_SDK_ERROR_INVALID_PARAM;
}
char command[TagInfo::SEND_COMMAND_HEAD_LEN_2] = {MIFARE_TRANSFER, char(blockIndex & 0xFF)};
std::string sendCommand(command, TagInfo::SEND_COMMAND_HEAD_LEN_2);
int response = TAG::ResResult::ResponseResult::RESULT_FAILURE;
SendCommand(sendCommand, false, response);
return response;
}
int MifareClassicTag::RestoreFromBlock(uint32_t blockIndex)
{
InfoLog("MifareClassicTag::RestoreFromBlock in");
if (!IsConnected()) {
DebugLog("[MifareClassicTag::TransferToBlock] connect tag first!");
return NfcErrorCode::NFC_SDK_ERROR_TAG_NOT_CONNECT;
}
if (blockIndex < 0 || blockIndex >= MC_MAX_BLOCK_INDEX) {
DebugLog("[MifareClassicTag::RestoreFromBlock] blockIndex= %{public}d err", blockIndex);
return NfcErrorCode::NFC_SDK_ERROR_INVALID_PARAM;
}
char command[TagInfo::SEND_COMMAND_HEAD_LEN_2] = {MIFARE_RESTORE, char(blockIndex & 0xFF)};
std::string sendCommand(command, TagInfo::SEND_COMMAND_HEAD_LEN_2);
int response = TAG::ResResult::ResponseResult::RESULT_FAILURE;
SendCommand(sendCommand, false, response);
return response;
}
int MifareClassicTag::GetSectorCount() const
{
size_t count = 0;
switch (size_) {
case MC_SIZE_1K:
count = MC_SECTOR_COUNT_OF_SIZE_1K;
break;
case MC_SIZE_2K:
count = MC_SECTOR_COUNT_OF_SIZE_2K;
break;
case MC_SIZE_4K:
count = MC_MAX_SECTOR_COUNT;
break;
case MC_SIZE_MINI:
count = MC_SECTOR_COUNT_OF_SIZE_MINI;
break;
default:
break;
}
return count;
}
int MifareClassicTag::GetBlockCountInSector(int sectorIndex) const
{
if (sectorIndex >= 0 && sectorIndex < MC_SECTOR_COUNT_OF_SIZE_2K) {
return MC_BLOCK_COUNT;
} else if (sectorIndex >= MC_SECTOR_COUNT_OF_SIZE_2K && sectorIndex < MC_MAX_SECTOR_COUNT) {
return MC_BLOCK_COUNT_OF_4K;
}
return NfcErrorCode::NFC_SDK_ERROR_UNKOWN;
}
size_t MifareClassicTag::GetMifareTagType() const
{
return mifareTagType_;
}
int MifareClassicTag::GetSize() const
{
return size_;
}
bool MifareClassicTag::IsEmulated() const
{
return isEmulated_;
}
int MifareClassicTag::GetBlockIndexFromSector(int sectorIndex) const
{
if (sectorIndex >= 0 && sectorIndex < MC_SECTOR_COUNT_OF_SIZE_2K) {
return sectorIndex * MC_BLOCK_COUNT;
}
if (sectorIndex >= MC_SECTOR_COUNT_OF_SIZE_2K && sectorIndex < MC_MAX_SECTOR_COUNT) {
return MC_SECTOR_COUNT_OF_SIZE_2K * MC_BLOCK_COUNT +
(sectorIndex - MC_SECTOR_COUNT_OF_SIZE_2K) * MC_BLOCK_COUNT_OF_4K;
}
return NfcErrorCode::NFC_SDK_ERROR_UNKOWN;
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,106 +0,0 @@
/*
* 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 "mifare_ultralight_tag.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
MifareUltralightTag::MifareUltralightTag(std::weak_ptr<TagInfo> tag)
: BasicTagSession(tag, KITS::TagTechnology::NFC_MIFARE_ULTRALIGHT_TECH)
{
InfoLog("MifareUltralightTag::MifareUltralightTag in");
if (tag.expired()) {
InfoLog("MifareUltralightTag::MifareUltralightTag tag invalid ");
return;
}
AppExecFwk::PacMap extraData = tag.lock()->GetTechExtrasData(KITS::TagTechnology::NFC_MIFARE_ULTRALIGHT_TECH);
if (extraData.IsEmpty()) {
DebugLog("MifareUltralightTag::MifareUltralightTag extra data invalid");
return;
}
InfoLog("MifareUltralightTag::MifareUltralightTag sak.%{public}d tagid.%{public}d",
tag.lock()->GetIntExtrasData(extraData, TagInfo::SAK),
tag.lock()->GetTagUid().at(0));
if ((tag.lock()->GetIntExtrasData(extraData, TagInfo::SAK) == 0x00) &&
tag.lock()->GetTagUid().at(0) == NXP_MANUFACTURER_ID) {
InfoLog("MifareUltralightTag::MifareUltralightTag Ctype.%{public}d",
tag.lock()->GetIntExtrasData(extraData, TagInfo::MIFARE_ULTRALIGHT_C_TYPE));
if (tag.lock()->GetIntExtrasData(extraData, TagInfo::MIFARE_ULTRALIGHT_C_TYPE)) {
type_ = EmMifareUltralightType::TYPE_ULTRALIGHT_C;
} else {
type_ = EmMifareUltralightType::TYPE_ULTRALIGHT;
}
}
}
MifareUltralightTag::~MifareUltralightTag() {}
std::shared_ptr<MifareUltralightTag> MifareUltralightTag::GetTag(std::weak_ptr<TagInfo> tag)
{
InfoLog("MifareUltralightTag::GetTag in tech len.%{public}d ", (int)tag.lock()->GetTagTechList().size());
if (tag.expired() || !tag.lock()->IsTechSupported(KITS::TagTechnology::NFC_MIFARE_ULTRALIGHT_TECH)) {
InfoLog("MifareUltralightTag::GetTag tag invalid");
return nullptr;
}
return std::make_shared<MifareUltralightTag>(tag);
}
std::string MifareUltralightTag::ReadMultiplePages(uint32_t pageIndex)
{
InfoLog("MifareUltralightTag::ReadMultiplePages in.");
if ((pageIndex > 0 && pageIndex < MU_MAX_PAGE_COUNT) && IsConnected()) {
char command[TagInfo::SEND_COMMAND_HEAD_LEN_2] = {MIFARE_ULTRALIGHT_READ, char(pageIndex & 0xFF)};
std::string sendCommand(command, TagInfo::SEND_COMMAND_HEAD_LEN_2);
DebugLog("%02X %02X ", command[0], command[1]);
int response = TAG::ResResult::ResponseResult::RESULT_FAILURE;
return SendCommand(sendCommand, false, response);
} else {
DebugLog("[MifareUltralightTag::ReadMultiplePages] pageindex.%{public}d err!", pageIndex);
}
return "";
}
int MifareUltralightTag::WriteSinglePages(uint32_t pageIndex, const std::string& data)
{
InfoLog("MifareUltralightTag::WriteSinglePages in.");
if (!IsConnected()) {
DebugLog("[MifareUltralightTag::WriteSinglePages] connect tag first!");
return NfcErrorCode::NFC_SDK_ERROR_TAG_NOT_CONNECT;
}
if ((pageIndex > 0 && pageIndex < MU_MAX_PAGE_COUNT) && (data.size() == MU_PAGE_SIZE)) {
char command[TagInfo::SEND_COMMAND_HEAD_LEN_2] = {MIFARE_ULTRALIGHT_WRITE, char(pageIndex & 0xFF)};
std::string sendCommand(command, TagInfo::SEND_COMMAND_HEAD_LEN_2);
sendCommand += data;
int response = TAG::ResResult::ResponseResult::RESULT_FAILURE;
SendCommand(sendCommand, false, response);
return response;
}
InfoLog("MifareUltralightTag::WriteSinglePages param error!");
return NfcErrorCode::NFC_SDK_ERROR_INVALID_PARAM;
}
MifareUltralightTag::EmMifareUltralightType MifareUltralightTag::GetType() const
{
return type_;
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,88 +0,0 @@
/*
* 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 "ndef_formatable_tag.h"
#include "loghelper.h"
#include "mifare_classic_tag.h"
namespace OHOS {
namespace NFC {
namespace KITS {
NdefFormatableTag::NdefFormatableTag(std::weak_ptr<TagInfo> tag)
: BasicTagSession(tag, KITS::TagTechnology::NFC_NDEF_FORMATABLE_TECH) {}
std::shared_ptr<NdefFormatableTag> NdefFormatableTag::GetTag(std::weak_ptr<TagInfo> tag)
{
if (tag.expired() || !tag.lock()->IsTechSupported(KITS::TagTechnology::NFC_NDEF_FORMATABLE_TECH)) {
return nullptr;
}
return std::make_shared<NdefFormatableTag>(tag);
}
int NFC::KITS::NdefFormatableTag::Format(std::weak_ptr<NdefMessage> firstMessage)
{
return Format(firstMessage, false);
}
int NFC::KITS::NdefFormatableTag::FormatReadOnly(std::weak_ptr<NdefMessage> firstMessage)
{
return Format(firstMessage, true);
}
int NFC::KITS::NdefFormatableTag::Format(std::weak_ptr<NdefMessage> firstMessage, bool bMakeReadOnly)
{
OHOS::sptr<TAG::ITagSession> tagSession = GetRemoteTagSession();
if (!tagSession) {
ErrorLog("[NdefTag::ReadNdef] tagSession is null.");
return NfcErrorCode::NFC_SDK_ERROR_TAG_INVALID;
}
int tagRfDiscId = GetTagRfDiscId();
std::string keyDefault(MifareClassicTag::MC_KEY_DEFAULT, MifareClassicTag::MC_KEY_LEN);
int res = tagSession->FormatNdef(tagRfDiscId, keyDefault);
if (res != NfcErrorCode::NFC_SUCCESS) {
return res;
}
if (!tagSession->IsNdef(tagRfDiscId)) {
return NfcErrorCode::NFC_SDK_ERROR_TAG_INVALID;
}
if (!firstMessage.expired()) {
std::string ndefMessage = NdefMessage::MessageToString(firstMessage);
if (ndefMessage.empty()) {
return NfcErrorCode::NFC_SDK_ERROR_INVALID_PARAM;
}
res = tagSession->NdefWrite(tagRfDiscId, ndefMessage);
if (res != NfcErrorCode::NFC_SUCCESS) {
return res;
}
}
if (bMakeReadOnly) {
if (!tagSession->CanMakeReadOnly(tagRfDiscId)) {
return NfcErrorCode::NFC_SDK_ERROR_DISABLE_MAKE_READONLY;
}
res = tagSession->NdefMakeReadOnly(tagRfDiscId);
if (res != NfcErrorCode::NFC_SUCCESS) {
return res;
}
}
return NfcErrorCode::NFC_SUCCESS;
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,449 +0,0 @@
/*
* 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 "ndef_message.h"
#include "loghelper.h"
#include "nfc_sdk_common.h"
namespace OHOS {
namespace NFC {
namespace KITS {
NdefMessage::NdefMessage(std::vector<std::shared_ptr<NdefRecord>> ndefRecords)
: ndefRecordList_(std::move(ndefRecords))
{
}
NdefMessage::~NdefMessage()
{
ndefRecordList_.clear();
}
std::shared_ptr<NdefMessage> NdefMessage::GetNdefMessage(const std::string& data)
{
std::vector<std::shared_ptr<NdefRecord>> ndefRecords = ParseRecord(data, false);
if (ndefRecords.empty()) {
return std::shared_ptr<NdefMessage>();
}
return GetNdefMessage(ndefRecords);
}
std::shared_ptr<NdefMessage> NdefMessage::GetNdefMessage(std::vector<std::shared_ptr<NdefRecord>> ndefRecords)
{
return std::make_shared<NdefMessage>(std::move(ndefRecords));
}
std::string NdefMessage::GetTagRtdType(EmRtdType rtdtype)
{
std::string rtd;
switch (rtdtype) {
case EmRtdType::RTD_TEXT:
rtd = "T"; // 0x54
break;
case EmRtdType::RTD_URI:
rtd = "U"; // 0x55
break;
case EmRtdType::RTD_SMART_POSTER:
rtd = "Sp"; // 0x53, 0x70
break;
case EmRtdType::RTD_ALTERNATIVE_CARRIER:
rtd = "ac"; // 0x61, 0x63
break;
case EmRtdType::RTD_HANDOVER_CARRIER:
rtd = "Hc"; // 0x48, 0x63
break;
case EmRtdType::RTD_HANDOVER_REQUEST:
rtd = "Hr"; // 0x48, 0x72
break;
case EmRtdType::RTD_HANDOVER_SELECT:
rtd = "Hs"; // 0x48, 0x73
break;
case EmRtdType::RTD_OHOS_APP:
rtd = "ohos.com:pkg"; // "ohos.com:pkg"
break;
default:
rtd.clear();
break;
}
return rtd;
}
std::vector<std::shared_ptr<NdefRecord>> NdefMessage::GetNdefRecords() const
{
return ndefRecordList_;
}
std::shared_ptr<NdefRecord> NdefMessage::MakeUriRecord(const std::string& uriString)
{
if (uriString.empty()) {
return std::shared_ptr<NdefRecord>();
}
std::string payLoad;
std::string uri = uriString;
for (size_t i = 1; i < gUriPrefix.size() - 1; i++) {
if (!uriString.compare(0, gUriPrefix[i].size(), gUriPrefix[i])) {
payLoad += (i & 0xFF);
uri = uriString.substr(gUriPrefix[i].size());
DebugLog("prefer index .%{public}d", (int)i);
break;
}
}
payLoad += uri;
std::string id = "";
std::string tagRtdType = GetTagRtdType(EmRtdType::RTD_URI);
return CreateNdefRecord(TNF_WELL_KNOWN, id, payLoad, tagRtdType);
}
std::shared_ptr<NdefRecord> NdefMessage::MakeTextRecord(const std::string& text, const std::string& locale)
{
std::string tagRtdType = GetTagRtdType(EmRtdType::RTD_TEXT);
std::string id = "";
std::string payLoad = std::to_string(locale.size());
payLoad += locale + text;
return CreateNdefRecord(TNF_WELL_KNOWN, id, payLoad, tagRtdType);
}
std::shared_ptr<NdefRecord> NdefMessage::MakeMimeRecord(const std::string& mimeType, const std::string& mimeData)
{
if (mimeData.empty()) {
return std::shared_ptr<NdefRecord>();
}
std::string id = "";
size_t t = mimeType.find_first_of('/');
if (t > 0 && t < mimeType.size() - 1) {
return CreateNdefRecord(TNF_MIME_MEDIA, id, mimeData, mimeType);
}
return std::shared_ptr<NdefRecord>();
}
std::shared_ptr<NdefRecord> NdefMessage::MakeExternalRecord(const std::string& domainName,
const std::string& serviceName,
const std::string& externalData)
{
if (domainName.empty() || serviceName.empty() || externalData.empty()) {
return std::shared_ptr<NdefRecord>();
}
std::string domain = domainName;
std::string service = serviceName;
domain.erase(0, domain.find_first_not_of("\r\t\n "));
domain.erase(domain.find_last_not_of("\r\t\n ") + 1);
transform(domain.begin(), domain.end(), domain.begin(), ::tolower);
service.erase(0, service.find_first_not_of("\r\t\n "));
service.erase(service.find_last_not_of("\r\t\n ") + 1);
transform(service.begin(), service.end(), service.begin(), ::tolower);
if (domain.empty() || service.empty()) {
return std::shared_ptr<NdefRecord>();
}
std::string tagRtdType = domain + ":" + service;
std::string id = "";
return CreateNdefRecord(TNF_EXTERNAL_TYPE, id, externalData, tagRtdType);
}
std::string NdefMessage::MessageToString(std::weak_ptr<NdefMessage> ndefMessage)
{
std::string buffer;
if (ndefMessage.expired()) {
return buffer;
}
for (size_t i = 0; i < ndefMessage.lock()->ndefRecordList_.size(); i++) {
bool bIsMB = (i == 0); // first record
bool bIsME = (i == ndefMessage.lock()->ndefRecordList_.size() - 1); // last record
NdefRecordToString(ndefMessage.lock()->ndefRecordList_.at(i), buffer, bIsMB, bIsME);
}
return buffer;
}
void NdefMessage::NdefRecordToString(std::weak_ptr<NdefRecord> record, std::string& buffer, bool bIsMB, bool bIsME)
{
if (record.expired()) {
return;
}
std::string payload = record.lock()->payload_;
uint32_t tnf = record.lock()->tnf_;
std::string id = record.lock()->id_;
std::string rtdType = record.lock()->tagRtdType_;
bool sr = payload.size() < SHORT_RECORD_SIZE;
bool il = (tnf == TNF_EMPTY) ? true : (id.size() > 0);
char flag =
char((bIsMB ? FLAG_MB : 0) | (bIsME ? FLAG_ME : 0) | (sr ? FLAG_SR : 0) | (il ? FLAG_IL : 0)) | (char)tnf;
buffer.push_back(flag);
buffer.push_back((char)rtdType.size());
if (sr) {
buffer.push_back(char(payload.size()));
} else {
buffer.append(NfcSdkCommon::IntToString(payload.size(), NfcSdkCommon::IsLittleEndian()));
}
if (il) {
buffer.push_back(char(id.size()));
}
buffer.append(rtdType);
buffer.append(id);
buffer.append(payload);
}
void NdefMessage::ParseRecordLayoutHead(RecordLayout& layout, char head)
{
layout.mb = (head & FLAG_MB) != 0;
layout.me = (head & FLAG_ME) != 0;
layout.cf = (head & FLAG_CF) != 0;
layout.sr = (head & FLAG_SR) != 0;
layout.il = (head & FLAG_IL) != 0;
layout.tnf = char(head & FLAG_TNF);
}
bool NdefMessage::IsInvalidRecordLayoutHead(RecordLayout& layout, bool isChunkFound,
uint32_t parsedRecordSize, bool isMbMeIgnored)
{
if (!layout.mb && parsedRecordSize == 0 && !isChunkFound && !isMbMeIgnored) {
return true;
} else if (layout.mb && (parsedRecordSize != 0 || isChunkFound) && !isMbMeIgnored) {
return true;
} else if (isChunkFound && layout.il) {
return true;
} else if (layout.cf && layout.me) {
return true;
} else if (isChunkFound && layout.tnf != TNF_UNCHANGED) {
return true;
} else if (!isChunkFound && layout.tnf == TNF_UNCHANGED) {
return true;
}
return false;
}
void NdefMessage::ParseRecordLayoutLength(RecordLayout& layout, bool isChunkFound,
const std::string& data, uint32_t& parsedDataIndex)
{
layout.typeLength = data.at(parsedDataIndex++) & 0xFF;
if (layout.sr) {
layout.payloadLength = data.at(parsedDataIndex++) & 0xFF;
} else {
if (static_cast<uint32_t>(data.size()) < parsedDataIndex + int(sizeof(int))) {
layout.payloadLength = 0;
} else {
std::string lenString = data.substr(parsedDataIndex, sizeof(int));
layout.payloadLength = NfcSdkCommon::StringToInt(lenString, NfcSdkCommon::IsLittleEndian());
parsedDataIndex += sizeof(int);
}
}
layout.idLength = layout.il ? (data.at(parsedDataIndex++) & 0xFF) : 0;
}
bool NdefMessage::IsRecordLayoutLengthInvalid(RecordLayout& layout, bool isChunkFound)
{
// for the middle chunks record, need the type length is zero.
if (isChunkFound && layout.typeLength != 0) {
return true;
}
// for the first chunk, expected has type.
if (layout.cf && !isChunkFound) {
if (layout.typeLength == 0 && layout.tnf != TNF_UNKNOWN) {
return true;
}
}
if (layout.payloadLength > MAX_PAYLOAD_SIZE) {
return true;
}
return false;
}
std::string NdefMessage::ParseRecordType(RecordLayout& layout, const std::string& data, uint32_t& parsedDataIndex)
{
if (layout.typeLength <= 0) {
return "";
} else if (static_cast<uint32_t>(data.size()) < parsedDataIndex + layout.typeLength) {
ErrorLog("data len.%{public}d index.%{public}d rtdtype len.%{public}d error",
static_cast<int>(data.size()),
parsedDataIndex,
layout.typeLength);
return "";
} else {
std::string type = data.substr(parsedDataIndex, layout.typeLength);
parsedDataIndex += layout.typeLength;
return type;
}
}
std::string NdefMessage::ParseRecordId(RecordLayout& layout, const std::string& data, uint32_t& parsedDataIndex)
{
if (layout.idLength <= 0) {
return "";
} else if (static_cast<uint32_t>(data.size()) < parsedDataIndex + layout.idLength) {
ErrorLog("data len.%{public}d index.%{public}d id len.%{public}d error",
static_cast<int>(data.size()),
parsedDataIndex,
layout.idLength);
return "";
} else {
std::string id = data.substr(parsedDataIndex, layout.idLength);
parsedDataIndex += layout.idLength;
return id;
}
}
std::string NdefMessage::ParseRecordPayload(RecordLayout& layout, const std::string& data, uint32_t& parsedDataIndex)
{
if (layout.payloadLength > 0) {
if (static_cast<uint32_t>(data.size()) < (parsedDataIndex + layout.payloadLength)) {
ErrorLog("data len.%{public}d index.%{public}d payload len.%{public}d error",
static_cast<int>(data.size()), parsedDataIndex, layout.payloadLength);
return "";
}
std::string payload = data.substr(parsedDataIndex, layout.payloadLength);
parsedDataIndex += layout.payloadLength;
return payload;
} else {
return "";
}
}
void NdefMessage::SaveRecordChunks(RecordLayout& layout, bool isChunkFound,
std::vector<std::string>& chunks, char& chunkTnf, const std::string& payload)
{
// handle for the first chunk.
if (layout.cf && !isChunkFound) {
chunks.clear();
chunkTnf = layout.tnf;
}
// save the payload for all(first/middle/last) chunk.
if (layout.cf || isChunkFound) {
chunks.push_back(payload);
}
}
std::string NdefMessage::MergePayloadByChunks(RecordLayout& layout, bool isChunkFound,
std::vector<std::string>& chunks, char chunkTnf, const std::string& payload)
{
// it's the last chunk, merge the payload for NdefRecord.
if (!layout.cf && isChunkFound) {
std::string mergedPayload;
for (std::string n : chunks) {
mergedPayload += n;
}
layout.tnf = chunkTnf;
return mergedPayload;
}
return payload;
}
std::shared_ptr<NdefRecord> NdefMessage::CreateNdefRecord(size_t tnf, const std::string& id,
const std::string& payload, const std::string& tagRtdType)
{
bool res = CheckTnf(tnf, tagRtdType, id, payload);
if (!res) {
return std::shared_ptr<NdefRecord>();
}
std::shared_ptr<NdefRecord> ndefRecord = std::make_shared<NdefRecord>();
ndefRecord->tnf_ = tnf;
ndefRecord->id_ = id;
ndefRecord->payload_ = payload;
ndefRecord->tagRtdType_ = tagRtdType;
return ndefRecord;
}
bool NdefMessage::CheckTnf(size_t tnf, const std::string& tagRtdType, const std::string& id, const std::string& payload)
{
switch (tnf) {
case TNF_EMPTY:
if (!tagRtdType.empty() || !id.empty() || !payload.empty()) {
return false;
}
break;
case TNF_WELL_KNOWN:
case TNF_MIME_MEDIA:
case TNF_ABSOLUTE_URI:
case TNF_EXTERNAL_TYPE:
return true;
case TNF_UNKNOWN:
case TNF_RESERVED:
if (tagRtdType.empty()) {
return false;
}
return true;
case TNF_UNCHANGED:
return false;
default:
break;
}
return false;
}
std::vector<std::shared_ptr<NdefRecord>> NdefMessage::ParseRecord(const std::string& data, bool isMbMeIgnored)
{
std::vector<std::shared_ptr<NdefRecord>> recordList;
if (data.empty()) {
return recordList;
}
std::string tagRtdType, id, payload;
std::vector<std::string> chunks;
bool isChunkFound = false;
char chunkTnf = 0;
bool isMessageEnd = false;
uint32_t parsedDataIndex = 0;
while (!isMessageEnd) {
RecordLayout layout;
ParseRecordLayoutHead(layout, data.at(parsedDataIndex++));
isMessageEnd = layout.me;
if (IsInvalidRecordLayoutHead(layout, isChunkFound, recordList.size(), isMbMeIgnored)) {
return recordList;
}
ParseRecordLayoutLength(layout, isChunkFound, data, parsedDataIndex);
if (IsRecordLayoutLengthInvalid(layout, isChunkFound)) {
return recordList;
}
if (!isChunkFound) {
// don't parse the type and id for the middle chunks record.
tagRtdType = ParseRecordType(layout, data, parsedDataIndex);
id = ParseRecordId(layout, data, parsedDataIndex);
if (tagRtdType.empty() || id.empty()) {
return recordList;
}
}
// parse the payload.
payload = ParseRecordPayload(layout, data, parsedDataIndex);
SaveRecordChunks(layout, isChunkFound, chunks, chunkTnf, payload);
payload = MergePayloadByChunks(layout, isChunkFound, chunks, chunkTnf, payload);
if (payload.length() > MAX_PAYLOAD_SIZE) {
return recordList;
}
// if not the last chunk, continue to parse again.
isChunkFound = layout.cf;
if (isChunkFound) {
continue;
}
// all chunks parsed end, add a new NdefRecord.
std::shared_ptr<NdefRecord> record = CreateNdefRecord(layout.tnf, id, payload, tagRtdType);
recordList.push_back(record);
// isMbMeIgnored is true, means that single record need tobe parsed.
if (isMbMeIgnored) {
break;
}
}
return recordList;
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,181 +0,0 @@
/*
* 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 "ndef_tag.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
NdefTag::NdefTag(std::weak_ptr<TagInfo> tag) : BasicTagSession(tag, KITS::TagTechnology::NFC_NDEF_TECH)
{
DebugLog("NdefTag::NdefTag in");
if (tag.expired()) {
DebugLog("NdefTag::NdefTag tag invalid");
return;
}
AppExecFwk::PacMap extraData = tag.lock()->GetTechExtrasData(KITS::TagTechnology::NFC_NDEF_TECH);
if (extraData.IsEmpty()) {
DebugLog("NdefTag::NdefTag extra data invalid");
return;
}
nfcForumType_ = (EmNfcForumType)tag.lock()->GetIntExtrasData(extraData, TagInfo::NDEF_FORUM_TYPE);
ndefTagMode_ = (EmNdefTagMode)tag.lock()->GetIntExtrasData(extraData, TagInfo::NDEF_TAG_MODE);
ndefMsg_ = tag.lock()->GetStringExtrasData(extraData, TagInfo::NDEF_MSG);
DebugLog("NdefTag::NdefTag nfcForumType_(%{public}d) ndefTagMode_(%{public}d) ndefMsg_(%{public}s)",
nfcForumType_, ndefTagMode_, ndefMsg_.c_str());
}
std::shared_ptr<NdefTag> NdefTag::GetTag(std::weak_ptr<TagInfo> tag)
{
if (tag.expired() || !tag.lock()->IsTechSupported(KITS::TagTechnology::NFC_NDEF_TECH)) {
DebugLog("NdefTag::GetTag error");
return nullptr;
}
return std::make_shared<NdefTag>(tag);
}
NdefTag::EmNfcForumType NdefTag::GetNdefTagType() const
{
return nfcForumType_;
}
NdefTag::EmNdefTagMode NdefTag::GetNdefTagMode() const
{
return ndefTagMode_;
}
std::shared_ptr<NdefMessage> NdefTag::GetCachedNdefMsg() const
{
return NdefMessage::GetNdefMessage(ndefMsg_);
}
std::string NdefTag::GetNdefTagTypeString(EmNfcForumType emNfcForumType)
{
InfoLog("NdefTag::GetNdefTagTypeString in");
std::string typeString;
switch (emNfcForumType) {
case NFC_FORUM_TYPE_1:
typeString = STRING_NFC_FORUM_TYPE_1;
break;
case NFC_FORUM_TYPE_2:
typeString = STRING_NFC_FORUM_TYPE_2;
break;
case NFC_FORUM_TYPE_3:
typeString = STRING_NFC_FORUM_TYPE_3;
break;
case NFC_FORUM_TYPE_4:
typeString = STRING_NFC_FORUM_TYPE_4;
break;
case MIFARE_CLASSIC:
typeString = STRING_MIFARE_CLASSIC;
break;
case ICODE_SLI:
typeString = STRING_ICODE_SLI;
break;
default:
break;
}
DebugLog("[NdefTag::GetNdefTagTypeString] typeString=%{public}d.", emNfcForumType);
return typeString;
}
bool NdefTag::IsNdefWritable() const
{
return (ndefTagMode_ == EmNdefTagMode::MODE_READ_WRITE);
}
std::shared_ptr<NdefMessage> NdefTag::ReadNdef()
{
DebugLog("NdefTag::ReadNdef in.");
OHOS::sptr<TAG::ITagSession> tagSession = GetRemoteTagSession();
if (!tagSession) {
DebugLog("[NdefTag::ReadNdef] tagSession is null.");
return std::shared_ptr<NdefMessage>();
}
if (tagSession->IsNdef(GetTagRfDiscId())) {
std::string MessageData = tagSession->NdefRead(GetTagRfDiscId());
if (MessageData.empty() && !tagSession->IsTagFieldOn(GetTagRfDiscId())) {
DebugLog("[NdefTag::ReadNdef] read ndef message is null and tag is not field on");
return std::shared_ptr<NdefMessage>();
}
return NdefMessage::GetNdefMessage(MessageData);
} else {
if (!tagSession->IsTagFieldOn(GetTagRfDiscId())) {
DebugLog("[NdefTag::ReadNdef] tag is not field on.");
return std::shared_ptr<NdefMessage>();
}
}
return std::shared_ptr<NdefMessage>();
}
int NdefTag::WriteNdef(std::shared_ptr<NdefMessage> msg)
{
InfoLog("NdefTag::WriteNdef in.");
if (!IsConnected()) {
DebugLog("[NdefTag::WriteNdef] connect tag first!");
return NfcErrorCode::NFC_SDK_ERROR_TAG_NOT_CONNECT;
}
OHOS::sptr<TAG::ITagSession> tagSession = GetRemoteTagSession();
if (!tagSession) {
DebugLog("[NdefTag::WriteNdef] tagSession is null.");
return NfcErrorCode::NFC_SDK_ERROR_TAG_NOT_CONNECT;
}
if (tagSession->IsNdef(GetTagRfDiscId())) {
std::string ndefMessage = NdefMessage::MessageToString(msg);
for (size_t i = 0; i < ndefMessage.size(); i++) {
printf("%02x ", ndefMessage.at(i));
}
printf("\n");
return tagSession->NdefWrite(GetTagRfDiscId(), ndefMessage);
} else {
DebugLog("[NdefTag::WriteNdef] is not ndef tag!");
return NfcErrorCode::NFC_SDK_ERROR_NOT_NDEF_TAG;
}
}
bool NdefTag::IsEnableReadOnly()
{
OHOS::sptr<TAG::ITagSession> tagSession = GetRemoteTagSession();
if (!tagSession) {
DebugLog("[NdefTag::IsEnableReadOnly] tagSession is null.");
return 0;
}
return tagSession->CanMakeReadOnly(nfcForumType_);
}
int NdefTag::EnableReadOnly()
{
if (!IsConnected()) {
DebugLog("[NdefTag::EnableReadOnly] connect tag first!");
return NfcErrorCode::NFC_SDK_ERROR_TAG_NOT_CONNECT;
}
OHOS::sptr<TAG::ITagSession> tagSession = GetRemoteTagSession();
if (!tagSession) {
DebugLog("[NdefTag::EnableReadOnly] tagSession is null.");
return NfcErrorCode::NFC_SDK_ERROR_TAG_NOT_CONNECT;
}
return tagSession->NdefMakeReadOnly(GetTagRfDiscId());
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,61 +0,0 @@
/*
* 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 "nfca_tag.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
NfcATag::NfcATag(std::weak_ptr<TagInfo> tag) : BasicTagSession(tag, KITS::TagTechnology::NFC_A_TECH)
{
if (tag.expired()) {
DebugLog("NfcATag::NfcATag tag invalid ");
return;
}
AppExecFwk::PacMap extraData = tag.lock()->GetTechExtrasData(KITS::TagTechnology::NFC_A_TECH);
if (extraData.IsEmpty()) {
DebugLog("NfcATag::NfcATag extra data invalid");
return;
}
sak_ = tag.lock()->GetIntExtrasData(extraData, TagInfo::SAK);
atqa_ = tag.lock()->GetStringExtrasData(extraData, TagInfo::ATQA);
DebugLog("NfcATag::NfcATag sak_(%{public}d) atqa_(%{public}s)", sak_, atqa_.c_str());
}
std::shared_ptr<NfcATag> NfcATag::GetTag(std::weak_ptr<TagInfo> tag)
{
DebugLog("NfcATag::GetTag in");
if (tag.expired() || !tag.lock()->IsTechSupported(KITS::TagTechnology::NFC_A_TECH)) {
DebugLog("NfcATag::GetTag err");
return nullptr;
}
return std::make_shared<NfcATag>(tag);
}
int NfcATag::GetSak() const
{
return sak_;
}
std::string NfcATag::GetAtqa() const
{
return atqa_;
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,62 +0,0 @@
/*
* 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 "nfcb_tag.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
NfcBTag::NfcBTag(std::weak_ptr<TagInfo> tag) : BasicTagSession(tag, KITS::TagTechnology::NFC_B_TECH)
{
if (tag.expired()) {
DebugLog("NfcBTag::NfcBTag tag invalid ");
return;
}
AppExecFwk::PacMap extraData = tag.lock()->GetTechExtrasData(KITS::TagTechnology::NFC_B_TECH);
if (extraData.IsEmpty()) {
DebugLog("NfcBTag::NfcBTag extra data invalid");
return;
}
appData_ = tag.lock()->GetStringExtrasData(extraData, TagInfo::APP_DATA);
protocolInfo_ = tag.lock()->GetStringExtrasData(extraData, TagInfo::PROTOCOL_INFO);
DebugLog("NfcBTag::NfcBTag appData_(%{public}s) protocolInfo_(%{public}s)",
appData_.c_str(), protocolInfo_.c_str());
}
std::shared_ptr<NfcBTag> NfcBTag::GetTag(std::weak_ptr<TagInfo> tag)
{
DebugLog("NfcBTag::GetTag in");
if (tag.expired() || !tag.lock()->IsTechSupported(KITS::TagTechnology::NFC_B_TECH)) {
DebugLog("NfcBTag::GetTag err");
return nullptr;
}
return std::make_shared<NfcBTag>(tag);
}
std::string NfcBTag::GetAppData() const
{
return appData_;
}
std::string NfcBTag::GetProtocolInfo() const
{
return protocolInfo_;
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,60 +0,0 @@
/*
* 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 "nfcf_tag.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
NfcFTag::NfcFTag(std::weak_ptr<TagInfo> tag) : BasicTagSession(tag, KITS::TagTechnology::NFC_F_TECH)
{
if (tag.expired()) {
DebugLog("NfcFTag::NfcFTag tag invalid ");
return;
}
AppExecFwk::PacMap extraData = tag.lock()->GetTechExtrasData(KITS::TagTechnology::NFC_F_TECH);
if (extraData.IsEmpty()) {
DebugLog("NfcFTag::NfcFTag extra data invalid");
return;
}
std::string pmmStr = tag.lock()->GetStringExtrasData(extraData, TagInfo::NFCF_PMM);
std::string scStr = tag.lock()->GetStringExtrasData(extraData, TagInfo::NFCF_SC);
KITS::NfcSdkCommon::StringToUnsignedCharArray(pmmStr, pmm_);
KITS::NfcSdkCommon::StringToUnsignedCharArray(scStr, systemCode_);
}
std::shared_ptr<NfcFTag> NfcFTag::GetTag(std::weak_ptr<TagInfo> tag)
{
DebugLog("NfcFTag::GetTag in");
if (tag.expired() || !tag.lock()->IsTechSupported(KITS::TagTechnology::NFC_F_TECH)) {
DebugLog("NfcFTag::GetTag no NFC_F_TECH");
return nullptr;
}
return std::make_shared<NfcFTag>(tag);
}
std::vector<unsigned char> NfcFTag::getSystemCode() const
{
return systemCode_;
}
std::vector<unsigned char> NfcFTag::getPmm() const
{
return pmm_;
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,234 +0,0 @@
/*
* 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 "tag_session_proxy.h"
#include "loghelper.h"
#include "message_option.h"
#include "message_parcel.h"
#include "nfc_sdk_common.h"
namespace OHOS {
namespace NFC {
namespace TAG {
int TagSessionProxy::Connect(int tagRfDiscId, int technology)
{
int result = 0;
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return KITS::NfcErrorCode::NFC_SDK_ERROR_UNKOWN;
}
data.WriteInt32(tagRfDiscId);
data.WriteInt32(static_cast<int32_t>(technology));
MessageOption option(MessageOption::TF_SYNC);
ProcessIntRes(KITS::COMMAND_CONNECT, data, option, result);
return result;
}
int TagSessionProxy::Reconnect(int tagRfDiscId)
{
int result = 0;
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return KITS::NfcErrorCode::NFC_SDK_ERROR_UNKOWN;
}
data.WriteInt32(tagRfDiscId);
MessageOption option(MessageOption::TF_SYNC);
ProcessIntRes(KITS::COMMAND_RECONNECT, data, option, result);
return result;
}
void TagSessionProxy::Disconnect(int tagRfDiscId)
{
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return;
}
data.WriteInt32(tagRfDiscId);
MessageOption option(MessageOption::TF_ASYNC);
ProcessCommand(KITS::COMMAND_DISCONNECT, data, option);
return;
}
std::vector<int> TagSessionProxy::GetTechList(int tagRfDiscId)
{
MessageParcel data;
MessageParcel reply;
MessageOption option(MessageOption::TF_SYNC);
if (!data.WriteInterfaceToken(GetDescriptor())) {
return std::vector<int>();
}
data.WriteInt32(tagRfDiscId);
int res = Remote()->SendRequest(KITS::COMMAND_GET_TECHLIST, data, reply, option);
if (res != ERR_NONE) {
InfoLog("It is failed To Get Tech List with Res(%{public}d).", res);
return std::vector<int>();
}
std::vector<int32_t> result {};
reply.ReadInt32Vector(&result);
return result;
}
bool TagSessionProxy::IsTagFieldOn(int tagRfDiscId)
{
bool result = false;
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return false;
}
data.WriteInt32(tagRfDiscId);
MessageOption option(MessageOption::TF_SYNC);
ProcessBoolRes(KITS::COMMAND_IS_PRESENT, data, option, result);
return result;
}
bool TagSessionProxy::IsNdef(int tagRfDiscId)
{
bool result = false;
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return false;
}
data.WriteInt32(tagRfDiscId);
MessageOption option(MessageOption::TF_SYNC);
ProcessBoolRes(KITS::COMMAND_IS_NDEF, data, option, result);
return result;
}
std::unique_ptr<ResResult> TagSessionProxy::SendRawFrame(int tagRfDiscId, std::string msg, bool raw)
{
MessageParcel data, reply;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return std::unique_ptr<ResResult>();
}
data.WriteInt32(tagRfDiscId);
data.WriteString(msg);
data.WriteBool(raw);
int res = Remote()->SendRequest(KITS::COMMAND_SEND_RAW_FRAME, data, reply, option);
if (res != ERR_NONE) {
InfoLog("It is failed To Send Raw Frame with Res(%{public}d).", res);
return std::unique_ptr<ResResult>();
}
sptr<ResResult> result = reply.ReadStrongParcelable<ResResult>();
int res1 = reply.ReadInt32();
if (res1 != ERR_NONE) {
InfoLog("It is failed To Send Raw Frame with Res1(%{public}d).", res1);
return std::unique_ptr<ResResult>();
}
std::unique_ptr<ResResult> resResult = std::make_unique<ResResult>();
resResult->SetResult(result->GetResult());
resResult->SetResData(result->GetResData());
DebugLog("TagSessionProxy::SendRawFrame result.%{public}d", result->GetResult());
return resResult;
}
std::string TagSessionProxy::NdefRead(int tagRfDiscId)
{
MessageParcel data;
MessageParcel reply;
MessageOption option(MessageOption::TF_SYNC);
if (!data.WriteInterfaceToken(GetDescriptor())) {
return "";
}
data.WriteInt32(tagRfDiscId);
int res = Remote()->SendRequest(KITS::COMMAND_NDEF_READ, data, reply, option);
if (res != ERR_NONE) {
InfoLog("It is failed To Ndef Read with Res(%{public}d).", res);
return std::string();
}
return reply.ReadString();
}
int TagSessionProxy::NdefWrite(int tagRfDiscId, std::string msg)
{
int result = 0;
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return KITS::NfcErrorCode::NFC_SDK_ERROR_UNKOWN;
}
data.WriteInt32(tagRfDiscId);
data.WriteString(msg);
MessageOption option(MessageOption::TF_SYNC);
ProcessIntRes(KITS::COMMAND_NDEF_WRITE, data, option, result);
return result;
}
int TagSessionProxy::NdefMakeReadOnly(int tagRfDiscId)
{
int result = 0;
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return KITS::NfcErrorCode::NFC_SDK_ERROR_UNKOWN;
}
data.WriteInt32(tagRfDiscId);
MessageOption option(MessageOption::TF_SYNC);
ProcessIntRes(KITS::COMMAND_NDEF_MAKE_READ_ONLY, data, option, result);
return result;
}
int TagSessionProxy::FormatNdef(int tagRfDiscId, const std::string& key)
{
int result = 0;
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return KITS::NfcErrorCode::NFC_SDK_ERROR_UNKOWN;
}
data.WriteInt32(tagRfDiscId);
data.WriteString(key);
MessageOption option(MessageOption::TF_SYNC);
ProcessIntRes(KITS::COMMAND_FORMAT_NDEF, data, option, result);
return result;
}
bool TagSessionProxy::CanMakeReadOnly(int technology)
{
bool result = false;
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return false;
}
data.WriteInt32(technology);
MessageOption option(MessageOption::TF_SYNC);
ProcessBoolRes(KITS::COMMAND_CAN_MAKE_READ_ONLY, data, option, result);
return result;
}
int TagSessionProxy::GetMaxTransceiveLength(int technology)
{
int result = 0;
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor())) {
return KITS::NfcErrorCode::NFC_SDK_ERROR_UNKOWN;
}
data.WriteInt32(technology);
MessageOption option(MessageOption::TF_SYNC);
ProcessIntRes(KITS::COMMAND_GET_MAX_TRANSCEIVE_LENGTH, data, option, result);
return result;
}
bool TagSessionProxy::IsSupportedApdusExtended()
{
bool result = false;
MessageParcel data;
MessageOption option(MessageOption::TF_SYNC);
if (!data.WriteInterfaceToken(GetDescriptor())) {
return false;
}
ProcessBoolRes(KITS::COMMAND_IS_SUPPORTED_APDUS_EXTENDED, data, option, result);
return result;
}
} // namespace TAG
} // namespace NFC
} // namespace OHOS
@@ -1,176 +0,0 @@
/*
* 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 "taginfo.h"
#include "loghelper.h"
#include "nfc_sdk_common.h"
#include "parcel.h"
#include "refbase.h"
#include "tag_session_proxy.h"
namespace OHOS {
namespace NFC {
namespace KITS {
TagInfo::TagInfo(std::vector<int> tagTechList,
std::weak_ptr<AppExecFwk::PacMap> tagTechExtrasData,
std::string& tagUid,
int tagRfDiscId,
OHOS::sptr<TAG::ITagSession> tagSession)
: tagRfDiscId_(tagRfDiscId),
connectedTagTech_(KITS::TagTechnology::NFC_INVALID_TECH),
tagUid_(tagUid),
tagTechList_(std::move(tagTechList)),
remoteTagSession_(tagSession),
tagTechExtrasData_(tagTechExtrasData.lock())
{
}
TagInfo::~TagInfo()
{
tagUid_.clear();
tagTechList_.clear();
connectedTagTech_ = KITS::TagTechnology::NFC_INVALID_TECH;
tagRfDiscId_ = 0;
}
bool TagInfo::IsTechSupported(KITS::TagTechnology tech)
{
for (auto n : tagTechList_) {
if (n == static_cast<int>(tech)) {
return true;
}
}
return false;
}
OHOS::sptr<TAG::ITagSession> TagInfo::GetRemoteTagSession() const
{
return remoteTagSession_;
}
std::weak_ptr<AppExecFwk::PacMap> TagInfo::GetTagExtrasData() const
{
return tagTechExtrasData_;
}
std::vector<int> TagInfo::GetTagTechList() const
{
return std::move(tagTechList_);
}
AppExecFwk::PacMap TagInfo::GetTechExtrasData(KITS::TagTechnology tech)
{
AppExecFwk::PacMap pacmap;
if (!tagTechExtrasData_) {
return pacmap;
}
for (int i = 0; i < int(tagTechList_.size()); i++) {
if (static_cast<int>(tech) == tagTechList_[i]) {
pacmap = tagTechExtrasData_->GetPacMap(TECH_EXTRA_DATA_PREFIX + std::to_string(i));
}
}
return pacmap;
}
std::string TagInfo::GetStringExtrasData(AppExecFwk::PacMap& extrasData, const std::string& extrasName)
{
std::string value = "";
if (extrasData.IsEmpty() || extrasName.empty()) {
return value;
}
return extrasData.GetStringValue(extrasName);
}
int TagInfo::GetIntExtrasData(AppExecFwk::PacMap& extrasData, const std::string& extrasName)
{
if (extrasData.IsEmpty() || extrasName.empty()) {
return NfcErrorCode::NFC_SDK_ERROR_INVALID_PARAM;
}
return extrasData.GetLongValue(extrasName);
}
void TagInfo::SetConnectedTagTech(KITS::TagTechnology connectedTagTech)
{
connectedTagTech_ = connectedTagTech;
}
KITS::TagTechnology TagInfo::GetConnectedTagTech() const
{
return connectedTagTech_;
}
std::string TagInfo::GetTagUid() const
{
return tagUid_;
}
int TagInfo::GetTagRfDiscId() const
{
return tagRfDiscId_;
}
bool TagInfo::Marshalling(Parcel& parcel) const
{
if (remoteTagSession_ == nullptr) {
WarnLog("TagInfo::Marshalling remoteTagSession_ is null.");
return false;
}
if (tagTechList_.size() > MAX_TAG_TECH_NUM) {
WarnLog("TagInfo::Marshalling more than MAX_TAG_TECH_NUM.");
return false;
}
parcel.WriteInt32(tagRfDiscId_);
parcel.WriteString(tagUid_);
parcel.WriteInt32(tagTechList_.size());
parcel.WriteInt32Vector(tagTechList_);
parcel.WriteObject<IRemoteObject>(remoteTagSession_->AsObject());
if (tagTechList_.size() > 0 && tagTechExtrasData_ != nullptr) {
parcel.WriteParcelable(tagTechExtrasData_.get());
}
return true;
}
std::shared_ptr<TagInfo> TagInfo::Unmarshalling(Parcel& parcel)
{
int tagRfDiscId = parcel.ReadInt32();
std::string tagUid = parcel.ReadString();
int size = parcel.ReadInt32();
if (size > MAX_TAG_TECH_NUM) {
WarnLog("TagInfo::Marshalling more than MAX_TAG_TECH_NUM.");
return nullptr;
}
std::vector<int> tagTechList;
parcel.ReadInt32Vector(&tagTechList);
sptr<IRemoteObject> tagService = parcel.ReadObject<IRemoteObject>();
if (tagService == nullptr) {
WarnLog("TagInfo::Unmarshalling tagService is null.");
return nullptr;
}
OHOS::sptr<TAG::ITagSession> tagSession = new TAG::TagSessionProxy(tagService);
std::shared_ptr<AppExecFwk::PacMap> tagTechExtrasData(parcel.ReadParcelable<AppExecFwk::PacMap>());
if (tagTechList.size() > 0 && tagTechExtrasData == nullptr) {
WarnLog("TagInfo::Unmarshalling tagTechExtrasData is null.");
return nullptr;
}
std::shared_ptr<TagInfo> tag = std::make_shared<TagInfo>(tagTechList, tagTechExtrasData,
tagUid, tagRfDiscId, tagSession);
return tag;
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,52 +0,0 @@
# Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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")
ohos_shared_library("controller") {
defines = [ "DEBUG" ]
install_enable = true
include_dirs = [
"//third_party/node/src",
"//native_engine",
"//commonlibrary/c_utils/base/include",
"//utils/system/safwk/native/include",
"//foundation/communication/nfc/nfc_core/interfaces/innerkits/include",
"//foundation/communication/nfc/nfc_core/interfaces/innerkits/include/controller",
"//base/notification/common_event_service/frameworks/core/include",
]
sources = [
"nfc_napi_controller.cpp",
"nfc_napi_controller_adapter.cpp",
"nfc_napi_controller_event.cpp",
]
deps = [ "//foundation/communication/nfc/nfc_core/interfaces/innerkits:nfc_inner_kits" ]
external_deps = [
"ability_base:want",
"c_utils:utils",
"common_event_service:cesfwk_core",
"common_event_service:cesfwk_innerkits",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"napi:ace_napi",
"samgr:samgr_proxy",
]
relative_install_dir = "module/nfc"
part_name = "nfc"
subsystem_name = "communication"
}
@@ -1,98 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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 "loghelper.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "nfc_napi_controller_adapter.h"
#include "nfc_napi_controller_event.h"
#include "nfc_sdk_common.h"
namespace OHOS {
namespace NFC {
namespace KITS {
/*
* Module initialization function
*/
static napi_value CreateEnumConstructor(napi_env env, napi_callback_info info)
{
napi_value thisArg = nullptr;
void *data = nullptr;
napi_get_cb_info(env, info, nullptr, nullptr, &thisArg, &data);
napi_value global = nullptr;
napi_get_global(env, &global);
return thisArg;
}
static napi_value CreateEnumNfcState(napi_env env, napi_value exports)
{
napi_value state_off = nullptr;
napi_value state_turning_on = nullptr;
napi_value state_on = nullptr;
napi_value state_turning_off = nullptr;
napi_create_int32(env, (int32_t)NfcState::STATE_OFF, &state_off);
napi_create_int32(env, (int32_t)NfcState::STATE_TURNING_OFF, &state_turning_off);
napi_create_int32(env, (int32_t)NfcState::STATE_ON, &state_on);
napi_create_int32(env, (int32_t)NfcState::STATE_TURNING_ON, &state_turning_on);
napi_property_descriptor desc[] = {
DECLARE_NAPI_STATIC_PROPERTY("STATE_OFF", state_off),
DECLARE_NAPI_STATIC_PROPERTY("STATE_TURNING_OFF", state_turning_off),
DECLARE_NAPI_STATIC_PROPERTY("STATE_ON", state_on),
DECLARE_NAPI_STATIC_PROPERTY("STATE_TURNING_ON", state_turning_on),
};
napi_value result = nullptr;
napi_define_class(env, "NfcState", NAPI_AUTO_LENGTH, CreateEnumConstructor, nullptr,
sizeof(desc) / sizeof(*desc), desc, &result);
napi_set_named_property(env, exports, "NfcState", result);
return exports;
}
static napi_value InitJs(napi_env env, napi_value exports)
{
DebugLog("Init, nfc_napi_controller");
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("openNfc", OpenNfc),
DECLARE_NAPI_FUNCTION("closeNfc", CloseNfc),
DECLARE_NAPI_FUNCTION("getNfcState", GetNfcState),
DECLARE_NAPI_FUNCTION("isNfcAvailable", IsNfcAvailable),
DECLARE_NAPI_FUNCTION("isNfcOpen", IsNfcOpen),
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));
CreateEnumNfcState(env, exports);
return exports;
}
static napi_module nfcControllerModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = NULL,
.nm_register_func = InitJs,
.nm_modname = "nfc.controller",
.nm_priv = ((void *)0),
.reserved = { 0 }
};
extern "C" __attribute__((constructor)) void RegisterModule(void)
{
napi_module_register(&nfcControllerModule);
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,96 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_controller_adapter.h"
#include <vector>
#include "loghelper.h"
#include "nfc_controller.h"
#include "nfc_sdk_common.h"
namespace OHOS {
namespace NFC {
namespace KITS {
napi_value OpenNfc(napi_env env, napi_callback_info info)
{
DebugLog("nfc_napi_controller_adapter::OpenNfc");
NfcController nfcCtrl = OHOS::NFC::KITS::NfcController::GetInstance();
int ret = nfcCtrl.TurnOn();
InfoLog("nfc_napi_controller_adapter::OpenNfc ret = %{pubilic}d", ret);
bool success = false;
if (ret && (ret != KITS::NFC_SDK_ERROR_NOT_INITIALIZED)) {
success = true;
}
napi_value result;
napi_get_boolean(env, success, &result);
return result;
}
napi_value CloseNfc(napi_env env, napi_callback_info info)
{
DebugLog("nfc_napi_controller_adapter::CloseNfc");
NfcController nfcCtrl = OHOS::NFC::KITS::NfcController::GetInstance();
int ret = nfcCtrl.TurnOff();
InfoLog("nfc_napi_controller_adapter::CloseNfc ret = %{pubilic}d", ret);
bool success = false;
if (ret && (ret != KITS::NFC_SDK_ERROR_NOT_INITIALIZED)) {
success = true;
}
napi_value result;
napi_get_boolean(env, success, &result);
return result;
}
napi_value GetNfcState(napi_env env, napi_callback_info info)
{
DebugLog("nfc_napi_controller_adapter::GetNfcState");
NfcController nfcCtrl = OHOS::NFC::KITS::NfcController::GetInstance();
int ret = nfcCtrl.GetNfcState();
napi_value result;
napi_create_int32(env, ret, &result);
return result;
}
napi_value IsNfcAvailable(napi_env env, napi_callback_info info)
{
DebugLog("nfc_napi_controller_adapter::IsNfcAvailable");
NfcController nfcCtrl = OHOS::NFC::KITS::NfcController::GetInstance();
int ret = nfcCtrl.IsNfcAvailable();
bool success = false;
if (ret && (ret != KITS::NFC_SDK_ERROR_NOT_INITIALIZED)) {
success = true;
}
napi_value result;
napi_get_boolean(env, success, &result);
return result;
}
napi_value IsNfcOpen(napi_env env, napi_callback_info info)
{
DebugLog("nfc_napi_controller_adapter::IsNfcOpen");
NfcController nfcCtrl = OHOS::NFC::KITS::NfcController::GetInstance();
int ret = nfcCtrl.IsNfcOpen();
bool success = false;
if (ret && (ret != KITS::NFC_SDK_ERROR_NOT_INITIALIZED)) {
success = true;
}
napi_value result;
napi_get_boolean(env, success, &result);
return result;
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,36 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_CONTROLLER_ADAPTER_H_
#define NFC_NAPI_CONTROLLER_ADAPTER_H_
#include <chrono>
#include <string>
#include "napi/native_api.h"
#include "napi/native_node_api.h"
namespace OHOS {
namespace NFC {
namespace KITS {
napi_value OpenNfc(napi_env env, napi_callback_info info);
napi_value CloseNfc(napi_env env, napi_callback_info info);
napi_value GetNfcState(napi_env env, napi_callback_info info);
napi_value IsNfcAvailable(napi_env env, napi_callback_info info);
napi_value IsNfcOpen(napi_env env, napi_callback_info info);
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif
@@ -1,356 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_controller_event.h"
#include <uv.h>
#include "loghelper.h"
#include "nfc_controller.h"
#include "nfc_sdk_common.h"
namespace OHOS {
namespace NFC {
namespace KITS {
const std::string EVENT_NFC_STATE_CHANGE = "nfcStateChange";
static std::set<std::string> g_supportEventList = {
EVENT_NFC_STATE_CHANGE,
};
bool EventRegister::isEventRegistered = false;
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);
}
}
};
void NapiEvent::EventNotify(AsyncEventData *asyncEvent)
{
DebugLog("Enter nfc event notify");
if (asyncEvent == nullptr) {
DebugLog("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) {
DebugLog("uv_work_t work is null.");
delete asyncEvent;
asyncEvent = nullptr;
return;
}
InfoLog("Get the event loop, napi_env: %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);
InfoLog("Napi event uv_queue_work, env: %{private}p, status: %{public}d", asyncData->env, status);
napi_value handler = nullptr;
napi_handle_scope scope = nullptr;
napi_open_handle_scope(asyncData->env, &scope);
if (scope == nullptr) {
DebugLog("scope is nullptr");
napi_close_handle_scope(asyncData->env, scope);
goto EXIT;
}
napi_value undefine;
napi_get_undefined(asyncData->env, &undefine);
napi_get_reference_value(asyncData->env, asyncData->callbackRef, &handler);
DebugLog("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) {
DebugLog("Report event to Js failed");
}
napi_close_handle_scope(asyncData->env, scope);
EXIT:
delete asyncData;
asyncData = nullptr;
delete work;
work = nullptr;
});
}
bool NapiEvent::CheckIsRegister(const std::string& type)
{
return g_eventRegisterInfo.find(type) != g_eventRegisterInfo.end();
}
class NfcStateListenerEvent : public INfcControllerCallback, public NapiEvent {
public:
NfcStateListenerEvent() {
}
virtual ~NfcStateListenerEvent() {
}
public:
void OnNfcStateChanged(int nfcState) override
{
InfoLog("OnNotify rcvd nfcRfState: %{public}d", nfcState);
CheckAndNotify(EVENT_NFC_STATE_CHANGE, nfcState);
}
OHOS::sptr<OHOS::IRemoteObject> AsObject() override
{
return nullptr;
}
};
sptr<NfcStateListenerEvent> nfcStateListenerEvent =
sptr<NfcStateListenerEvent>(new (std::nothrow) NfcStateListenerEvent());
napi_value On(napi_env env, napi_callback_info cbinfo)
{
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_ASSERT(env, argc >= requireArgc, "requires 2 parameter");
napi_valuetype eventName = napi_undefined;
napi_typeof(env, argv[0], &eventName);
NAPI_ASSERT(env, eventName == napi_string, "type mismatch for parameter 1");
napi_valuetype handler = napi_undefined;
napi_typeof(env, argv[1], &handler);
NAPI_ASSERT(env, handler == napi_function, "type mismatch for parameter 2");
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)
{
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_ASSERT(env, argc >= requireArgc, "requires at least 1 parameter");
napi_valuetype eventName = napi_undefined;
napi_typeof(env, argv[0], &eventName);
NAPI_ASSERT(env, eventName == napi_string, "type mismatch for parameter 1");
if (argc >= requireArgcWithCb) {
napi_valuetype handler = napi_undefined;
napi_typeof(env, argv[1], &handler);
NAPI_ASSERT(env, handler == napi_function, "type mismatch for parameter 2");
}
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;
}
NfcErrorCode EventRegister::RegisterNfcStateChangedEvents(const std::string& type)
{
NfcController nfcCtrl = NfcController::GetInstance();
NfcErrorCode ret = nfcCtrl.RegListener(nfcStateListenerEvent, type);
if (ret != KITS::NFC_SUCCESS) {
DebugLog("RegisterNfcStateChangedEvents nfcListenerEvent failed!");
return ret;
}
return ret;
}
NfcErrorCode EventRegister::UnRegisterNfcEvents(const std::string& type)
{
NfcController nfcCtrl = OHOS::NFC::KITS::NfcController::GetInstance();
NfcErrorCode ret = nfcCtrl.UnregListener(type);
if (ret != KITS::NFC_SUCCESS) {
DebugLog("UnRegisterNfcEvents 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)
{
InfoLog("Register event: %{public}s, env: %{public}p", type.c_str(), env);
if (!IsEventSupport(type)) {
DebugLog("Register type error or not support!");
return;
}
std::unique_lock<std::shared_mutex> guard(g_regInfoMutex);
if (!isEventRegistered) {
if (RegisterNfcStateChangedEvents(type) != KITS::NFC_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};
DebugLog("Register, add new type.");
return;
}
auto miter = iter->second.begin();
for (; miter != iter->second.end();) {
if (env == miter->m_regEnv) {
napi_value handlerTemp = nullptr;
napi_get_reference_value(miter->m_regEnv, miter->m_regHanderRef, &handlerTemp);
bool isEqual = false;
napi_strict_equals(miter->m_regEnv, handlerTemp, handler, &isEqual);
if (isEqual) {
DebugLog("handler function is same");
++miter;
} else {
iter->second.emplace_back(regObj);
break;
}
} else {
iter->second.emplace_back(regObj);
break;
}
}
}
void EventRegister::DeleteRegisterObj(const napi_env& env, std::vector<RegObj>& vecRegObjs, napi_value& handler)
{
auto iter = vecRegObjs.begin();
for (; iter != vecRegObjs.end();) {
if (env == iter->m_regEnv) {
napi_value handlerTemp = nullptr;
napi_get_reference_value(iter->m_regEnv, iter->m_regHanderRef, &handlerTemp);
bool isEqual = false;
if (handlerTemp == nullptr) {
DebugLog("handlerTemp is null");
}
if (handler == nullptr) {
DebugLog("handler is null");
}
napi_strict_equals(iter->m_regEnv, handlerTemp, handler, &isEqual);
DebugLog("Delete register isEqual = %{public}d", isEqual);
if (isEqual) {
napi_delete_reference(iter->m_regEnv, iter->m_regHanderRef);
DebugLog("Delete register object ref.");
iter = vecRegObjs.erase(iter);
} else {
++iter;
}
} else {
DebugLog("Unregister event, env is not equal %{private}p, : %{private}p", env, iter->m_regEnv);
++iter;
}
}
}
void EventRegister::DeleteAllRegisterObj(const napi_env& env, std::vector<RegObj>& vecRegObjs)
{
auto iter = vecRegObjs.begin();
for (; iter != vecRegObjs.end();) {
if (env == iter->m_regEnv) {
napi_delete_reference(iter->m_regEnv, iter->m_regHanderRef);
iter = vecRegObjs.erase(iter);
} else {
DebugLog("Unregister all event, env is not equal %{private}p, : %{private}p", env, iter->m_regEnv);
++iter;
}
}
}
void EventRegister::Unregister(const napi_env& env, const std::string& type, napi_value handler)
{
InfoLog("Unregister event: %{public}s, env: %{public}p", type.c_str(), env);
if (!IsEventSupport(type)) {
DebugLog("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()) {
DebugLog("Unregister type not registered!");
if (UnRegisterNfcEvents(type) != KITS::NFC_SUCCESS) {
ErrorLog("UnRegisterNfcEvents failed.");
}
return;
}
if (handler != nullptr) {
DeleteRegisterObj(env, iter->second, handler);
} else {
InfoLog("All callback is unsubscribe for event: %{public}s", type.c_str());
DeleteAllRegisterObj(env, iter->second);
}
if (iter->second.empty()) {
g_eventRegisterInfo.erase(iter);
if (UnRegisterNfcEvents(type) != KITS::NFC_SUCCESS) {
ErrorLog("UnRegisterNfcEvents failed.");
}
isEventRegistered = false;
}
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,100 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_CONTROLLER_EVENT_H_
#define NFC_NAPI_CONTROLLER_EVENT_H_
#include <map>
#include <set>
#include <shared_mutex>
#include <string>
#include <uv.h>
#include <vector>
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "nfc_sdk_common.h"
#include "infc_controller_callback.h"
namespace OHOS {
namespace NFC {
namespace KITS {
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;
};
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:
NfcErrorCode RegisterNfcStateChangedEvents(const std::string& type);
NfcErrorCode UnRegisterNfcEvents(const std::string& type);
bool IsEventSupport(const std::string& type);
void DeleteRegisterObj(const napi_env& env, std::vector<RegObj>& vecRegObjs, napi_value& handler);
void DeleteAllRegisterObj(const napi_env& env, 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 KITS
} // namespace NFC
} // namespace OHOS
#endif
-57
View File
@@ -1,57 +0,0 @@
# Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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")
ohos_shared_library("tag") {
defines = [ "DEBUG" ]
install_enable = true
include_dirs = [
"//third_party/node/src",
"//native_engine",
"//foundation/communication/nfc/nfc_core/interfaces/innerkits/include",
"//foundation/communication/nfc/nfc_core/interfaces/innerkits/include/tags",
]
sources = [
"nfc_napi_ndef_message.cpp",
"nfc_napi_tag.cpp",
"nfc_napi_tag_isodep.cpp",
"nfc_napi_tag_mifare_classic.cpp",
"nfc_napi_tag_mifare_ul.cpp",
"nfc_napi_tag_ndef.cpp",
"nfc_napi_tag_ndef_formatable.cpp",
"nfc_napi_tag_sesstion.cpp",
"nfc_napi_taga.cpp",
"nfc_napi_tagb.cpp",
"nfc_napi_tagf.cpp",
"nfc_napi_tagv.cpp",
"nfc_napi_utils.cpp",
]
deps = [ "//foundation/communication/nfc/nfc_core/interfaces/innerkits:nfc_inner_kits" ]
external_deps = [
"ability_base:want",
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"napi:ace_napi",
"samgr:samgr_proxy",
]
relative_install_dir = "module/nfc"
part_name = "nfc"
subsystem_name = "communication"
}
@@ -1,271 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_ndef_message.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
napi_value NapiNdefMessage::GetNdefRecords(napi_env env, napi_callback_info info)
{
DebugLog("NdefMessage GetNdefRecords called");
napi_value thisVar = nullptr;
std::size_t argc = 0;
napi_value argv[ARGV_NUM_1] = {0};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiNdefMessage *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
// transfer
NdefMessage *ndefMessagePtr = static_cast<NdefMessage *>(static_cast<void *>(objectInfo));
if (ndefMessagePtr == nullptr) {
ErrorLog("GetNdefRecords find objectInfo failed!");
return nullptr;
} else {
std::vector<std::shared_ptr<NdefRecord>> ndefRecords = ndefMessagePtr->GetNdefRecords();
napi_value result = nullptr;
ConvertNdefRecordVectorToJS(env, result, ndefRecords);
return result;
}
}
napi_value NapiNdefMessage::MakeUriRecord(napi_env env, napi_callback_info info)
{
DebugLog("NdefMessage MakeUriRecord called");
napi_value thisVar = nullptr;
std::size_t argc = ARGV_NUM_1;
napi_value argv[ARGV_NUM_1] = {0};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiNdefMessage *objectInfo = nullptr;
// check parameter number
if (argc != ARGV_NUM_1) {
ErrorLog("NapiNdefMessage::MakeUriRecord, Invalid number of arguments!");
return nullptr;
}
napi_valuetype valueType = napi_undefined;
NAPI_CALL(env, napi_typeof(env, argv[ARGV_INDEX_0], &valueType));
// check parameter data type
if (valueType != napi_string) {
ErrorLog("NapiNdefMessage::MakeUriRecord, Invalid data type!");
return nullptr;
}
std::string uri = GetStringFromValue(env, argv[ARGV_INDEX_0]);
DebugLog("MakeUriRecord uri = %{public}s", uri.c_str());
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
// transfer
NdefMessage *ndefMessagePtr = static_cast<NdefMessage *>(static_cast<void *>(objectInfo));
if (ndefMessagePtr == nullptr) {
ErrorLog("MakeUriRecord find objectInfo failed!");
return nullptr;
} else {
std::shared_ptr<NdefRecord> ndefRecord = ndefMessagePtr->MakeUriRecord(uri);
napi_value result = nullptr;
ConvertNdefRecordToJS(env, result, ndefRecord);
return result;
}
}
napi_value NapiNdefMessage::MakeTextRecord(napi_env env, napi_callback_info info)
{
DebugLog("MakeTextRecord called");
napi_value thisVar = nullptr;
std::size_t argc = ARGV_NUM_2;
napi_value argv[ARGV_NUM_2] = {0};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiNdefMessage *objectInfo = nullptr;
// check parameter number
if (argc != ARGV_NUM_2) {
ErrorLog("NapiNdefMessage::MakeTextRecord, Invalid number of arguments!");
return nullptr;
}
napi_valuetype valueType1 = napi_undefined;
napi_valuetype valueType2 = napi_undefined;
NAPI_CALL(env, napi_typeof(env, argv[ARGV_INDEX_0], &valueType1));
NAPI_CALL(env, napi_typeof(env, argv[ARGV_INDEX_1], &valueType2));
// check parameter data type
if ((valueType1 != napi_string) || (valueType2 != napi_string)) {
ErrorLog("NapiNdefMessage::MakeTextRecord, Invalid data type!");
return nullptr;
}
std::string text = GetStringFromValue(env, argv[ARGV_INDEX_0]);
std::string locale = GetStringFromValue(env, argv[ARGV_INDEX_1]);
DebugLog("MakeTextRecord text = %{public}s, locale = = %{public}s", text.c_str(), locale.c_str());
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
// transfer
NdefMessage *ndefMessagePtr = static_cast<NdefMessage *>(static_cast<void *>(objectInfo));
if (ndefMessagePtr == nullptr) {
ErrorLog("MakeTextRecord find objectInfo failed!");
return nullptr;
} else {
std::shared_ptr<NdefRecord> ndefRecord = ndefMessagePtr->MakeTextRecord(text, locale);
napi_value result = nullptr;
ConvertNdefRecordToJS(env, result, ndefRecord);
return result;
}
}
napi_value NapiNdefMessage::MakeMimeRecord(napi_env env, napi_callback_info info)
{
DebugLog("MakeMimeRecord MakeUriRecord called");
napi_value thisVar = nullptr;
std::size_t argc = ARGV_NUM_2;
napi_value argv[ARGV_NUM_2] = {0};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiNdefMessage *objectInfo = nullptr;
// check parameter number
if (argc != ARGV_NUM_2) {
ErrorLog("NapiNdefMessage::MakeMimeRecord, Invalid number of arguments!");
return nullptr;
}
napi_valuetype valueType1 = napi_undefined;
napi_valuetype valueType2 = napi_undefined;
NAPI_CALL(env, napi_typeof(env, argv[ARGV_INDEX_0], &valueType1));
NAPI_CALL(env, napi_typeof(env, argv[ARGV_INDEX_1], &valueType2));
// check parameter data type
if ((valueType1 != napi_string) || (valueType2 != napi_string)) {
ErrorLog("NapiNdefMessage::MakeMimeRecord, Invalid data type!");
return nullptr;
}
std::string mimeType = GetStringFromValue(env, argv[ARGV_INDEX_0]);
std::string mimeData = GetStringFromValue(env, argv[ARGV_INDEX_1]);
DebugLog("MakeMimeRecord mimeType = %{public}s, mimeData = = %{public}s", mimeType.c_str(), mimeData.c_str());
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("MakeMimeRecord objInfo %{public}p", objectInfo);
// transfer
NdefMessage *ndefMessagePtr = static_cast<NdefMessage *>(static_cast<void *>(objectInfo));
if (ndefMessagePtr == nullptr) {
ErrorLog("MakeMimeRecord find objectInfo failed!");
return nullptr;
} else {
std::shared_ptr<NdefRecord> ndefRecord = ndefMessagePtr->MakeMimeRecord(mimeType, mimeData);
napi_value result = nullptr;
ConvertNdefRecordToJS(env, result, ndefRecord);
return result;
}
}
napi_value NapiNdefMessage::MakeExternalRecord(napi_env env, napi_callback_info info)
{
DebugLog("MakeExternalRecord MakeUriRecord called");
napi_value thisVar = nullptr;
std::size_t argc = ARGV_NUM_3;
napi_value argv[ARGV_NUM_3] = {0};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiNdefMessage *objectInfo = nullptr;
// check parameter number
if (argc != ARGV_NUM_3) {
ErrorLog("NapiNdefMessage::MakeExternalRecord, Invalid number of arguments!");
return nullptr;
}
napi_valuetype valueType1 = napi_undefined;
napi_valuetype valueType2 = napi_undefined;
napi_valuetype valueType3 = napi_undefined;
NAPI_CALL(env, napi_typeof(env, argv[ARGV_INDEX_0], &valueType1));
NAPI_CALL(env, napi_typeof(env, argv[ARGV_INDEX_1], &valueType2));
NAPI_CALL(env, napi_typeof(env, argv[ARGV_INDEX_2], &valueType3));
// check parameter data type
if ((valueType1 != napi_string) || (valueType2 != napi_string) || (valueType3 != napi_string)) {
ErrorLog("NapiNdefMessage::MakeExternalRecord, Invalid data type!");
return nullptr;
}
std::string domainName = GetStringFromValue(env, argv[ARGV_INDEX_0]);
std::string serviceName = GetStringFromValue(env, argv[ARGV_INDEX_1]);
std::string externalData = GetStringFromValue(env, argv[ARGV_INDEX_2]);
DebugLog("MakeExternalRecord domainName = %{public}s, serviceName = %{public}s, externalData = %{public}s",
domainName.c_str(), serviceName.c_str(), externalData.c_str());
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("MakeExternalRecord objInfo %{public}p", objectInfo);
// transfer
NdefMessage *ndefMessagePtr = static_cast<NdefMessage *>(static_cast<void *>(objectInfo));
if (ndefMessagePtr == nullptr) {
ErrorLog("MakeExternalRecord find objectInfo failed!");
return nullptr;
} else {
std::shared_ptr<NdefRecord> ndefRecord =
ndefMessagePtr->MakeExternalRecord(domainName, serviceName, externalData);
napi_value result = nullptr;
ConvertNdefRecordToJS(env, result, ndefRecord);
return result;
}
}
napi_value NapiNdefMessage::MessageToString(napi_env env, napi_callback_info info)
{
DebugLog("MessageToString MakeUriRecord called");
napi_value thisVar = nullptr;
std::size_t argc = ARGV_NUM_1;
napi_value argv[ARGV_NUM_1] = {0};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiNdefMessage *objectInfo = nullptr;
std::shared_ptr<NdefMessage> ndefMessage = nullptr;
// check parameter number
if (argc != ARGV_NUM_1) {
ErrorLog("NapiNdefMessage::MessageToString, Invalid number of arguments!");
return nullptr;
}
napi_valuetype valueType = napi_undefined;
NAPI_CALL(env, napi_typeof(env, argv[ARGV_INDEX_0], &valueType));
// check parameter data type
if (valueType != napi_object) {
ErrorLog("NapiNdefMessage::MessageToString, Invalid data type!");
return nullptr;
}
napi_status status1 = napi_unwrap(env, argv[ARGV_INDEX_0], reinterpret_cast<void **>(&ndefMessage));
NAPI_ASSERT(env, status1 == napi_ok, "failed to get ndefMessage");
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("MessageToString objInfo %{public}p", objectInfo);
// transfer
NdefMessage *ndefMessagePtr = static_cast<NdefMessage *>(static_cast<void *>(objectInfo));
if (ndefMessagePtr == nullptr) {
ErrorLog("MessageToString find objectInfo failed!");
return nullptr;
} else {
std::string buffer = ndefMessagePtr->MessageToString(ndefMessage);
napi_value result = nullptr;
ErrorLog("buffer %{public}s", buffer.c_str());
napi_create_string_utf8(env, buffer.c_str(), NAPI_AUTO_LENGTH, &result);
return result;
}
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,42 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_NDEF_MESSAGE_H_
#define NFC_NAPI_NDEF_MESSAGE_H_
#include <locale>
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "ndef_tag.h"
#include "ndef_message.h"
#include "nfc_napi_tag_sesstion.h"
#include "nfc_napi_utils.h"
namespace OHOS {
namespace NFC {
namespace KITS {
struct NapiNdefMessage {
static napi_value GetNdefRecords(napi_env env, napi_callback_info info);
static napi_value MakeUriRecord(napi_env env, napi_callback_info info);
static napi_value MakeTextRecord(napi_env env, napi_callback_info info);
static napi_value MakeMimeRecord(napi_env env, napi_callback_info info);
static napi_value MakeExternalRecord(napi_env env, napi_callback_info info);
static napi_value MessageToString(napi_env env, napi_callback_info info);
std::shared_ptr<NdefMessage> ndefMessage = nullptr;
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif
@@ -1,643 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_tag.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
napi_value nfcATagObject;
napi_value nfcBTagObject;
napi_value nfcFTagObject;
napi_value nfcVTagObject; // iso15693
napi_value isoDepTagObject;
napi_value ndefTagObject;
napi_value mifareClassicTagObject;
napi_value mifareUltralightTagObject;
napi_value ndefFormatableTagObject;
std::shared_ptr<TagInfo> nfcTaginfo;
napi_value ParseIntArray(napi_env env, napi_value obj, std::vector<int> &typeArray)
{
const int32_t ERROR_DEFAULT = -1;
bool result = false;
napi_status status = napi_is_array(env, obj, &result);
if (status != napi_ok || !result) {
ErrorLog("Invalid input parameter type!");
return nullptr;
}
napi_value elementValue = nullptr;
int32_t element = ERROR_DEFAULT;
uint32_t arrayLength = 0;
NAPI_CALL(env, napi_get_array_length(env, obj, &arrayLength));
typeArray.resize(arrayLength);
for (uint32_t i = 0; i < arrayLength; ++i) {
NAPI_CALL(env, napi_get_element(env, obj, i, &elementValue));
napi_valuetype valueType = napi_undefined;
napi_typeof(env, elementValue, &valueType);
if (valueType == napi_number) {
NAPI_CALL(env, napi_get_value_int32(env, elementValue, &element));
typeArray[i] = element;
DebugLog("tag tech array :%{public}d is %{public}d ", i, element);
} else {
ErrorLog("Invalid parameter type of array element!");
return nullptr;
}
}
return CreateUndefined(env);
}
void SetPacMapObject(
std::shared_ptr<AppExecFwk::PacMap> &pacMap, const napi_env &env, std::string keyStr, napi_value value)
{
napi_valuetype valueType = napi_undefined;
napi_typeof(env, value, &valueType);
if (valueType == napi_string) {
std::string valueString = UnwrapStringFromJS(env, value);
DebugLog("SetPacMap keystr :%{public}s", valueString.c_str());
pacMap->PutStringValue(keyStr, valueString);
} else if (valueType == napi_number) {
double valueNumber = 0;
napi_get_value_double(env, value, &valueNumber);
pacMap->PutDoubleValue(keyStr, valueNumber);
} else if (valueType == napi_boolean) {
bool valueBool = false;
napi_get_value_bool(env, value, &valueBool);
pacMap->PutBooleanValue(keyStr, valueBool);
} else if (valueType == napi_null) {
pacMap->PutObject(keyStr, nullptr);
} else if (valueType == napi_object) {
pacMap->PutStringValueArray(keyStr, ConvertStringVector(env, value));
} else {
ErrorLog("SetPacMapObject pacMap type error");
}
}
void AnalysisPacMap(std::shared_ptr<AppExecFwk::PacMap> &pacMap, const napi_env &env, const napi_value &arg)
{
DebugLog("AnalysisPacMap begin");
napi_value keys = 0;
napi_get_property_names(env, arg, &keys);
uint32_t arrLen = 0;
napi_status status = napi_get_array_length(env, keys, &arrLen);
if (status != napi_ok) {
ErrorLog("AnalysisPacMap errr");
return;
}
for (size_t i = 0; i < arrLen; ++i) {
napi_value key = 0;
status = napi_get_element(env, keys, i, &key);
std::string keyStr = UnwrapStringFromJS(env, key);
napi_value value = 0;
napi_get_property(env, arg, key, &value);
SetPacMapObject(pacMap, env, keyStr, value);
}
}
napi_value ParseExtrasData(napi_env env, napi_value obj, std::shared_ptr<AppExecFwk::PacMap> &tagTechExtrasData)
{
napi_valuetype valueType = napi_undefined;
napi_typeof(env, obj, &valueType);
if (valueType == napi_object) {
DebugLog("PacMap parse begin");
AnalysisPacMap(tagTechExtrasData, env, obj);
} else {
ErrorLog("ParseExtrasData wrong arg!");
return nullptr;
}
return CreateUndefined(env);
}
napi_value ParseTagSession(napi_env env, napi_value obj, OHOS::sptr<TAG::ITagSession> &tagSession)
{
napi_valuetype valueType = napi_undefined;
napi_typeof(env, obj, &valueType);
if (valueType == napi_object) {
DebugLog("TagSession is object");
} else {
ErrorLog("ParseTagSession arg err!");
return nullptr;
}
return CreateUndefined(env);
}
std::shared_ptr<TagInfo> ParseTagInfo(napi_env env, napi_value obj)
{
std::string tagUid = GetNapiStringValue(env, obj, "uid");
DebugLog("tag uid:%{public}s", tagUid.c_str());
std::vector<int> tagTechList;
napi_value technology = GetNamedProperty(env, obj, "technology");
if (technology) {
if (ParseIntArray(env, technology, tagTechList) == nullptr) {
DebugLog("parse tagTechList failed");
return nullptr;
}
} else {
// if technology is not set, check supportedProfiles
napi_value supportedProfiles = GetNamedProperty(env, obj, "supportedProfiles");
// if supportedProfiles is not null, set tagTechList with it
if (supportedProfiles) {
if (ParseIntArray(env, supportedProfiles, tagTechList) == nullptr) {
DebugLog("parse supportedProfiles failed");
return nullptr;
}
}
}
std::shared_ptr<AppExecFwk::PacMap> tagTechExtrasData = std::make_shared<AppExecFwk::PacMap>();
napi_value extrasData = GetNamedProperty(env, obj, "extrasData");
if (extrasData) {
if (ParseExtrasData(env, extrasData, tagTechExtrasData) == nullptr) {
ErrorLog("parse tagTechExtrasData failed");
return nullptr;
}
}
int tagRfDiscId = GetNapiInt32Value(env, obj, "tagRfDiscId");
DebugLog("tag RfDiscId:%{public}d", tagRfDiscId);
OHOS::sptr<TAG::ITagSession> tagSession = nullptr;
napi_value remoteTagSession = GetNamedProperty(env, obj, "remoteTagService");
if (remoteTagSession) {
if (ParseTagSession(env, remoteTagSession, tagSession) == nullptr) {
ErrorLog("parse tagSession failed");
return nullptr;
}
}
DebugLog("taginfo parse finished.");
return std::make_shared<TagInfo>(tagTechList, tagTechExtrasData, tagUid, tagRfDiscId, tagSession);
}
template<typename T>
bool RegisterTag(NapiNfcTagSession *nfcTag, std::shared_ptr<TagInfo> nfcTaginfo)
{
nfcTag->tagSession = T::GetTag(nfcTaginfo);
return nfcTag->tagSession != nullptr ? true : false;
}
template<typename T, typename D>
napi_value JS_Constructor(napi_env env, napi_callback_info cbinfo)
{
DebugLog("nfcTag JS_Constructor");
// nfcTag is defined as a native instance that will be wrapped in the JS object
NapiNfcTagSession *nfcTag = new T();
size_t argc = 1;
napi_value argv[] = {nullptr};
napi_value thisVar = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, nullptr));
// check parameter number
if (argc != static_cast<size_t>(JS_ARGV_INDEX::ARGV_INDEX_1)) {
ErrorLog("Invalid number of arguments");
return nullptr;
}
napi_valuetype valueType = napi_undefined;
NAPI_CALL(env, napi_typeof(env, argv[static_cast<size_t>(JS_ARGV_INDEX::ARGV_INDEX_0)], &valueType));
// check parameter data type
if (valueType != napi_object) {
ErrorLog("invalid data type!");
return nullptr;
}
// parse Taginfo parameters passed from JS
nfcTaginfo = ParseTagInfo(env, argv[static_cast<size_t>(JS_ARGV_INDEX::ARGV_INDEX_0)]);
if (nfcTaginfo == nullptr) {
ErrorLog("taginfo parse failed.");
return nullptr;
}
if (!RegisterTag<D>(nfcTag, nfcTaginfo)) {
ErrorLog("Get Nfc Tag failed");
return nullptr;
}
// wrap data into thisVar
napi_status status = napi_wrap(
env, thisVar, nfcTag,
[](napi_env env, void *data, void *hint) {
if (data) {
T *nfcTag = (T *)data;
delete nfcTag;
}
},
nullptr, nullptr);
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
return thisVar;
}
napi_status InitNfcForumType(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_STATIC_PROPERTY(
"NFC_FORUM_TYPE_1 ", GetNapiValue(env, static_cast<int32_t>(NdefTag::EmNfcForumType::NFC_FORUM_TYPE_1))),
DECLARE_NAPI_STATIC_PROPERTY(
"NFC_FORUM_TYPE_2 ", GetNapiValue(env, static_cast<int32_t>(NdefTag::EmNfcForumType::NFC_FORUM_TYPE_2))),
DECLARE_NAPI_STATIC_PROPERTY(
"NFC_FORUM_TYPE_3 ", GetNapiValue(env, static_cast<int32_t>(NdefTag::EmNfcForumType::NFC_FORUM_TYPE_3))),
DECLARE_NAPI_STATIC_PROPERTY(
"NFC_FORUM_TYPE_4 ", GetNapiValue(env, static_cast<int32_t>(NdefTag::EmNfcForumType::NFC_FORUM_TYPE_4))),
DECLARE_NAPI_STATIC_PROPERTY(
"MIFARE_CLASSIC ", GetNapiValue(env, static_cast<int32_t>(NdefTag::EmNfcForumType::MIFARE_CLASSIC))),
};
constexpr size_t arrSize = sizeof(desc) / sizeof(desc[0]);
DefineEnumClassByName(env, exports, "NfcForumType ", arrSize, desc);
return napi_define_properties(env, exports, arrSize, desc);
}
napi_status InitMifareClassicType(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_STATIC_PROPERTY(
"TYPE_UNKOWN", GetNapiValue(env, static_cast<int32_t>(MifareClassicTag::EmMifareTagType::TYPE_UNKNOWN))),
DECLARE_NAPI_STATIC_PROPERTY(
"TYPE_CLASSIC", GetNapiValue(env, static_cast<int32_t>(MifareClassicTag::EmMifareTagType::TYPE_CLASSIC))),
DECLARE_NAPI_STATIC_PROPERTY(
"TYPE_PLUS", GetNapiValue(env, static_cast<int32_t>(MifareClassicTag::EmMifareTagType::TYPE_PLUS))),
DECLARE_NAPI_STATIC_PROPERTY(
"TYPE_PRO", GetNapiValue(env, static_cast<int32_t>(MifareClassicTag::EmMifareTagType::TYPE_PRO))),
};
constexpr size_t arrSize = sizeof(desc) / sizeof(desc[0]);
DefineEnumClassByName(env, exports, "MifareUltralightType", arrSize, desc);
return napi_define_properties(env, exports, arrSize, desc);
}
napi_status InitMifareUltralightType(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_STATIC_PROPERTY("TYPE_UNKOWN",
GetNapiValue(env, static_cast<int32_t>(MifareUltralightTag::EmMifareUltralightType::TYPE_UNKOWN))),
DECLARE_NAPI_STATIC_PROPERTY("TYPE_ULTRALIGHT",
GetNapiValue(env, static_cast<int32_t>(MifareUltralightTag::EmMifareUltralightType::TYPE_ULTRALIGHT))),
DECLARE_NAPI_STATIC_PROPERTY("TYPE_ULTRALIGHT_C",
GetNapiValue(env, static_cast<int32_t>(MifareUltralightTag::EmMifareUltralightType::TYPE_ULTRALIGHT_C))),
};
constexpr size_t arrSize = sizeof(desc) / sizeof(desc[0]);
DefineEnumClassByName(env, exports, "MifareUltralightType", arrSize, desc);
return napi_define_properties(env, exports, arrSize, desc);
}
napi_value RegisternfcATagObject(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("getSak", NapiNfcATag::GetSak),
DECLARE_NAPI_FUNCTION("getAtqa", NapiNfcATag::GetAtqa),
DECLARE_NAPI_FUNCTION("connectTag", NapiNfcTagSession::ConnectTag),
DECLARE_NAPI_FUNCTION("reset", NapiNfcTagSession::Reset),
DECLARE_NAPI_FUNCTION("isTagConnected", NapiNfcTagSession::IsTagConnected),
DECLARE_NAPI_FUNCTION("getMaxSendLength", NapiNfcTagSession::GetMaxSendLength),
};
// define JS class NfcATag, JS_Constructor is the callback function
NAPI_CALL(env,
napi_define_class(env, "NfcATag", NAPI_AUTO_LENGTH, JS_Constructor<NapiNfcATag, NfcATag>, nullptr,
sizeof(desc) / sizeof(desc[0]), desc, &nfcATagObject));
return exports;
}
napi_value RegisternfcBTagObject(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("getRespAppData", NapiNfcBTag::GetRespAppData),
DECLARE_NAPI_FUNCTION("getRespProtocol", NapiNfcBTag::GetRespProtocol),
DECLARE_NAPI_FUNCTION("connectTag", NapiNfcTagSession::ConnectTag),
DECLARE_NAPI_FUNCTION("reset", NapiNfcTagSession::Reset),
DECLARE_NAPI_FUNCTION("isTagConnected", NapiNfcTagSession::IsTagConnected),
DECLARE_NAPI_FUNCTION("getMaxSendLength", NapiNfcTagSession::GetMaxSendLength),
};
// define JS class NfcBTag, JS_Constructor is the callback function
NAPI_CALL(env,
napi_define_class(env, "NfcBTag", NAPI_AUTO_LENGTH, JS_Constructor<NapiNfcBTag, NfcBTag>, nullptr,
sizeof(desc) / sizeof(desc[0]), desc, &nfcBTagObject));
return exports;
}
napi_value RegisternfcFTagObject(napi_env env, napi_value exports)
{
DebugLog("Register nfcFTag Object begin");
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("getSystemCode", NapiNfcFTag::GetSystemCode),
DECLARE_NAPI_FUNCTION("getPmm", NapiNfcFTag::GetPmm),
DECLARE_NAPI_FUNCTION("connectTag", NapiNfcTagSession::ConnectTag),
DECLARE_NAPI_FUNCTION("reset", NapiNfcTagSession::Reset),
DECLARE_NAPI_FUNCTION("isTagConnected", NapiNfcTagSession::IsTagConnected),
DECLARE_NAPI_FUNCTION("getMaxSendLength", NapiNfcTagSession::GetMaxSendLength),
};
// define JS class NfcFTag, JS_Constructor is the callback function
NAPI_CALL(env,
napi_define_class(env, "NfcFTag", NAPI_AUTO_LENGTH, JS_Constructor<NapiNfcFTag, NfcFTag>, nullptr,
sizeof(desc) / sizeof(desc[0]), desc, &nfcFTagObject));
return exports;
}
napi_value RegisternfcVTagObject(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("getResponseFlags", NapiNfcVTag::GetResponseFlags),
DECLARE_NAPI_FUNCTION("getDsfId", NapiNfcVTag::GetDsfId),
DECLARE_NAPI_FUNCTION("connectTag", NapiNfcTagSession::ConnectTag),
DECLARE_NAPI_FUNCTION("reset", NapiNfcTagSession::Reset),
DECLARE_NAPI_FUNCTION("isTagConnected", NapiNfcTagSession::IsTagConnected),
DECLARE_NAPI_FUNCTION("getMaxSendLength", NapiNfcTagSession::GetMaxSendLength),
};
// define JS class NfcVTag, JS_Constructor is the callback function
NAPI_CALL(env,
napi_define_class(env, "NfcVTag", NAPI_AUTO_LENGTH, JS_Constructor<NapiNfcVTag, Iso15693Tag>, nullptr,
sizeof(desc) / sizeof(desc[0]), desc, &nfcVTagObject));
return exports;
}
napi_value RegisterIsoDepTagObject(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("getHistoricalBytes", NapiIsoDepTag::GetHistoricalBytes),
DECLARE_NAPI_FUNCTION("getHiLayerResponse", NapiIsoDepTag::GetHiLayerResponse),
DECLARE_NAPI_FUNCTION("isExtendedApduSupported", NapiIsoDepTag::IsExtendedApduSupported),
DECLARE_NAPI_FUNCTION("connectTag", NapiNfcTagSession::ConnectTag),
DECLARE_NAPI_FUNCTION("reset", NapiNfcTagSession::Reset),
DECLARE_NAPI_FUNCTION("isTagConnected", NapiNfcTagSession::IsTagConnected),
DECLARE_NAPI_FUNCTION("getMaxSendLength", NapiNfcTagSession::GetMaxSendLength),
};
// define JS class IsoDepTag, JS_Constructor is the callback function
NAPI_CALL(env,
napi_define_class(env, "IsoDepTag", NAPI_AUTO_LENGTH, JS_Constructor<NapiIsoDepTag, IsoDepTag>, nullptr,
sizeof(desc) / sizeof(desc[0]), desc, &isoDepTagObject));
return exports;
}
napi_value RegisterNdefTagObject(napi_env env, napi_value exports)
{
// register NdefMessage object
NapiNdefTag::RegisterNdefMessageObject(env, exports);
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("createNdefMessage", NapiNdefTag::CreateNdefMessage),
DECLARE_NAPI_FUNCTION("getNdefTagType", NapiNdefTag::GetNdefTagType),
DECLARE_NAPI_FUNCTION("getNdefMessage", NapiNdefTag::GetNdefMessage),
DECLARE_NAPI_FUNCTION("isNdefWritable", NapiNdefTag::IsNdefWritable),
DECLARE_NAPI_FUNCTION("readNdef", NapiNdefTag::ReadNdef),
DECLARE_NAPI_FUNCTION("writeNdef", NapiNdefTag::WriteNdef),
DECLARE_NAPI_FUNCTION("canSetReadOnly", NapiNdefTag::CanSetReadOnly),
DECLARE_NAPI_FUNCTION("setReadOnly", NapiNdefTag::SetReadOnly),
DECLARE_NAPI_FUNCTION("getNdefTagTypeString", NapiNdefTag::GetNdefTagTypeString),
};
NAPI_CALL(env, InitNfcForumType(env, exports));
// define JS class NdefTag, JS_Constructor is the callback function
NAPI_CALL(env,
napi_define_class(env, "NdefTag", NAPI_AUTO_LENGTH, JS_Constructor<NapiNdefTag, NdefTag>, nullptr,
sizeof(desc) / sizeof(desc[0]), desc, &ndefTagObject));
return exports;
}
napi_value RegisterMifareClassicTagObject(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("authenticateSector", NapiMifareClassicTag::AuthenticateSector),
DECLARE_NAPI_FUNCTION("readSingleBlock", NapiMifareClassicTag::ReadSingleBlock),
DECLARE_NAPI_FUNCTION("writeSingleBlock", NapiMifareClassicTag::WriteSingleBlock),
DECLARE_NAPI_FUNCTION("incrementBlock", NapiMifareClassicTag::IncrementBlock),
DECLARE_NAPI_FUNCTION("decrementBlock", NapiMifareClassicTag::DecrementBlock),
DECLARE_NAPI_FUNCTION("transferToBlock", NapiMifareClassicTag::TransferToBlock),
DECLARE_NAPI_FUNCTION("restoreFromBlock", NapiMifareClassicTag::RestoreFromBlock),
DECLARE_NAPI_FUNCTION("getSectorCount", NapiMifareClassicTag::GetSectorCount),
DECLARE_NAPI_FUNCTION("getBlockCountInSector", NapiMifareClassicTag::GetBlockCountInSector),
DECLARE_NAPI_FUNCTION("getType", NapiMifareClassicTag::GetType),
DECLARE_NAPI_FUNCTION("getTagSize", NapiMifareClassicTag::GetTagSize),
DECLARE_NAPI_FUNCTION("isEmulatedTag", NapiMifareClassicTag::IsEmulatedTag),
DECLARE_NAPI_FUNCTION("getBlockIndex", NapiMifareClassicTag::GetBlockIndex),
DECLARE_NAPI_FUNCTION("getSectorIndex", NapiMifareClassicTag::GetSectorIndex),
DECLARE_NAPI_FUNCTION("reset", NapiNfcTagSession::Reset),
DECLARE_NAPI_FUNCTION("isTagConnected", NapiNfcTagSession::IsTagConnected),
DECLARE_NAPI_FUNCTION("getMaxSendLength", NapiNfcTagSession::GetMaxSendLength),
};
NAPI_CALL(env, InitMifareClassicType(env, exports));
// define JS class MifareClassicTag, JS_Constructor is the callback function
NAPI_CALL(env,
napi_define_class(env, "MifareClassicTag", NAPI_AUTO_LENGTH,
JS_Constructor<NapiMifareClassicTag, MifareClassicTag>, nullptr, sizeof(desc) / sizeof(desc[0]), desc,
&mifareClassicTagObject));
return exports;
}
napi_value RegisterMifareUltralightTagObject(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("readMultiplePages", NapiMifareUltralightTag::ReadMultiplePages),
DECLARE_NAPI_FUNCTION("writeSinglePages", NapiMifareUltralightTag::WriteSinglePages),
DECLARE_NAPI_FUNCTION("getType", NapiMifareUltralightTag::GetType),
DECLARE_NAPI_FUNCTION("reset", NapiNfcTagSession::Reset),
DECLARE_NAPI_FUNCTION("isTagConnected", NapiNfcTagSession::IsTagConnected),
DECLARE_NAPI_FUNCTION("getMaxSendLength", NapiNfcTagSession::GetMaxSendLength),
};
NAPI_CALL(env, InitMifareUltralightType(env, exports));
// define JS class MifareUltralightTag, JS_Constructor is the callback function
NAPI_CALL(env,
napi_define_class(env, "MifareUltralightTag", NAPI_AUTO_LENGTH,
JS_Constructor<NapiMifareUltralightTag, MifareUltralightTag>, nullptr, sizeof(desc) / sizeof(desc[0]),
desc, &mifareUltralightTagObject));
return exports;
}
napi_value RegisterNdefFormatableTagObject(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("format", NapiNdefFormatableTag::Format),
DECLARE_NAPI_FUNCTION("formatReadOnly", NapiNdefFormatableTag::FormatReadOnly),
DECLARE_NAPI_FUNCTION("reset", NapiNfcTagSession::Reset),
DECLARE_NAPI_FUNCTION("isTagConnected", NapiNfcTagSession::IsTagConnected),
DECLARE_NAPI_FUNCTION("getMaxSendLength", NapiNfcTagSession::GetMaxSendLength),
};
NAPI_CALL(env, InitMifareUltralightType(env, exports));
// define JS class NdefFormatableTag , JS_Constructor is the callback function
NAPI_CALL(env,
napi_define_class(env, "NdefFormatableTag ", NAPI_AUTO_LENGTH,
JS_Constructor<NapiNdefFormatableTag, NdefFormatableTag>, nullptr, sizeof(desc) / sizeof(desc[0]),
desc, &ndefFormatableTagObject));
return exports;
}
napi_value GetNfcATag(napi_env env, napi_callback_info info)
{
DebugLog("nfcTag GetNfcATag begin");
std::size_t argc = 1;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr));
napi_value result = nullptr;
// new instance of JS object NfcATag
NAPI_CALL(env, napi_new_instance(env, nfcATagObject, argc, argv, &result));
return result;
}
napi_value GetNfcBTag(napi_env env, napi_callback_info info)
{
DebugLog("nfcTag GetNfcBTag begin");
std::size_t argc = 1;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr));
napi_value result = nullptr;
// new instance of JS object NfcBTag,
NAPI_CALL(env, napi_new_instance(env, nfcBTagObject, argc, argv, &result));
return result;
}
napi_value GetNfcFTag(napi_env env, napi_callback_info info)
{
DebugLog("nfcFag GetNfcFTag begin");
std::size_t argc = 1;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr));
napi_value result = nullptr;
// new instance of JS object NfcFTag,
NAPI_CALL(env, napi_new_instance(env, nfcFTagObject, argc, argv, &result));
return result;
}
napi_value GetNfcVTag(napi_env env, napi_callback_info info)
{
DebugLog("nfcTag GetNfcVTag begin");
std::size_t argc = 1;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr));
napi_value result = nullptr;
// new instance of JS object NfcVTag
NAPI_CALL(env, napi_new_instance(env, nfcVTagObject, argc, argv, &result));
return result;
}
napi_value GetIsoDepTag(napi_env env, napi_callback_info info)
{
DebugLog("nfcTag GetIsoDepTag begin");
std::size_t argc = 1;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr));
napi_value result = nullptr;
// new instance of JS object IsoDepTag
NAPI_CALL(env, napi_new_instance(env, isoDepTagObject, argc, argv, &result));
return result;
}
napi_value GetNdefTag(napi_env env, napi_callback_info info)
{
DebugLog("nfcTag GetNdefTag begin");
std::size_t argc = 1;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr));
napi_value result = nullptr;
// new instance of JS object NdefTag
NAPI_CALL(env, napi_new_instance(env, ndefTagObject, argc, argv, &result));
return result;
}
napi_value GetMifareClassicTag(napi_env env, napi_callback_info info)
{
DebugLog("nfcTag GetMifareClassicTag begin");
std::size_t argc = 1;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr));
napi_value result = nullptr;
// new instance of JS object MifareClassicTag
NAPI_CALL(env, napi_new_instance(env, mifareClassicTagObject, argc, argv, &result));
return result;
}
napi_value GetMifareUltralightTag(napi_env env, napi_callback_info info)
{
DebugLog("nfcTag GetMifareUltralightTag begin");
std::size_t argc = 1;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr));
napi_value result = nullptr;
// new instance of JS object MifareUltralightTag
NAPI_CALL(env, napi_new_instance(env, mifareUltralightTagObject, argc, argv, &result));
return result;
}
napi_value GetNdefFormatableTag(napi_env env, napi_callback_info info)
{
DebugLog("nfcTag GetNdefFormatableTag begin");
std::size_t argc = 1;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr));
napi_value result = nullptr;
// new instance of JS object NdefFormatableTag
NAPI_CALL(env, napi_new_instance(env, ndefFormatableTagObject, argc, argv, &result));
return result;
}
static napi_value InitJs(napi_env env, napi_value exports)
{
DebugLog("Init, nfc_napi_tag");
// register NfcA tag object
RegisternfcATagObject(env, exports);
// register NfcBtag object
RegisternfcBTagObject(env, exports);
// register NfcFtag object
RegisternfcFTagObject(env, exports);
// register NfcVtag object
RegisternfcVTagObject(env, exports);
// register IsoDeptag object
RegisterIsoDepTagObject(env, exports);
// register NedfTag object
RegisterNdefTagObject(env, exports);
// register MifareClassictag object
RegisterMifareClassicTagObject(env, exports);
// register MifareUltralightTag object
RegisterMifareUltralightTagObject(env, exports);
// register NdefFormatableTag object
RegisterNdefFormatableTagObject(env, exports);
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("getNfcATag", GetNfcATag),
DECLARE_NAPI_FUNCTION("getNfcBTag", GetNfcBTag),
DECLARE_NAPI_FUNCTION("getNfcFTag", GetNfcFTag),
DECLARE_NAPI_FUNCTION("getNfcVTag", GetNfcVTag),
DECLARE_NAPI_FUNCTION("getIsoDepTag", GetIsoDepTag),
DECLARE_NAPI_FUNCTION("getNdefTag", GetNdefTag),
DECLARE_NAPI_FUNCTION("getMifareClassicTag", GetMifareClassicTag),
DECLARE_NAPI_FUNCTION("getMifareUltralightTag", GetMifareUltralightTag),
DECLARE_NAPI_FUNCTION("getNdefFormatableTag", GetNdefFormatableTag),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc));
return exports;
}
static napi_module nfcTagModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = InitJs,
.nm_modname = "nfc.tag",
.nm_priv = ((void *)0),
.reserved = {0},
};
extern "C" __attribute__((constructor)) void RegisterNfcTagModule(void)
{
napi_module_register(&nfcTagModule);
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,59 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_TAG_H_
#define NFC_NAPI_TAG_H_
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "nfc_napi_tag_sesstion.h"
#include "nfc_napi_taga.h"
#include "nfc_napi_tagb.h"
#include "nfc_napi_tagf.h"
#include "nfc_napi_tagv.h"
#include "nfc_napi_tag_isodep.h"
#include "nfc_napi_tag_mifare_classic.h"
#include "nfc_napi_tag_mifare_ul.h"
#include "nfc_napi_tag_ndef.h"
#include "nfc_napi_tag_ndef_formatable.h"
#include "nfc_napi_utils.h"
#include "taginfo.h"
namespace OHOS {
namespace NFC {
namespace KITS {
napi_value RegisternfcATagObject(napi_env env, napi_value exports);
napi_value RegisternfcBTagObject(napi_env env, napi_value exports);
napi_value RegisternfcFTagObject(napi_env env, napi_value exports);
napi_value RegisternfcVTagObject(napi_env env, napi_value exports);
napi_value RegisterIsoDepTagObject(napi_env env, napi_value exports);
napi_value RegisterNdefTagObject(napi_env env, napi_value exports);
napi_value RegisterMifareClassicTagObject(napi_env env, napi_value exports);
napi_value RegisterMifareUltralightTagObject(napi_env env, napi_value exports);
napi_value RegisterNdefFormatableTagObject(napi_env env, napi_value exports);
napi_value GetNfcATag(napi_env env, napi_callback_info info);
napi_value GetNfcBTag(napi_env env, napi_callback_info info);
napi_value GetNfcFTag(napi_env env, napi_callback_info info);
napi_value GetNfcVTag(napi_env env, napi_callback_info info);
napi_value GetIsoDepTag(napi_env env, napi_callback_info info);
napi_value GetNdefTag(napi_env env, napi_callback_info info);
napi_value GetMifareClassicTag(napi_env env, napi_callback_info info);
napi_value GetMifareUltralightTag(napi_env env, napi_callback_info info);
napi_value GetNdefFormatableTag(napi_env env, napi_callback_info info);
napi_value JS_Constructor(napi_env env, napi_callback_info cbinfo);
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif
@@ -1,161 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_tag_isodep.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
static const int32_t DEFAULT_REF_COUNT = 1;
napi_value NapiIsoDepTag::GetHistoricalBytes(napi_env env, napi_callback_info info)
{
DebugLog("GetIsoDepTag GetHistoricalBytes called");
napi_value thisVar = nullptr;
std::size_t argc = 0;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiIsoDepTag *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("getHistoricalBytes objInfo %{public}p", objectInfo);
// transfer
IsoDepTag *nfcIsoDepTagPtr = static_cast<IsoDepTag *>(static_cast<void *>(objectInfo->tagSession.get()));
if (nfcIsoDepTagPtr == nullptr) {
ErrorLog("GetHistoricalBytes find objectInfo failed!");
return nullptr;
} else {
napi_value ret = nullptr;
std::string historicalBytes = nfcIsoDepTagPtr->GetHistoricalBytes();
DebugLog("HistoricalBytes %{public}s", historicalBytes.c_str());
napi_create_string_utf8(env, historicalBytes.c_str(), NAPI_AUTO_LENGTH, &ret);
return ret;
}
}
napi_value NapiIsoDepTag::GetHiLayerResponse(napi_env env, napi_callback_info info)
{
DebugLog("GetIsoDepTag GetHiLayerResponse called");
napi_value thisVar = nullptr;
std::size_t argc = 0;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiIsoDepTag *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("getHiLayerResponse objInfo %{public}p", objectInfo);
// transfer
IsoDepTag *nfcIsoDepTagPtr = static_cast<IsoDepTag *>(static_cast<void *>(objectInfo->tagSession.get()));
if (nfcIsoDepTagPtr == nullptr) {
ErrorLog("GetHiLayerResponse find objectInfo failed!");
return nullptr;
} else {
napi_value ret = nullptr;
std::string hiLayerResponse = nfcIsoDepTagPtr->GetHiLayerResponse();
DebugLog("HiLayerResponse %{public}s", hiLayerResponse.c_str());
napi_create_string_utf8(env, hiLayerResponse.c_str(), NAPI_AUTO_LENGTH, &ret);
return ret;
}
}
static bool MatchIsExtendedApduSupportedParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
if (parameterCount > 1) {
return false;
}
if (parameterCount == 1) {
return MatchParameters(env, parameters, {napi_function});
}
return true;
}
static void NativeIsExtendedApduSupported(napi_env env, void *data)
{
DebugLog("NativeIsExtendedApduSupported called");
auto context = static_cast<CallBackContext<bool, NapiIsoDepTag> *>(data);
DebugLog("NativeIsExtendedApduSupported objInfo %{public}p", context->objectInfo);
IsoDepTag *nfcIsoDepTagPtr = static_cast<IsoDepTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcIsoDepTagPtr == nullptr) {
DebugLog("NativeIsExtendedApduSupported find objectInfo failed!");
context->value = true;
} else {
context->value = nfcIsoDepTagPtr->IsExtendedApduSupported();
}
context->resolved = true;
}
static void IsExtendedApduSupportedCallback(napi_env env, napi_status status, void *data)
{
DebugLog("IsExtendedApduSupportedCallback called");
auto context = static_cast<CallBackContext<bool, NapiIsoDepTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_status status = napi_get_boolean(env, context->value, &callbackValue);
if (status != napi_ok) {
ErrorLog("get boolean failed");
}
} else {
callbackValue = CreateErrorMessage(env, "IsExtendedApduSupported error by ipc");
}
} else {
callbackValue =
CreateErrorMessage(env, "IsExtendedApduSupported error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiIsoDepTag::IsExtendedApduSupported(napi_env env, napi_callback_info info)
{
DebugLog("GetIsoDepTag IsExtendedApduSupported called");
size_t paramsCount = 1;
napi_value params[1] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiIsoDepTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("IsExtendedApduSupported objInfo %{public}p", objectInfoCb);
NAPI_ASSERT(env, MatchIsExtendedApduSupportedParameters(env, params, paramsCount),
"IsExtendedApduSupported type mismatch");
auto context = std::make_unique<CallBackContext<bool, NapiIsoDepTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "error at SingleValueContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
if (paramsCount == 1) {
napi_create_reference(env, params[0], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result = HandleAsyncWork(
env, context, "IsExtendedApduSupported", NativeIsExtendedApduSupported, IsExtendedApduSupportedCallback);
return result;
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,36 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_TAG_ISODEP_H_
#define NFC_NAPI_TAG_ISODEP_H_
#include "isodep_tag.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "nfc_napi_tag_sesstion.h"
#include "nfc_napi_utils.h"
namespace OHOS {
namespace NFC {
namespace KITS {
struct NapiIsoDepTag : public NapiNfcTagSession {
static napi_value GetHistoricalBytes(napi_env env, napi_callback_info info);
static napi_value GetHiLayerResponse(napi_env env, napi_callback_info info);
static napi_value IsExtendedApduSupported(napi_env env, napi_callback_info info);
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif
@@ -1,895 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_tag_mifare_classic.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
static const int32_t DEFAULT_REF_COUNT = 1;
napi_value NapiMifareClassicTag::GetSectorCount(napi_env env, napi_callback_info info)
{
DebugLog("GetSectorCount called");
napi_value thisVar = nullptr;
std::size_t argc = 0;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiMifareClassicTag *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
// transfer
MifareClassicTag *nfcMifareClassicTagPtr =
static_cast<MifareClassicTag *>(static_cast<void *>(objectInfo->tagSession.get()));
if (nfcMifareClassicTagPtr == nullptr) {
ErrorLog("GetSectorCount find objectInfo failed!");
return nullptr;
} else {
int sectorCount = nfcMifareClassicTagPtr->GetSectorCount();
DebugLog("sectorCount %{public}d", sectorCount);
napi_value result = nullptr;
napi_create_int32(env, sectorCount, &result);
return result;
}
}
napi_value NapiMifareClassicTag::GetBlockCountInSector(napi_env env, napi_callback_info info)
{
DebugLog("GetBlockCountInSector called");
napi_value thisVar = nullptr;
size_t expectedArgsCount = ARGV_NUM_1;
size_t argc = expectedArgsCount;
napi_value argv[ARGV_NUM_1] = {0};
napi_value result = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
// check parameter number
if (argc != expectedArgsCount) {
ErrorLog("NapiMifareClassicTag::GetBlockCountInSector, Requires 1 argument.");
return result;
}
// check parameter data type
napi_valuetype valueType = napi_undefined;
if (valueType != napi_number) {
ErrorLog("NapiMifareClassicTag::GetBlockCountInSector, Invalid data type!");
return nullptr;
}
NapiMifareClassicTag *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
int32_t sectorIndex;
ParseInt32(env, sectorIndex, argv[ARGV_INDEX_0]);
// transfer
MifareClassicTag *nfcMifareClassicTagPtr =
static_cast<MifareClassicTag *>(static_cast<void *>(objectInfo->tagSession.get()));
if (nfcMifareClassicTagPtr == nullptr) {
ErrorLog("GetSectorCount find objectInfo failed!");
return nullptr;
}
int blockCountInSector = nfcMifareClassicTagPtr->GetBlockCountInSector(sectorIndex);
DebugLog("blockCountInSector %{public}d", blockCountInSector);
napi_create_int32(env, blockCountInSector, &result);
return result;
}
napi_value NapiMifareClassicTag::GetType(napi_env env, napi_callback_info info)
{
DebugLog("Mifare Classic GetType called");
napi_value thisVar = nullptr;
std::size_t argc = 0;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiMifareClassicTag *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
// transfer
MifareClassicTag *nfcMifareClassicTagPtr =
static_cast<MifareClassicTag *>(static_cast<void *>(objectInfo->tagSession.get()));
if (nfcMifareClassicTagPtr == nullptr) {
ErrorLog("GetType find objectInfo failed!");
return nullptr;
} else {
// MifareClassicTag::EmMifareTagType mifareType = nfcMifareClassicTagPtr->GetType();
MifareClassicTag::EmMifareTagType mifareType = MifareClassicTag::TYPE_UNKNOWN;
DebugLog("sectorCount %{public}d", mifareType);
napi_value result = nullptr;
napi_create_int32(env, mifareType, &result);
return result;
}
}
napi_value NapiMifareClassicTag::GetTagSize(napi_env env, napi_callback_info info)
{
DebugLog("GetTagSize called");
napi_value thisVar = nullptr;
std::size_t argc = 0;
napi_value argv[] = {nullptr};
napi_value result = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiMifareClassicTag *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
// transfer
MifareClassicTag *nfcMifareClassicTagPtr =
static_cast<MifareClassicTag *>(static_cast<void *>(objectInfo->tagSession.get()));
if (nfcMifareClassicTagPtr == nullptr) {
ErrorLog("GetSectorCount find objectInfo failed!");
return result;
}
int tagSize = nfcMifareClassicTagPtr->GetSize();
DebugLog("sectorCount %{public}d", tagSize);
napi_create_int32(env, tagSize, &result);
return result;
}
napi_value NapiMifareClassicTag::IsEmulatedTag(napi_env env, napi_callback_info info)
{
DebugLog("IsEmulatedTag called");
napi_value thisVar = nullptr;
std::size_t argc = 0;
napi_value argv[] = {nullptr};
napi_value result = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiMifareClassicTag *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
// transfer
MifareClassicTag *nfcMifareClassicTagPtr =
static_cast<MifareClassicTag *>(static_cast<void *>(objectInfo->tagSession.get()));
if (nfcMifareClassicTagPtr == nullptr) {
ErrorLog("GetSectorCount find objectInfo failed!");
return result;
}
bool isEmulated = nfcMifareClassicTagPtr->IsEmulated();
DebugLog("sectorCount %{public}d", isEmulated);
napi_get_boolean(env, isEmulated, &result);
return result;
}
napi_value NapiMifareClassicTag::GetBlockIndex(napi_env env, napi_callback_info info)
{
DebugLog("GetBlockCountInSector called");
napi_value thisVar = nullptr;
size_t expectedArgsCount = ARGV_NUM_1;
size_t argc = expectedArgsCount;
napi_value argv[ARGV_NUM_1] = {0};
napi_value result = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
// check parameter number
if (argc != expectedArgsCount) {
ErrorLog("NapiMifareClassicTag::GetBlockIndex, Requires 1 argument.");
return result;
}
// check parameter data type
napi_valuetype valueType = napi_undefined;
if (valueType != napi_number) {
ErrorLog("NapiMifareClassicTag::GetBlockIndex, Invalid data type!");
return nullptr;
}
NapiMifareClassicTag *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
int32_t sectorIndex;
ParseInt32(env, sectorIndex, argv[ARGV_INDEX_0]);
// transfer
MifareClassicTag *nfcMifareClassicTagPtr =
static_cast<MifareClassicTag *>(static_cast<void *>(objectInfo->tagSession.get()));
if (nfcMifareClassicTagPtr == nullptr) {
ErrorLog("GetSectorCount find objectInfo failed!");
return nullptr;
}
int blockIndex = nfcMifareClassicTagPtr->GetBlockIndexFromSector(sectorIndex);
DebugLog("BlockIndex %{public}d", blockIndex);
napi_create_int32(env, blockIndex, &result);
return result;
}
napi_value NapiMifareClassicTag::GetSectorIndex(napi_env env, napi_callback_info info)
{
DebugLog("GetSectorIndex called");
napi_value thisVar = nullptr;
size_t expectedArgsCount = ARGV_NUM_1;
size_t argc = expectedArgsCount;
napi_value argv[ARGV_NUM_1] = {0};
napi_value result = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
// check parameter number
if (argc != expectedArgsCount) {
ErrorLog("NapiMifareClassicTag::GetSectorIndex, Requires 1 argument.");
return result;
}
// check parameter data type
napi_valuetype valueType = napi_undefined;
if (valueType != napi_number) {
ErrorLog("NapiMifareClassicTag::GetSectorIndex, Invalid data type!");
return nullptr;
}
NapiMifareClassicTag *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
int32_t blockIndex;
ParseInt32(env, blockIndex, argv[ARGV_INDEX_0]);
// transfer
MifareClassicTag *nfcMifareClassicTagPtr =
static_cast<MifareClassicTag *>(static_cast<void *>(objectInfo->tagSession.get()));
if (nfcMifareClassicTagPtr == nullptr) {
ErrorLog("GetSectorCount find objectInfo failed!");
return nullptr;
}
// int sectorIndex = nfcMifareClassicTagPtr->GetBlockIndexFromSector(blockIndex); // no cpp func
int sectorIndex = 4;
DebugLog("sectorIndex%{public}d", blockIndex);
napi_create_int32(env, sectorIndex, &result);
return result;
}
static bool MatchAuthenticateSectorParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
bool typeMatch = false;
switch (parameterCount) {
case ARGV_NUM_3: {
typeMatch = MatchParameters(env, parameters, {napi_number, napi_object, napi_boolean});
break;
}
case ARGV_NUM_4:
typeMatch = MatchParameters(env, parameters, {napi_number, napi_object, napi_boolean, napi_function});
break;
default: {
return false;
}
}
if (typeMatch) {
bool isArray = false;
napi_is_array(env, parameters[1], &isArray);
return isArray;
}
return false;
}
static void NativeAuthenticateSector(napi_env env, void *data)
{
DebugLog("NativeAuthenticateSector called");
auto context = static_cast<MifareClassicContext<bool, NapiMifareClassicTag> *>(data);
DebugLog("NativeAuthenticateSector objInfo %{public}p", context->objectInfo);
MifareClassicTag *nfcMifareClassicTagPtr =
static_cast<MifareClassicTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcMifareClassicTagPtr == nullptr) {
ErrorLog("NativeAuthenticateSector find objectInfo failed!");
context->value = true;
} else {
context->value = nfcMifareClassicTagPtr->AuthenticateSector(context->sectorIndex, "aaa", context->bIsKeyA);
}
context->resolved = true;
}
static void AuthenticateSectorCallback(napi_env env, napi_status status, void *data)
{
DebugLog("AuthenticateSectorCallback called");
auto context = static_cast<MifareClassicContext<bool, NapiMifareClassicTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_status status = napi_get_boolean(env, context->value, &callbackValue);
if (status != napi_ok) {
ErrorLog("get boolean failed");
}
} else {
callbackValue = CreateErrorMessage(env, "AuthenticateSector error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "AuthenticateSector error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiMifareClassicTag::AuthenticateSector(napi_env env, napi_callback_info info)
{
DebugLog("AuthenticateSector called");
size_t paramsCount = ARGV_NUM_4;
napi_value params[ARGV_NUM_4] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiMifareClassicTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
NAPI_ASSERT(env, MatchAuthenticateSectorParameters(env, params, paramsCount), "AuthenticateSector type mismatch");
auto context = std::make_unique<MifareClassicContext<bool, NapiMifareClassicTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "MifareClassicContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
// parse the params
napi_get_value_int32(env, params[ARGV_INDEX_0], &context->sectorIndex);
DebugLog("AuthenticateSector sectorIndex = %{public}d", context->sectorIndex);
napi_get_value_bool(env, params[ARGV_INDEX_2], &context->bIsKeyA);
DebugLog("AuthenticateSector bIsKeyA = %{public}d", context->bIsKeyA);
if (paramsCount == ARGV_NUM_4) {
napi_create_reference(env, params[ARGV_INDEX_3], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result =
HandleAsyncWork(env, context, "AuthenticateSector", NativeAuthenticateSector, AuthenticateSectorCallback);
return result;
}
static bool MatchReadSingleBlockParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
bool typeMatch = false;
switch (parameterCount) {
case ARGV_NUM_1: {
typeMatch = MatchParameters(env, parameters, {napi_number});
break;
}
case ARGV_NUM_2:
typeMatch = MatchParameters(env, parameters, {napi_number, napi_function});
break;
default: {
return false;
}
}
return typeMatch;
}
static void NativeReadSingleBlock(napi_env env, void *data)
{
DebugLog("NativeReadSingleBlock called");
auto context = static_cast<MifareClassicContext<std::string, NapiMifareClassicTag> *>(data);
MifareClassicTag *nfcMifareClassicTagPtr =
static_cast<MifareClassicTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcMifareClassicTagPtr == nullptr) {
ErrorLog("NativeReadSingleBlock find objectInfo failed!");
context->value = "";
} else {
context->value = nfcMifareClassicTagPtr->ReadSingleBlock(context->blockIndex);
DebugLog("ReadSingleBlock context value = %{public}s", context->value.c_str());
}
context->resolved = true;
}
static void ReadSingleBlockCallback(napi_env env, napi_status status, void *data)
{
auto context = static_cast<MifareClassicContext<std::string, NapiMifareClassicTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_create_string_utf8(env, context->value.c_str(), context->value.size(), &callbackValue);
} else {
callbackValue = CreateErrorMessage(env, "ReadSingleBlock error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "ReadSingleBlock error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiMifareClassicTag::ReadSingleBlock(napi_env env, napi_callback_info info)
{
size_t paramsCount = ARGV_NUM_2;
napi_value params[ARGV_NUM_2] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiMifareClassicTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
NAPI_ASSERT(env, MatchReadSingleBlockParameters(env, params, paramsCount), "ReadSingleBlock type mismatch");
auto context = std::make_unique<MifareClassicContext<std::string, NapiMifareClassicTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "MifareClassicContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
// parse the params
napi_get_value_int32(env, params[ARGV_INDEX_0], &context->blockIndex);
if (paramsCount == ARGV_NUM_2) {
napi_create_reference(env, params[ARGV_INDEX_1], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result =
HandleAsyncWork(env, context, "ReadSingleBlock", NativeReadSingleBlock, ReadSingleBlockCallback);
return result;
}
static bool MatchWriteSingleBlockParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
bool typeMatch = false;
switch (parameterCount) {
case ARGV_NUM_2: {
typeMatch = MatchParameters(env, parameters, {napi_number, napi_string});
break;
}
case ARGV_NUM_3:
typeMatch = MatchParameters(env, parameters, {napi_number, napi_string, napi_function});
break;
default: {
return false;
}
}
return typeMatch;
}
static void NativeWriteSingleBlock(napi_env env, void *data)
{
auto context = static_cast<MifareClassicContext<int, NapiMifareClassicTag> *>(data);
DebugLog("NativeWriteSingleBlock objInfo %{public}p", context->objectInfo);
MifareClassicTag *nfcMifareClassicTagPtr =
static_cast<MifareClassicTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcMifareClassicTagPtr == nullptr) {
ErrorLog("NativeWriteSingleBlock find objectInfo failed!");
} else {
context->value = nfcMifareClassicTagPtr->WriteSingleBlock(context->blockIndex, context->data);
}
context->resolved = true;
}
static void WriteSingleBlockCallback(napi_env env, napi_status status, void *data)
{
auto context = static_cast<MifareClassicContext<int, NapiMifareClassicTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_create_int32(env, context->value, &callbackValue);
} else {
callbackValue = CreateErrorMessage(env, "WriteSingleBlock error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "WriteSingleBlock error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiMifareClassicTag::WriteSingleBlock(napi_env env, napi_callback_info info)
{
size_t paramsCount = ARGV_NUM_3;
napi_value params[ARGV_NUM_3] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiMifareClassicTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
NAPI_ASSERT(env, MatchWriteSingleBlockParameters(env, params, paramsCount), "WriteSingleBlock type mismatch");
auto context = std::make_unique<MifareClassicContext<int, NapiMifareClassicTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "MifareClassicContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
// parse the params
napi_get_value_int32(env, params[ARGV_INDEX_0], &context->blockIndex);
DebugLog("WriteSingleBlock blockIndex = %{public}d", context->blockIndex);
context->data = GetStringFromValue(env, params[ARGV_INDEX_1]);
DebugLog("WriteSingleBlock data = %{public}s", context->data.c_str());
if (paramsCount == ARGV_NUM_3) {
napi_create_reference(env, params[ARGV_INDEX_2], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result =
HandleAsyncWork(env, context, "WriteSingleBlock", NativeWriteSingleBlock, WriteSingleBlockCallback);
return result;
}
static bool MatchIncrementBlockParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
bool typeMatch = false;
switch (parameterCount) {
case ARGV_NUM_2: {
typeMatch = MatchParameters(env, parameters, {napi_number, napi_number});
break;
}
case ARGV_NUM_3:
typeMatch = MatchParameters(env, parameters, {napi_number, napi_number, napi_function});
break;
default: {
return false;
}
}
return typeMatch;
}
static void NativeIncrementBlock(napi_env env, void *data)
{
auto context = static_cast<MifareClassicContext<int, NapiMifareClassicTag> *>(data);
DebugLog("NativeIncrementBlock objInfo %{public}p", context->objectInfo);
MifareClassicTag *nfcMifareClassicTagPtr =
static_cast<MifareClassicTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcMifareClassicTagPtr == nullptr) {
ErrorLog("NativeIncrementBlock find objectInfo failed!");
} else {
context->value = nfcMifareClassicTagPtr->IncrementBlock(context->blockIndex, context->incrementValue);
DebugLog("IncrementBlock context value = %{public}d", context->value);
}
context->resolved = true;
}
static void IncrementBlockCallback(napi_env env, napi_status status, void *data)
{
DebugLog("IncrementBlockCallback called");
auto context = static_cast<MifareClassicContext<int, NapiMifareClassicTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_create_int32(env, context->value, &callbackValue);
} else {
callbackValue = CreateErrorMessage(env, "IncrementBlock error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "IncrementBlock error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiMifareClassicTag::IncrementBlock(napi_env env, napi_callback_info info)
{
size_t paramsCount = ARGV_NUM_3;
napi_value params[ARGV_NUM_3] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiMifareClassicTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
NAPI_ASSERT(env, MatchIncrementBlockParameters(env, params, paramsCount), "WriteSingleBlock type mismatch");
auto context = std::make_unique<MifareClassicContext<int, NapiMifareClassicTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "MifareClassicContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
// parse the params
napi_get_value_int32(env, params[ARGV_INDEX_0], &context->blockIndex);
DebugLog("IncrementBlock blockIndex = %{public}d", context->blockIndex);
napi_get_value_int32(env, params[ARGV_INDEX_1], &context->incrementValue);
DebugLog("IncrementBlock data = %{public}d", context->incrementValue);
if (paramsCount == ARGV_NUM_3) {
napi_create_reference(env, params[ARGV_INDEX_2], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result = HandleAsyncWork(env, context, "IncrementBlock", NativeIncrementBlock, IncrementBlockCallback);
return result;
}
static bool MatchDecrementBlockParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
bool typeMatch = false;
switch (parameterCount) {
case ARGV_NUM_2: {
typeMatch = MatchParameters(env, parameters, {napi_number, napi_number});
break;
}
case ARGV_NUM_3:
typeMatch = MatchParameters(env, parameters, {napi_number, napi_number, napi_function});
break;
default: {
return false;
}
}
return typeMatch;
}
static void NativeDecrementBlock(napi_env env, void *data)
{
auto context = static_cast<MifareClassicContext<int, NapiMifareClassicTag> *>(data);
DebugLog("NativeDecrementBlock objInfo %{public}p", context->objectInfo);
MifareClassicTag *nfcMifareClassicTagPtr =
static_cast<MifareClassicTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcMifareClassicTagPtr == nullptr) {
ErrorLog("NativeDecrementBlock find objectInfo failed!");
} else {
context->value = nfcMifareClassicTagPtr->DecrementBlock(context->blockIndex, context->decrementValue);
DebugLog("DecrementBlock context value = %{public}d", context->value);
}
context->resolved = true;
}
static void DecrementBlockCallback(napi_env env, napi_status status, void *data)
{
auto context = static_cast<MifareClassicContext<int, NapiMifareClassicTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_create_int32(env, context->value, &callbackValue);
} else {
callbackValue = CreateErrorMessage(env, "DecrementBlock error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "DecrementBlock error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiMifareClassicTag::DecrementBlock(napi_env env, napi_callback_info info)
{
size_t paramsCount = ARGV_NUM_3;
napi_value params[ARGV_NUM_3] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiMifareClassicTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
NAPI_ASSERT(env, MatchDecrementBlockParameters(env, params, paramsCount), "DecrementBlock type mismatch");
auto context = std::make_unique<MifareClassicContext<int, NapiMifareClassicTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "MifareClassicContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
// parse the params
napi_get_value_int32(env, params[ARGV_INDEX_0], &context->blockIndex);
DebugLog("DecrementBlock blockIndex = %{public}d", context->blockIndex);
napi_get_value_int32(env, params[ARGV_INDEX_1], &context->decrementValue);
DebugLog("DecrementBlock data = %{public}d", context->decrementValue);
if (paramsCount == ARGV_NUM_3) {
napi_create_reference(env, params[ARGV_INDEX_2], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result = HandleAsyncWork(env, context, "DecrementBlock", NativeDecrementBlock, DecrementBlockCallback);
return result;
}
static bool MatchTransferToBlockParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
bool typeMatch = false;
switch (parameterCount) {
case ARGV_NUM_1: {
typeMatch = MatchParameters(env, parameters, {napi_number});
break;
}
case ARGV_NUM_2:
typeMatch = MatchParameters(env, parameters, {napi_number, napi_function});
break;
default: {
return false;
}
}
return typeMatch;
}
static void NativeTransferToBlock(napi_env env, void *data)
{
auto context = static_cast<MifareClassicContext<int, NapiMifareClassicTag> *>(data);
DebugLog("NativeTransferToBlock objInfo %{public}p", context->objectInfo);
MifareClassicTag *nfcMifareClassicTagPtr =
static_cast<MifareClassicTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcMifareClassicTagPtr == nullptr) {
ErrorLog("NativeTransferToBlock find objectInfo failed!");
} else {
context->value = nfcMifareClassicTagPtr->TransferToBlock(context->blockIndex);
DebugLog("TransferToBlock context value = %{public}d", context->value);
}
context->resolved = true;
}
static void TransferToBlockCallback(napi_env env, napi_status status, void *data)
{
auto context = static_cast<MifareClassicContext<int, NapiMifareClassicTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_create_int32(env, context->value, &callbackValue);
} else {
callbackValue = CreateErrorMessage(env, "TransferToBlock error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "TransferToBlock error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiMifareClassicTag::TransferToBlock(napi_env env, napi_callback_info info)
{
size_t paramsCount = ARGV_NUM_2;
napi_value params[ARGV_NUM_2] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiMifareClassicTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
NAPI_ASSERT(env, MatchTransferToBlockParameters(env, params, paramsCount), "TransferToBlock type mismatch");
auto context = std::make_unique<MifareClassicContext<int, NapiMifareClassicTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "MifareClassicContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
// parse the params
napi_get_value_int32(env, params[ARGV_INDEX_0], &context->blockIndex);
DebugLog("TransferToBlock blockIndex = %{public}d", context->blockIndex);
if (paramsCount == ARGV_NUM_2) {
napi_create_reference(env, params[ARGV_INDEX_1], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result =
HandleAsyncWork(env, context, "TransferToBlock", NativeTransferToBlock, TransferToBlockCallback);
return result;
}
static bool MatchRestoreFromBlockParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
bool typeMatch = false;
switch (parameterCount) {
case ARGV_NUM_1: {
typeMatch = MatchParameters(env, parameters, {napi_number});
break;
}
case ARGV_NUM_2:
typeMatch = MatchParameters(env, parameters, {napi_number, napi_function});
break;
default: {
return false;
}
}
return typeMatch;
}
static void NativeRestoreFromBlock(napi_env env, void *data)
{
auto context = static_cast<MifareClassicContext<int, NapiMifareClassicTag> *>(data);
DebugLog("NativeRestoreFromBlock objInfo %{public}p", context->objectInfo);
MifareClassicTag *nfcMifareClassicTagPtr =
static_cast<MifareClassicTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcMifareClassicTagPtr == nullptr) {
ErrorLog("NativeRestoreFromBlock find objectInfo failed!");
} else {
context->value = nfcMifareClassicTagPtr->RestoreFromBlock(context->blockIndex);
DebugLog("RestoreFromBlock context value = %{public}d", context->value);
}
context->resolved = true;
}
static void RestoreFromBlockCallback(napi_env env, napi_status status, void *data)
{
auto context = static_cast<MifareClassicContext<int, NapiMifareClassicTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_create_int32(env, context->value, &callbackValue);
} else {
callbackValue = CreateErrorMessage(env, "RestoreFromBlock error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "RestoreFromBlock error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiMifareClassicTag::RestoreFromBlock(napi_env env, napi_callback_info info)
{
size_t paramsCount = ARGV_NUM_2;
napi_value params[ARGV_NUM_2] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiMifareClassicTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
NAPI_ASSERT(env, MatchRestoreFromBlockParameters(env, params, paramsCount), "RestoreFromBlock type mismatch");
auto context = std::make_unique<MifareClassicContext<int, NapiMifareClassicTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "MifareClassicContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
// parse the params
napi_get_value_int32(env, params[ARGV_INDEX_0], &context->blockIndex);
DebugLog("RestoreFromBlock blockIndex = %{public}d", context->blockIndex);
if (paramsCount == ARGV_NUM_2) {
napi_create_reference(env, params[ARGV_INDEX_1], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result =
HandleAsyncWork(env, context, "RestoreFromBlock", NativeRestoreFromBlock, RestoreFromBlockCallback);
return result;
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,61 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_TAG_MIFARE_CLASSIC_H_
#define NFC_NAPI_TAG_MIFARE_CLASSIC_H_
#include <locale>
#include "mifare_classic_tag.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "nfc_napi_tag_sesstion.h"
#include "nfc_napi_utils.h"
namespace OHOS {
namespace NFC {
namespace KITS {
struct NapiMifareClassicTag : public NapiNfcTagSession {
static napi_value AuthenticateSector(napi_env env, napi_callback_info info);
static napi_value ReadSingleBlock(napi_env env, napi_callback_info info);
static napi_value WriteSingleBlock(napi_env env, napi_callback_info info);
static napi_value IncrementBlock(napi_env env, napi_callback_info info);
static napi_value DecrementBlock(napi_env env, napi_callback_info info);
static napi_value TransferToBlock(napi_env env, napi_callback_info info);
static napi_value RestoreFromBlock(napi_env env, napi_callback_info info);
static napi_value GetSectorCount(napi_env env, napi_callback_info info);
static napi_value GetBlockCountInSector(napi_env env, napi_callback_info info);
static napi_value GetType(napi_env env, napi_callback_info info);
static napi_value GetTagSize(napi_env env, napi_callback_info info);
static napi_value IsEmulatedTag(napi_env env, napi_callback_info info);
static napi_value GetBlockIndex(napi_env env, napi_callback_info info);
static napi_value GetSectorIndex(napi_env env, napi_callback_info info);
};
template<typename T, typename D>
struct MifareClassicContext : BaseContext {
T value;
D *objectInfo;
int sectorIndex;
std::string key;
bool bIsKeyA;
int blockIndex;
std::string data;
int incrementValue;
int decrementValue;
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif
@@ -1,237 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_tag_mifare_ul.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
static const int32_t DEFAULT_REF_COUNT = 1;
static bool MatchReadMultiplePagesParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
bool typeMatch = false;
switch (parameterCount) {
case ARGV_NUM_1: {
typeMatch = MatchParameters(env, parameters, {napi_number});
break;
}
case ARGV_NUM_2:
typeMatch = MatchParameters(env, parameters, {napi_number, napi_function});
break;
default: {
return false;
}
}
return typeMatch;
}
static void NativeReadMultiplePages(napi_env env, void *data)
{
DebugLog("NativeReadMultiplePages called");
auto context = static_cast<MifareUltralightContext<std::string, NapiMifareUltralightTag> *>(data);
DebugLog("NativeReadMultiplePages objInfo %{public}p", context->objectInfo);
MifareUltralightTag *nfcMifareUlTagPtr =
static_cast<MifareUltralightTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcMifareUlTagPtr == nullptr) {
ErrorLog("NativeReadMultiplePages find objectInfo failed!");
} else {
context->value = nfcMifareUlTagPtr->ReadMultiplePages(context->pageIndex);
DebugLog("ReadMultiplePages context value = %{public}d", context->pageIndex);
}
context->resolved = true;
}
static void ReadMultiplePagesCallback(napi_env env, napi_status status, void *data)
{
DebugLog("ReadMultiplePagesCallback called");
auto context = static_cast<MifareUltralightContext<std::string, NapiMifareUltralightTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_create_string_utf8(env, context->value.c_str(), context->value.size(), &callbackValue);
} else {
callbackValue = CreateErrorMessage(env, "ReadMultiplePages error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "ReadMultiplePages error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiMifareUltralightTag::ReadMultiplePages(napi_env env, napi_callback_info info)
{
DebugLog("ReadMultiplePages called");
size_t paramsCount = ARGV_NUM_2;
napi_value params[ARGV_NUM_2] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiMifareUltralightTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("ReadMultiplePages objInfo %{public}p", objectInfoCb);
NAPI_ASSERT(env, MatchReadMultiplePagesParameters(env, params, paramsCount), "ReadMultiplePages type mismatch");
auto context = std::make_unique<MifareUltralightContext<std::string, NapiMifareUltralightTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "MifareUltralightContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
// parse the params
napi_get_value_int32(env, params[ARGV_INDEX_0], &context->pageIndex);
DebugLog("ReadMultiplePages sectorIndex = %{public}d", context->pageIndex);
if (paramsCount == ARGV_NUM_2) {
napi_create_reference(env, params[1], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result =
HandleAsyncWork(env, context, "ReadMultiplePages", NativeReadMultiplePages, ReadMultiplePagesCallback);
return result;
}
static bool MatchWriteSinglePagesParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
bool typeMatch = false;
switch (parameterCount) {
case ARGV_NUM_2: {
typeMatch = MatchParameters(env, parameters, {napi_number, napi_string});
break;
}
case ARGV_NUM_3:
typeMatch = MatchParameters(env, parameters, {napi_number, napi_string, napi_function});
break;
default: {
return false;
}
}
return typeMatch;
}
static void NativeWriteSinglePages(napi_env env, void *data)
{
DebugLog("NativeWriteSinglePages called");
auto context = static_cast<MifareUltralightContext<int, NapiMifareUltralightTag> *>(data);
DebugLog("NativeWriteSinglePages objInfo %{public}p", context->objectInfo);
MifareUltralightTag *nfcMifareUlTagPtr =
static_cast<MifareUltralightTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcMifareUlTagPtr == nullptr) {
DebugLog("NativeReadMultiplePages find objectInfo failed!");
} else {
context->value = nfcMifareUlTagPtr->WriteSinglePages(context->pageIndex, context->data);
DebugLog("WriteSinglePages context value = %{public}d", context->value);
}
context->resolved = true;
}
static void WriteSinglePagesCallback(napi_env env, napi_status status, void *data)
{
DebugLog("WriteSinglePagesCallback called");
auto context = static_cast<MifareUltralightContext<int, NapiMifareUltralightTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_create_int32(env, context->value, &callbackValue);
} else {
callbackValue = CreateErrorMessage(env, "WriteSinglePages error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "WriteSinglePages error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiMifareUltralightTag::WriteSinglePages(napi_env env, napi_callback_info info)
{
DebugLog("WriteSinglePages called");
size_t paramsCount = ARGV_NUM_3;
napi_value params[ARGV_NUM_3] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiMifareUltralightTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("WriteSinglePages objInfo %{public}p", objectInfoCb);
NAPI_ASSERT(env, MatchWriteSinglePagesParameters(env, params, paramsCount), "WriteSinglePages type mismatch");
auto context = std::make_unique<MifareUltralightContext<int, NapiMifareUltralightTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "MifareUltralightContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
// parse the params
napi_get_value_int32(env, params[ARGV_INDEX_0], &context->pageIndex);
DebugLog("WriteSinglePages blockIndex = %{public}d", context->pageIndex);
context->data = GetStringFromValue(env, params[ARGV_INDEX_1]);
DebugLog("WriteSinglePages data = %{public}s", context->data.c_str());
if (paramsCount == ARGV_NUM_3) {
napi_create_reference(env, params[ARGV_INDEX_2], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result =
HandleAsyncWork(env, context, "WriteSinglePages", NativeWriteSinglePages, WriteSinglePagesCallback);
return result;
}
napi_value NapiMifareUltralightTag::GetType(napi_env env, napi_callback_info info)
{
DebugLog("MifareUl GetType called");
napi_value thisVar = nullptr;
std::size_t argc = 0;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiMifareUltralightTag *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("getType objInfo %{public}p", objectInfo);
// transfer
MifareUltralightTag *nfcMifareUlTagPtr =
static_cast<MifareUltralightTag *>(static_cast<void *>(objectInfo->tagSession.get()));
if (nfcMifareUlTagPtr == nullptr) {
ErrorLog("GetType find objectInfo failed!");
return nullptr;
} else {
MifareUltralightTag::EmMifareUltralightType mifareUlType = nfcMifareUlTagPtr->GetType();
DebugLog("sectorCount %{public}d", mifareUlType);
napi_value result = nullptr;
napi_create_int32(env, mifareUlType, &result);
return result;
}
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,45 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_TAG_MIFARE_UL_H_
#define NFC_NAPI_TAG_MIFARE_UL_H_
#include <locale>
#include "mifare_ultralight_tag.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "nfc_napi_tag_sesstion.h"
#include "nfc_napi_utils.h"
namespace OHOS {
namespace NFC {
namespace KITS {
struct NapiMifareUltralightTag : public NapiNfcTagSession {
static napi_value ReadMultiplePages(napi_env env, napi_callback_info info);
static napi_value WriteSinglePages(napi_env env, napi_callback_info info);
static napi_value GetType(napi_env env, napi_callback_info info);
};
template<typename T, typename D>
struct MifareUltralightContext : BaseContext {
T value;
D *objectInfo;
int pageIndex;
std::string data;
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif
@@ -1,692 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_tag_ndef.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
static const int32_t DEFAULT_REF_COUNT = 1;
napi_value ndefMessageObject;
std::vector<std::shared_ptr<NdefRecord>> ParseNdefRecords(const napi_env &env, napi_value &args)
{
DebugLog("ParseNdefRecords called");
uint32_t length = 0;
napi_get_array_length(env, args, &length);
std::vector<std::shared_ptr<NdefRecord>> params;
std::shared_ptr<NdefRecord> param = std::make_shared<NdefRecord>();
for (size_t i = 0; i < length; i++) {
napi_value ndefRecord;
napi_valuetype valueType = napi_undefined;
napi_value result = nullptr;
napi_get_element(env, args, i, &ndefRecord);
napi_typeof(env, ndefRecord, &valueType);
if (valueType != napi_object) {
ErrorLog("Wrong ndefRecord argument type. Object expected.");
return params;
}
napi_get_named_property(env, ndefRecord, "tnf", &result);
napi_typeof(env, result, &valueType);
if (valueType != napi_number) {
ErrorLog("Wrong tnf argument type. Number expected.");
return params;
}
napi_get_value_uint32(env, result, reinterpret_cast<uint32_t *>(&param->tnf_));
napi_get_named_property(env, ndefRecord, "rtdType", &result);
napi_typeof(env, result, &valueType);
if (valueType != napi_string) {
ErrorLog("Wrong rtdType argument type. String expected.");
return params;
}
ParseString(env, param->tagRtdType_, result);
napi_get_named_property(env, ndefRecord, "id", &result);
napi_typeof(env, result, &valueType);
if (valueType != napi_string) {
ErrorLog("Wrong id argument type. String expected.");
return params;
}
ParseString(env, param->id_, result);
napi_get_named_property(env, ndefRecord, "payload", &result);
napi_typeof(env, result, &valueType);
if (valueType != napi_string) {
ErrorLog("Wrong payload argument type. String expected.");
return params;
}
ParseString(env, param->payload_, result);
params.push_back(param);
}
return params;
}
napi_value JS_Constructor(napi_env env, napi_callback_info cbinfo)
{
DebugLog("ndef JS_Constructor in");
std::shared_ptr<NdefMessage> ndefMessage;
// nfcTag is defined as a native instance that will be wrapped in the JS object
NapiNdefMessage *napiNdefMessage = new NapiNdefMessage();
size_t argc = 1;
napi_value argv[] = {nullptr};
napi_value thisVar = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, nullptr));
// check parameter number
if (argc != ARGV_NUM_1) {
ErrorLog("Invalid number of arguments");
return nullptr;
}
napi_valuetype valueType = napi_undefined;
NAPI_CALL(env, napi_typeof(env, argv[ARGV_NUM_0], &valueType));
// check parameter data type
bool isArray = false;
napi_is_array(env, argv[ARGV_INDEX_0], &isArray);
// parse parameter from JS
if (valueType == napi_string) {
std::string data = GetStringFromValue(env, argv[ARGV_INDEX_0]);
DebugLog("ndfe message parse data = %{public}s", data.c_str());
napiNdefMessage->ndefMessage = NdefMessage::GetNdefMessage(data);
} else if (isArray) {
std::vector<std::shared_ptr<NdefRecord>> ndefRecords ;
ndefRecords = ParseNdefRecords(env, argv[ARGV_INDEX_0]);
DebugLog("NdefRecords Array parsed.");
napiNdefMessage->ndefMessage = NdefMessage::GetNdefMessage(ndefRecords);
} else {
ErrorLog("invalid data type!");
return nullptr;
}
// wrap data into thisVar
napi_status status = napi_wrap(
env, thisVar, napiNdefMessage,
[](napi_env env, void *data, void *hint) {
if (data) {
NdefMessage *nfcTag = (NdefMessage *)data;
delete nfcTag;
}
},
nullptr, nullptr);
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
return thisVar;
}
napi_value NapiNdefTag::RegisterNdefMessageObject(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("getNdefRecords", NapiNdefMessage::GetNdefRecords),
DECLARE_NAPI_FUNCTION("makeUriRecord", NapiNdefMessage::MakeUriRecord),
DECLARE_NAPI_FUNCTION("makeTextRecord", NapiNdefMessage::MakeTextRecord),
DECLARE_NAPI_FUNCTION("makeMimeRecord", NapiNdefMessage::MakeMimeRecord),
DECLARE_NAPI_FUNCTION("makeExternalRecord", NapiNdefMessage::MakeExternalRecord),
DECLARE_NAPI_FUNCTION("messageToString", NapiNdefMessage::MessageToString),
};
// define JS class NdefMessage, JS_Constructor is the callback function
NAPI_CALL(env,
napi_define_class(env, "NdefMessage", NAPI_AUTO_LENGTH, JS_Constructor, nullptr,
sizeof(desc) / sizeof(desc[0]), desc, &ndefMessageObject));
return exports;
}
napi_value NapiNdefTag::CreateNdefMessage(napi_env env, napi_callback_info info)
{
DebugLog("Ndef CreateNdefMessage begin");
std::size_t argc = ARGV_NUM_1;
napi_value argv[ARGV_NUM_1] = {0};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr));
napi_value result = nullptr;
// new instance of JS object ndefMessageObject
NAPI_CALL(env, napi_new_instance(env, ndefMessageObject, argc, argv, &result));
return result;
}
napi_value NapiNdefTag::GetNdefTagType(napi_env env, napi_callback_info info)
{
DebugLog("Ndef GetType called");
napi_value thisVar = nullptr;
std::size_t argc = 0;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiNdefTag *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("getType objInfo %{public}p", objectInfo);
// transfer
NdefTag *nfcNdefTagPtr = static_cast<NdefTag *>(static_cast<void *>(objectInfo->tagSession.get()));
if (nfcNdefTagPtr == nullptr) {
ErrorLog("GetType find objectInfo failed!");
return nullptr;
} else {
NdefTag::EmNfcForumType nfcForumType = nfcNdefTagPtr->GetNdefTagType();
DebugLog("nfcForumType %{public}d", nfcForumType);
napi_value result = nullptr;
napi_create_int32(env, nfcForumType, &result);
return result;
}
}
napi_value NapiNdefTag::GetNdefMessage(napi_env env, napi_callback_info info)
{
DebugLog("Ndef GetNdefMessage called");
napi_value thisVar = nullptr;
napi_value ndefMessage = nullptr;
NapiNdefMessage *ndpiNdefMessage = new NapiNdefMessage();
std::size_t argc = 0;
napi_value argv[] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiNdefTag *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("getType objInfo %{public}p", objectInfo);
// transfer
NdefTag *nfcNdefTagPtr = static_cast<NdefTag *>(static_cast<void *>(objectInfo->tagSession.get()));
if (nfcNdefTagPtr == nullptr) {
ErrorLog("GetType find objectInfo failed!");
return nullptr;
} else {
ndpiNdefMessage->ndefMessage = nfcNdefTagPtr->GetCachedNdefMsg();
napi_status status1 = napi_wrap(
env, ndefMessage, ndpiNdefMessage,
[](napi_env env, void *data, void *hint) {
if (data) {
NdefMessage *message = (NdefMessage *)data;
delete message;
}
},
nullptr, nullptr);
NAPI_ASSERT(env, status1 == napi_ok, "failed to wrap ndefMessage");
return ndefMessage;
}
}
static bool MatchIsNdefWritableParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
if (parameterCount > ARGV_NUM_1) {
return false;
}
if (parameterCount == ARGV_NUM_1) {
return MatchParameters(env, parameters, {napi_function});
}
return true;
}
static void NativeIsNdefWritable(napi_env env, void *data)
{
DebugLog("NativeIsNdefWritable called");
auto context = static_cast<NdefContext<bool, NapiNdefTag> *>(data);
DebugLog("NativeIsNdefWritable objInfo %{public}p", context->objectInfo);
NdefTag *nfcNdefTagPtr = static_cast<NdefTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcNdefTagPtr == nullptr) {
ErrorLog("NativeIsNdefWritable find objectInfo failed!");
context->value = true;
} else {
context->value = nfcNdefTagPtr->IsNdefWritable();
DebugLog("IsNdefWritable %{public}d", context->value);
}
context->resolved = true;
}
static void IsNdefWritableCallback(napi_env env, napi_status status, void *data)
{
DebugLog("IsNdefWritableCallback called");
auto context = static_cast<NdefContext<bool, NapiNdefTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_status status = napi_get_boolean(env, context->value, &callbackValue);
if (status != napi_ok) {
ErrorLog("get boolean failed");
}
} else {
callbackValue = CreateErrorMessage(env, "IsNdefWritable error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "IsNdefWritable error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiNdefTag::IsNdefWritable(napi_env env, napi_callback_info info)
{
DebugLog("GetNdefTag IsNdefWritable called");
size_t paramsCount = ARGV_NUM_1;
napi_value params[ARGV_NUM_1] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiNdefTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("IsNdefWritable objInfo %{public}p", objectInfoCb);
NAPI_ASSERT(env, MatchIsNdefWritableParameters(env, params, paramsCount), "IsNdefWritable type mismatch");
auto context = std::make_unique<NdefContext<bool, NapiNdefTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "error at CallBackContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
if (paramsCount == ARGV_NUM_1) {
napi_create_reference(env, params[ARGV_INDEX_0], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result = HandleAsyncWork(env, context, "IsNdefWritable", NativeIsNdefWritable, IsNdefWritableCallback);
return result;
}
static bool MatchReadNdefParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
if (parameterCount > ARGV_NUM_1) {
return false;
}
if (parameterCount == ARGV_NUM_1) {
return MatchParameters(env, parameters, {napi_function});
}
return true;
}
static void NativeReadNdef(napi_env env, void *data)
{
DebugLog("NativeReadNdef called");
auto context = static_cast<NdefContext<std::shared_ptr<NdefMessage>, NapiNdefTag> *>(data);
DebugLog("NativeReadNdef objInfo %{public}p", context->objectInfo);
NdefTag *nfcNdefTagPtr = static_cast<NdefTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcNdefTagPtr == nullptr) {
ErrorLog("NativeReadNdef find objectInfo failed!");
} else {
context->value = nfcNdefTagPtr->ReadNdef();
}
context->resolved = true;
}
static void ReadNdefCallback(napi_env env, napi_status status, void *data)
{
DebugLog("ReadNdefCallback called");
NapiNdefMessage *ndpiNdefMessage = new NapiNdefMessage();
auto context = static_cast<NdefContext<std::shared_ptr<NdefMessage>, NapiNdefTag> *>(data);
napi_value callbackValue = nullptr;
ndpiNdefMessage->ndefMessage = context->value;
if (status == napi_ok) {
if (context->resolved) {
napi_create_object(env, &callbackValue);
napi_status status1 = napi_wrap(
env, callbackValue, ndpiNdefMessage,
[](napi_env env, void *data, void *hint) {
if (data) {
NdefMessage *message = (NdefMessage *)data;
delete message;
}
},
nullptr, nullptr);
if (status1 != napi_ok) {
ErrorLog("get object failed");
}
} else {
callbackValue = CreateErrorMessage(env, "ReadNdef error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "ReadNdef error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiNdefTag::ReadNdef(napi_env env, napi_callback_info info)
{
DebugLog("GetNdefTag ReadNdef called");
size_t paramsCount = ARGV_NUM_1;
napi_value params[ARGV_NUM_1] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiNdefTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("ReadNdef objInfo %{public}p", objectInfoCb);
NAPI_ASSERT(env, MatchReadNdefParameters(env, params, paramsCount), "ReadNdef type mismatch");
auto context = std::make_unique<NdefContext<std::shared_ptr<NdefMessage>, NapiNdefTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "error at CallBackContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
if (paramsCount == ARGV_NUM_1) {
napi_create_reference(env, params[ARGV_INDEX_0], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result = HandleAsyncWork(env, context, "ReadNdef", NativeReadNdef, ReadNdefCallback);
return result;
}
static bool MatchWriteNdefParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
bool typeMatch = false;
switch (parameterCount) {
case ARGV_NUM_1: {
typeMatch = MatchParameters(env, parameters, {napi_object});
break;
}
case ARGV_NUM_2:
typeMatch = MatchParameters(env, parameters, {napi_object, napi_function});
break;
default: {
return false;
}
}
return typeMatch;
}
static void NativeWriteNdef(napi_env env, void *data)
{
DebugLog("NativeWriteNdef called");
auto context = static_cast<NdefContext<int, NapiNdefTag> *>(data);
DebugLog("NativeWriteNdef objInfo %{public}p", context->objectInfo);
NdefTag *nfcNdefTagPtr = static_cast<NdefTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcNdefTagPtr == nullptr) {
ErrorLog("NativeWriteNdef find objectInfo failed!");
context->value = true;
} else {
context->value = nfcNdefTagPtr->WriteNdef(context->msg);
DebugLog("WriteNdef %{public}d", context->value);
}
context->resolved = true;
}
static void WriteNdefCallback(napi_env env, napi_status status, void *data)
{
DebugLog("SetReadOnlyCallback called");
auto context = static_cast<NdefContext<int, NapiNdefTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_create_int32(env, context->value, &callbackValue);
} else {
callbackValue = CreateErrorMessage(env, "WriteNdef error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "WriteNdef error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiNdefTag::WriteNdef(napi_env env, napi_callback_info info)
{
DebugLog("GetNdefTag WriteNdef called");
size_t paramsCount = ARGV_NUM_2;
napi_value params[ARGV_NUM_2] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiNdefTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("WriteNdef objInfo %{public}p", objectInfoCb);
NAPI_ASSERT(env, MatchWriteNdefParameters(env, params, paramsCount), "WriteNdef type mismatch");
auto context = std::make_unique<NdefContext<int, NapiNdefTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "error at CallBackContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
// parse the params
napi_status status1 = napi_unwrap(env, params[ARGV_INDEX_0], reinterpret_cast<void **>(&context->msg));
NAPI_ASSERT(env, status1 == napi_ok, "failed to get ndefMessage");
if (paramsCount == ARGV_NUM_2) {
napi_create_reference(env, params[ARGV_INDEX_1], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result = HandleAsyncWork(env, context, "WriteNdef", NativeWriteNdef, WriteNdefCallback);
return result;
}
static bool MatchCanSetReadOnlyParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
if (parameterCount > ARGV_NUM_1) {
return false;
}
if (parameterCount == ARGV_NUM_1) {
return MatchParameters(env, parameters, {napi_function});
}
return true;
}
static void NativeCanSetReadOnly(napi_env env, void *data)
{
DebugLog("NativeCanSetReadOnly called");
auto context = static_cast<NdefContext<bool, NapiNdefTag> *>(data);
DebugLog("NativeCanSetReadOnly objInfo %{public}p", context->objectInfo);
NdefTag *nfcNdefTagPtr = static_cast<NdefTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcNdefTagPtr == nullptr) {
ErrorLog("NativeCanSetReadOnly find objectInfo failed!");
context->value = true;
} else {
context->value = nfcNdefTagPtr->IsEnableReadOnly();
DebugLog("CanSetReadOnly %{public}d", context->value);
}
context->resolved = true;
}
static void CanSetReadOnlyCallback(napi_env env, napi_status status, void *data)
{
DebugLog("CanSetReadOnlyCallback called");
auto context = static_cast<NdefContext<bool, NapiNdefTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_status status = napi_get_boolean(env, context->value, &callbackValue);
if (status != napi_ok) {
ErrorLog("get boolean failed");
}
} else {
callbackValue = CreateErrorMessage(env, "CanSetReadOnly error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "CanSetReadOnly error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiNdefTag::CanSetReadOnly(napi_env env, napi_callback_info info)
{
DebugLog("GetNdefTag CanSetReadOnly called");
size_t paramsCount = ARGV_NUM_1;
napi_value params[ARGV_NUM_1] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiNdefTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("CanSetReadOnly objInfo %{public}p", objectInfoCb);
NAPI_ASSERT(env, MatchCanSetReadOnlyParameters(env, params, paramsCount), "CanSetReadOnly type mismatch");
auto context = std::make_unique<NdefContext<bool, NapiNdefTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "error at CallBackContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
if (paramsCount == ARGV_NUM_1) {
napi_create_reference(env, params[ARGV_INDEX_0], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result = HandleAsyncWork(env, context, "CanSetReadOnly", NativeCanSetReadOnly, CanSetReadOnlyCallback);
return result;
}
static bool MatchSetReadOnlyParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
if (parameterCount > ARGV_NUM_1) {
return false;
}
if (parameterCount == ARGV_NUM_1) {
return MatchParameters(env, parameters, {napi_function});
}
return true;
}
static void NativeSetReadOnly(napi_env env, void *data)
{
DebugLog("NativeSetReadOnly called");
auto context = static_cast<NdefContext<int, NapiNdefTag> *>(data);
DebugLog("NativeSetReadOnly objInfo %{public}p", context->objectInfo);
NdefTag *nfcNdefTagPtr = static_cast<NdefTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (nfcNdefTagPtr == nullptr) {
ErrorLog("NativeSetReadOnly find objectInfo failed!");
context->value = true;
} else {
context->value = nfcNdefTagPtr->EnableReadOnly();
DebugLog("SetReadOnly %{public}d", context->value);
}
context->resolved = true;
}
static void SetReadOnlyCallback(napi_env env, napi_status status, void *data)
{
DebugLog("SetReadOnlyCallback called");
auto context = static_cast<NdefContext<int, NapiNdefTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_create_int32(env, context->value, &callbackValue);
} else {
callbackValue = CreateErrorMessage(env, "SetReadOnly error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "SetReadOnly error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiNdefTag::SetReadOnly(napi_env env, napi_callback_info info)
{
DebugLog("GetNdefTag SetReadOnly called");
size_t paramsCount = ARGV_NUM_1;
napi_value params[ARGV_NUM_1] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiNdefTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("SetReadOnly objInfo %{public}p", objectInfoCb);
NAPI_ASSERT(env, MatchSetReadOnlyParameters(env, params, paramsCount), "SetReadOnly type mismatch");
auto context = std::make_unique<NdefContext<int, NapiNdefTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "error at CallBackContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
if (paramsCount == ARGV_NUM_1) {
napi_create_reference(env, params[ARGV_INDEX_0], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result = HandleAsyncWork(env, context, "SetReadOnly", NativeSetReadOnly, SetReadOnlyCallback);
return result;
}
napi_value NapiNdefTag::GetNdefTagTypeString(napi_env env, napi_callback_info info)
{
DebugLog("GetNdefTag GetNdefTagTypeString called");
napi_value thisVar = nullptr;
size_t expectedArgsCount = ARGV_NUM_1;
size_t argc = expectedArgsCount;
napi_value argv[ARGV_NUM_1] = {0};
napi_value result = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
// check parameter number
if (argc != expectedArgsCount) {
ErrorLog("NapiNdefTag::GetNdefTagTypeString, Requires 1 argument.");
return result;
}
// check parameter data type
napi_valuetype valueType = napi_undefined;
NAPI_CALL(env, napi_typeof(env, argv[ARGV_INDEX_0], &valueType));
if (valueType != napi_number) {
ErrorLog("NapiNdefTag::GetNdefTagTypeString, Invalid data type!");
return nullptr;
}
NapiNdefTag *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("getNdefTagTypeString objInfo %{public}p", objectInfo);
int type;
ParseInt32(env, type, argv[ARGV_INDEX_0]);
// transfer
NdefTag *nfcNdefTagPtr = static_cast<NdefTag *>(static_cast<void *>(objectInfo->tagSession.get()));
if (nfcNdefTagPtr == nullptr) {
ErrorLog("GetNdefTagTypeString find objectInfo failed!");
return nullptr;
} else {
napi_value ret = nullptr;
std::string ndefTagType =
nfcNdefTagPtr->GetNdefTagTypeString(static_cast<NdefTag::EmNfcForumType>(type));
DebugLog("ndefTagType %{public}s", ndefTagType.c_str());
napi_create_string_utf8(env, ndefTagType.c_str(), NAPI_AUTO_LENGTH, &ret);
return ret;
}
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,53 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_TAG_NDEF_H_
#define NFC_NAPI_TAG_NDEF_H_
#include <locale>
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "ndef_tag.h"
#include "ndef_message.h"
#include "nfc_napi_ndef_message.h"
#include "nfc_napi_tag_sesstion.h"
#include "nfc_napi_utils.h"
namespace OHOS {
namespace NFC {
namespace KITS {
struct NapiNdefTag : public NapiNfcTagSession {
static napi_value RegisterNdefMessageObject(napi_env env, napi_value exports);
static napi_value CreateNdefMessage(napi_env env, napi_callback_info info);
static napi_value GetNdefTagType(napi_env env, napi_callback_info info);
static napi_value GetNdefMessage(napi_env env, napi_callback_info info);
static napi_value IsNdefWritable(napi_env env, napi_callback_info info);
static napi_value ReadNdef(napi_env env, napi_callback_info info);
static napi_value WriteNdef(napi_env env, napi_callback_info info);
static napi_value CanSetReadOnly(napi_env env, napi_callback_info info);
static napi_value SetReadOnly(napi_env env, napi_callback_info info);
static napi_value GetNdefTagTypeString(napi_env env, napi_callback_info info);
};
template<typename T, typename D>
struct NdefContext : BaseContext {
T value;
D *objectInfo;
std::shared_ptr<NdefMessage> msg;
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif
@@ -1,206 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_tag_ndef_formatable.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
static const int32_t DEFAULT_REF_COUNT = 1;
static bool MatchFormatParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
bool typeMatch = false;
switch (parameterCount) {
case ARGV_NUM_1: {
typeMatch = MatchParameters(env, parameters, {napi_object});
break;
}
case ARGV_NUM_2:
typeMatch = MatchParameters(env, parameters, {napi_object, napi_function});
break;
default: {
return false;
}
}
return typeMatch;
}
static void NativeFormat(napi_env env, void *data)
{
DebugLog("NativeFormat called");
auto context = static_cast<NdefFormatableContext<int, NapiNdefFormatableTag> *>(data);
DebugLog("NativeFormat objInfo %{public}p", context->objectInfo);
NdefFormatableTag *ndefFormatableTagPtr =
static_cast<NdefFormatableTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (ndefFormatableTagPtr == nullptr) {
ErrorLog("NativeFormat find objectInfo failed!");
context->value = true;
} else {
context->value = ndefFormatableTagPtr->Format(context->msg);
DebugLog("Format %{public}d", context->value);
}
context->resolved = true;
}
static void FormatCallback(napi_env env, napi_status status, void *data)
{
DebugLog("FormatCallback called");
auto context = static_cast<NdefFormatableContext<int, NapiNdefFormatableTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_create_int32(env, context->value, &callbackValue);
} else {
callbackValue = CreateErrorMessage(env, "Format error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "Format error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiNdefFormatableTag::Format(napi_env env, napi_callback_info info)
{
DebugLog("GetNdefFormatableTag Format called");
size_t paramsCount = ARGV_NUM_2;
napi_value params[ARGV_NUM_2] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiNdefFormatableTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("WriteNdef objInfo %{public}p", objectInfoCb);
NAPI_ASSERT(env, MatchFormatParameters(env, params, paramsCount), "Format type mismatch");
auto context = std::make_unique<NdefFormatableContext<int, NapiNdefFormatableTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "error at CallBackContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
// parse the params
napi_status status1 = napi_unwrap(env, params[ARGV_INDEX_0], reinterpret_cast<void **>(&context->msg));
NAPI_ASSERT(env, status1 == napi_ok, "failed to get ndefMessage");
if (paramsCount == ARGV_NUM_2) {
napi_create_reference(env, params[ARGV_INDEX_1], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result = HandleAsyncWork(env, context, "Format", NativeFormat, FormatCallback);
return result;
}
static bool MatchFormatReadOnlyParameters(napi_env env, const napi_value parameters[], size_t parameterCount)
{
bool typeMatch = false;
switch (parameterCount) {
case ARGV_NUM_1: {
typeMatch = MatchParameters(env, parameters, {napi_object});
break;
}
case ARGV_NUM_2:
typeMatch = MatchParameters(env, parameters, {napi_object, napi_function});
break;
default: {
return false;
}
}
return typeMatch;
}
static void NativeFormatReadOnly(napi_env env, void *data)
{
DebugLog("NativeFormatReadOnly called");
auto context = static_cast<NdefFormatableContext<int, NapiNdefFormatableTag> *>(data);
DebugLog("NativeFormatReadOnly objInfo %{public}p", context->objectInfo);
NdefFormatableTag *ndefFormatableTagPtr =
static_cast<NdefFormatableTag *>(static_cast<void *>(context->objectInfo->tagSession.get()));
if (ndefFormatableTagPtr == nullptr) {
ErrorLog("NativeFormatReadOnly find objectInfo failed!");
context->value = true;
} else {
context->value = ndefFormatableTagPtr->FormatReadOnly(context->msg);
DebugLog("FormatReadOnly %{public}d", context->value);
}
context->resolved = true;
}
static void FormatReadOnlyCallback(napi_env env, napi_status status, void *data)
{
DebugLog("FormatReadOnlyCallback called");
auto context = static_cast<NdefFormatableContext<int, NapiNdefFormatableTag> *>(data);
napi_value callbackValue = nullptr;
if (status == napi_ok) {
if (context->resolved) {
napi_create_int32(env, context->value, &callbackValue);
} else {
callbackValue = CreateErrorMessage(env, "FormatReadOnly error by ipc");
}
} else {
callbackValue = CreateErrorMessage(env, "FormatReadOnly error,napi_status = " + std ::to_string(status));
}
Handle2ValueCallback(env, context, callbackValue);
}
napi_value NapiNdefFormatableTag::FormatReadOnly(napi_env env, napi_callback_info info)
{
DebugLog("GetNdefFormatableTag FormatReadOnly called");
size_t paramsCount = ARGV_NUM_2;
napi_value params[ARGV_NUM_2] = {0};
void *data = nullptr;
napi_value thisVar = nullptr;
NapiNdefFormatableTag *objectInfoCb = nullptr;
napi_get_cb_info(env, info, &paramsCount, params, &thisVar, &data);
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfoCb));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
DebugLog("FormatReadOnly objInfo %{public}p", objectInfoCb);
NAPI_ASSERT(env, MatchFormatReadOnlyParameters(env, params, paramsCount), "FormatReadOnly type mismatch");
auto context = std::make_unique<NdefFormatableContext<int, NapiNdefFormatableTag>>().release();
if (context == nullptr) {
std::string errorCode = std::to_string(napi_generic_failure);
std::string errorMessage = "error at CallBackContext is nullptr";
NAPI_CALL(env, napi_throw_error(env, errorCode.c_str(), errorMessage.c_str()));
return nullptr;
}
// parse the params
napi_status status1 = napi_unwrap(env, params[ARGV_INDEX_0], reinterpret_cast<void **>(&context->msg));
NAPI_ASSERT(env, status1 == napi_ok, "failed to get ndefMessage");
if (paramsCount == ARGV_NUM_2) {
napi_create_reference(env, params[ARGV_INDEX_1], DEFAULT_REF_COUNT, &context->callbackRef);
}
context->objectInfo = objectInfoCb;
napi_value result = HandleAsyncWork(env, context, "FormatReadOnly", NativeFormatReadOnly, FormatReadOnlyCallback);
return result;
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,45 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_TAG_NDEF_FORMATABLE_H_
#define NFC_NAPI_TAG_NDEF_FORMATABLE_H_
#include <locale>
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "ndef_formatable_tag.h"
#include "ndef_message.h"
#include "nfc_napi_ndef_message.h"
#include "nfc_napi_tag_sesstion.h"
#include "nfc_napi_utils.h"
namespace OHOS {
namespace NFC {
namespace KITS {
struct NapiNdefFormatableTag : public NapiNfcTagSession {
static napi_value Format(napi_env env, napi_callback_info info);
static napi_value FormatReadOnly(napi_env env, napi_callback_info info);
};
template<typename T, typename D>
struct NdefFormatableContext : BaseContext {
T value;
D *objectInfo;
std::shared_ptr<NdefMessage> msg;
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif
@@ -1,127 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_tag_sesstion.h"
#include "loghelper.h"
namespace OHOS {
namespace NFC {
namespace KITS {
napi_value NapiNfcTagSession::ConnectTag(napi_env env, napi_callback_info info)
{
DebugLog("GetTagSession ConnectTag called");
std::size_t argc = 0;
napi_value argv[] = {nullptr};
napi_value result = nullptr;
napi_value thisVar = nullptr;
bool isConnected = false;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiNfcTagSession *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
BasicTagSession *nfcTagPtr = objectInfo->tagSession.get();
if (nfcTagPtr == nullptr) {
ErrorLog("ConnectTag find objectInfo failed!");
return nullptr;
} else {
napi_value ret = nullptr;
isConnected = nfcTagPtr->Connect();
napi_get_boolean(env, isConnected, &result);
return ret;
}
}
napi_value NapiNfcTagSession::Reset(napi_env env, napi_callback_info info)
{
DebugLog("TagSession Reset called");
std::size_t argc = 0;
napi_value argv[] = {nullptr};
napi_value result = nullptr;
napi_value thisVar = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiNfcTagSession *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
BasicTagSession *nfcTagPtr = objectInfo->tagSession.get();
if (nfcTagPtr == nullptr) {
ErrorLog("Reset find objectInfo failed!");
return nullptr;
} else {
int err = nfcTagPtr->Close();
if (err != NfcErrorCode::NFC_SUCCESS) {
ErrorLog("Reset failed!");
} else {
DebugLog("Reset finished.");
}
return result;
}
}
napi_value NapiNfcTagSession::IsTagConnected(napi_env env, napi_callback_info info)
{
DebugLog("GetTagSession IsTagConnected called");
std::size_t argc = 0;
napi_value argv[] = {nullptr};
napi_value result = nullptr;
napi_value thisVar = nullptr;
bool connectTag = false;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiNfcTagSession *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
BasicTagSession *nfcTagPtr = objectInfo->tagSession.get();
if (nfcTagPtr == nullptr) {
ErrorLog("IsTagConnected find objectInfo failed!");
return nullptr;
} else {
connectTag = nfcTagPtr->IsConnected();
napi_get_boolean(env, connectTag, &result);
return result;
}
}
napi_value NapiNfcTagSession::GetMaxSendLength(napi_env env, napi_callback_info info)
{
DebugLog("TagSession GetMaxSendLength called");
std::size_t argc = 0;
napi_value argv[] = {nullptr};
napi_value result = nullptr;
napi_value thisVar = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
NapiNfcTagSession *objectInfo = nullptr;
// unwrap from thisVar to retrieve the native instance
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&objectInfo));
NAPI_ASSERT(env, status == napi_ok, "failed to get objectInfo");
BasicTagSession *nfcTagPtr = objectInfo->tagSession.get();
if (nfcTagPtr == nullptr) {
ErrorLog("GetMaxSendLength find objectInfo failed!");
return nullptr;
} else {
int maxsendlen = nfcTagPtr->GetMaxSendCommandLength();
napi_create_int32(env, maxsendlen, &result);
return result;
}
}
} // namespace KITS
} // namespace NFC
} // namespace OHOS
@@ -1,41 +0,0 @@
/*
* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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_TAG_SESSTION_H_
#define NFC_NAPI_TAG_SESSTION_H_
#include <memory>
#include "basic_tag_session.h"
#include "napi/native_node_api.h"
#include "nfc_napi_utils.h"
namespace OHOS {
namespace NFC {
namespace KITS {
struct NapiNfcTagSession {
static napi_value GetTagInfo(napi_env env, napi_callback_info info);
static napi_value ConnectTag(napi_env env, napi_callback_info info);
static napi_value Reset(napi_env env, napi_callback_info info);
static napi_value IsTagConnected(napi_env env, napi_callback_info info);
static napi_value SetSendDataTimeout(napi_env env, napi_callback_info info);
static napi_value GetSendDataTimeout(napi_env env, napi_callback_info info);
static napi_value SendData(napi_env env, napi_callback_info info);
static napi_value GetMaxSendLength(napi_env env, napi_callback_info info);
std::shared_ptr<BasicTagSession> tagSession = nullptr;
};
} // namespace KITS
} // namespace NFC
} // namespace OHOS
#endif

Some files were not shown because too many files have changed in this diff Show More