1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "nfc_cardEmulation_controller.h"
17 #include "nfc_cardEmulation_ffi.h"
18 #include "cj_lambda.h"
19
20 namespace OHOS {
21 namespace NFC {
22 namespace KITS {
23 std::mutex CjNfcCardEmulationController::controllerMutex_;
24 std::shared_ptr<CjNfcCardEmulationController> CjNfcCardEmulationController::controller_ { nullptr };
25 const int8_t HCE_CMD = 0; // defined by cangjie enum NfcEventType
26
GetInstance()27 std::shared_ptr<CjNfcCardEmulationController> CjNfcCardEmulationController::GetInstance()
28 {
29 if (controller_ == nullptr) {
30 std::lock_guard<std::mutex> lock(controllerMutex_);
31 if (controller_ == nullptr) {
32 auto controller = std::make_shared<CjNfcCardEmulationController>();
33 controller_ = controller;
34 }
35 }
36 return controller_;
37 }
38
Subscribe(int8_t type,int64_t id)39 int32_t CjNfcCardEmulationController::Subscribe(int8_t type, int64_t id)
40 {
41 RegisterListener(type, id);
42 return SUCCESS_CODE;
43 }
44
UnSubscribe(int8_t type)45 int32_t CjNfcCardEmulationController::UnSubscribe(int8_t type)
46 {
47 UnRegisterListener(type);
48 return SUCCESS_CODE;
49 }
50
RegisterListener(int8_t type,int64_t id)51 void CjNfcCardEmulationController::RegisterListener(int8_t type, int64_t id)
52 {
53 std::lock_guard<std::recursive_mutex> lock(mutex_);
54 switch (type) {
55 case HCE_CMD:
56 InitHceCmd(id);
57 break;
58 default:
59 return;
60 }
61 }
62
UnRegisterListener(int8_t type)63 void CjNfcCardEmulationController::UnRegisterListener(int8_t type)
64 {
65 std::lock_guard<std::recursive_mutex> lock(mutex_);
66 switch (type) {
67 case HCE_CMD:
68 hceCmd_ = nullptr;
69 break;
70 default:
71 return;
72 }
73 }
74
InitHceCmd(int64_t id)75 void CjNfcCardEmulationController::InitHceCmd(int64_t id)
76 {
77 auto callback = reinterpret_cast<void (*)(const uint8_t *, int64_t)>(id);
78 hceCmd_ = [lambda = CJLambda::Create(callback)](const uint8_t *head, int64_t size) -> void { lambda(head, size); };
79 }
80
HceCmd(const std::vector<uint8_t> & data)81 void CjNfcCardEmulationController::HceCmd(const std::vector<uint8_t> &data)
82 {
83 std::lock_guard<std::recursive_mutex> lock(mutex_);
84 if (hceCmd_ == nullptr) {
85 return;
86 }
87 hceCmd_(data.data(), data.size());
88 return;
89 }
90
91 } // namespace KITS
92 } // namespace NFC
93 } // namespace OHOS