• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 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 #include "nfc_service.h"
16 #include <unistd.h>
17 #include "app_data_parser.h"
18 #include "infc_controller_callback.h"
19 #include "iservice_registry.h"
20 #include "loghelper.h"
21 #include "nfc_preferences.h"
22 #include "nfc_event_handler.h"
23 #include "nfc_event_publisher.h"
24 #include "nfc_hisysevent.h"
25 #include "nfc_polling_params.h"
26 #include "nfc_sdk_common.h"
27 #include "nfc_timer.h"
28 #include "nfc_watch_dog.h"
29 #include "tag_session.h"
30 #include "external_deps_proxy.h"
31 #include "want.h"
32 #include "nci_nfcc_proxy.h"
33 #include "nci_tag_proxy.h"
34 #include "nci_ce_proxy.h"
35 #include "hce_session.h"
36 
37 namespace OHOS {
38 namespace NFC {
39 const std::u16string NFC_SERVICE_NAME = OHOS::to_utf16("ohos.nfc.service");
40 uint32_t NfcService::unloadStaSaTimerId{0};
41 
NfcService()42 NfcService::NfcService()
43     : eventHandler_(nullptr),
44     tagDispatcher_(nullptr),
45     nfcControllerImpl_(nullptr),
46     nfcState_(KITS::STATE_OFF)
47 {
48 }
49 
~NfcService()50 NfcService::~NfcService()
51 {
52     nfcControllerImpl_ = nullptr;
53     nfcPollingManager_ = nullptr;
54     nfcRoutingManager_ = nullptr;
55 }
56 
GetInstance() const57 std::weak_ptr<NfcService> NfcService::GetInstance() const
58 {
59     return nfcService_;
60 }
61 
GetNciNfccProxy(void)62 std::weak_ptr<NCI::INciNfccInterface> NfcService::GetNciNfccProxy(void)
63 {
64     return nciNfccProxy_;
65 }
66 
GetNciTagProxy(void)67 std::weak_ptr<NCI::INciTagInterface> NfcService::GetNciTagProxy(void)
68 {
69     return nciTagProxy_;
70 }
71 
GetNfcPollingManager()72 std::weak_ptr<NfcPollingManager> NfcService::GetNfcPollingManager()
73 {
74     return nfcPollingManager_;
75 }
76 
GetNfcRoutingManager()77 std::weak_ptr<NfcRoutingManager> NfcService::GetNfcRoutingManager()
78 {
79     return nfcRoutingManager_;
80 }
81 
GetCeService()82 std::weak_ptr<CeService> NfcService::GetCeService()
83 {
84     return ceService_;
85 }
86 
GetSimVendorBundleName()87 std::string NfcService::GetSimVendorBundleName()
88 {
89     return nciCeProxy_->GetSimVendorBundleName();
90 }
91 
Initialize()92 bool NfcService::Initialize()
93 {
94     nfcService_ = shared_from_this();
95     InfoLog("Nfc service initialize.");
96     nciNfccProxy_ = std::make_shared<NFC::NCI::NciNfccProxy>();
97     nciTagProxy_ = std::make_shared<NFC::NCI::NciTagProxy>();
98     nciCeProxy_ = std::make_shared<NFC::NCI::NciCeProxy>();
99     nciTagProxy_->SetTagListener(nfcService_);
100     nciCeProxy_->SetCeHostListener(nfcService_);
101 
102     // inner message handler, used by other modules as initialization parameters
103     std::shared_ptr<AppExecFwk::EventRunner> runner = AppExecFwk::EventRunner::Create("nfcservice::EventRunner");
104     eventHandler_ = std::make_shared<NfcEventHandler>(runner, shared_from_this());
105     nfcSwitchHandler_ = std::make_shared<NfcSwitchEventHandler>(
106         AppExecFwk::EventRunner::Create("NfcSwitchHandler", AppExecFwk::ThreadMode::FFRT), shared_from_this());
107     tagDispatcher_ = std::make_shared<TAG::TagDispatcher>(shared_from_this());
108     ceService_ = std::make_shared<CeService>(shared_from_this(), nciCeProxy_);
109 
110     nfcPollingManager_ = std::make_shared<NfcPollingManager>(shared_from_this(), nciNfccProxy_, nciTagProxy_);
111     nfcRoutingManager_ = std::make_shared<NfcRoutingManager>(eventHandler_, nciNfccProxy_,
112         nciCeProxy_, shared_from_this());
113     tagSessionIface_ = new TAG::TagSession(shared_from_this());
114     hceSessionIface_ = new HCE::HceSession(shared_from_this());
115 
116     // used by NfcSaManager::Init(), to public for the proxy.
117     nfcControllerImpl_ = new NfcControllerImpl(shared_from_this());
118     nfcPollingManager_->ResetCurrPollingParams();
119 
120     runner->Run();
121 
122     eventHandler_->Intialize(tagDispatcher_, ceService_, nfcPollingManager_, nfcRoutingManager_, nciNfccProxy_);
123     ExternalDepsProxy::GetInstance().InitAppList();
124     return true;
125 }
126 
UnloadNfcSa()127 void NfcService::UnloadNfcSa()
128 {
129 #ifndef DTFUZZ_TEST // not for fuzz
130     InfoLog("%{public}s enter, systemAbilityId = [%{public}d] unloading", __func__, KITS::NFC_MANAGER_SYS_ABILITY_ID);
131     if (nfcState_ != KITS::STATE_OFF) {
132         InfoLog("%{public}s nfc state = [%{public}d] skip unload", __func__, nfcState_);
133         return;
134     }
135     sptr<ISystemAbilityManager> samgr =
136         SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
137     if (samgr == nullptr) {
138         ErrorLog("%{public}s: get system ability manager failed!", __func__);
139         return;
140     }
141     int32_t ret = samgr->UnloadSystemAbility(KITS::NFC_MANAGER_SYS_ABILITY_ID);
142     if (ret != ERR_NONE) {
143         ErrorLog("%{public}s: Failed to unload system ability, SA Id = [%{public}d], ret = [%{public}d].",
144             __func__, KITS::NFC_MANAGER_SYS_ABILITY_ID, ret);
145     }
146 #endif
147 }
148 
GetTagDispatcher()149 std::weak_ptr<TAG::TagDispatcher> NfcService::GetTagDispatcher()
150 {
151     return tagDispatcher_;
152 }
153 
GetTagServiceIface()154 OHOS::sptr<IRemoteObject> NfcService::GetTagServiceIface()
155 {
156     return tagSessionIface_;
157 }
158 
OnTagDiscovered(uint32_t tagDiscId)159 void NfcService::OnTagDiscovered(uint32_t tagDiscId)
160 {
161     InfoLog("NfcService::OnTagDiscovered tagDiscId %{public}d", tagDiscId);
162     eventHandler_->SendEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_TAG_FOUND), tagDiscId, 0);
163     InfoLog("NfcService::OnTagDiscovered end");
164 }
165 
OnTagLost(uint32_t tagDiscId)166 void NfcService::OnTagLost(uint32_t tagDiscId)
167 {
168     InfoLog("NfcService::OnTagLost tagDiscId %{public}d", tagDiscId);
169     eventHandler_->SendEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_TAG_LOST), tagDiscId, 0);
170 }
171 
FieldActivated()172 void NfcService::FieldActivated()
173 {
174     InfoLog("NfcService::FieldActivated");
175     eventHandler_->SendEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_FIELD_ACTIVATED));
176 }
177 
FieldDeactivated()178 void NfcService::FieldDeactivated()
179 {
180     InfoLog("NfcService::FieldDeactivated");
181     eventHandler_->SendEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_FIELD_DEACTIVATED));
182 }
183 
184 #ifdef VENDOR_APPLICATIONS_ENABLED
OnVendorEvent(int eventType,int arg1,std::string arg2)185 void NfcService::OnVendorEvent(int eventType, int arg1, std::string arg2)
186 {
187     InfoLog("NfcService::OnVendorEvent");
188     eventHandler_->SendEvent(static_cast<uint32_t>(NfcCommonEvent::MSG_VENDOR_EVENT), eventType, 0);
189 }
190 #endif
191 
OnCardEmulationData(const std::vector<uint8_t> & data)192 void NfcService::OnCardEmulationData(const std::vector<uint8_t> &data)
193 {
194     InfoLog("NfcService::OnCardEmulationData");
195     ceService_->OnCardEmulationData(data);
196 }
197 
OnCardEmulationActivated()198 void NfcService::OnCardEmulationActivated()
199 {
200     InfoLog("NfcService::OnCardEmulationActivated");
201     ceService_->OnCardEmulationActivated();
202 }
203 
GetHceServiceIface()204 OHOS::sptr<IRemoteObject> NfcService::GetHceServiceIface()
205 {
206     return hceSessionIface_;
207 }
208 
OnCardEmulationDeactivated()209 void NfcService::OnCardEmulationDeactivated()
210 {
211     InfoLog("NfcService::OnCardEmulationDeactivated");
212     ceService_->OnCardEmulationDeactivated();
213 }
214 
ExecuteTask(KITS::NfcTask param)215 int NfcService::ExecuteTask(KITS::NfcTask param)
216 {
217     if (nfcSwitchHandler_ == nullptr) {
218         ErrorLog("eventhandler nullptr.");
219         return KITS::ERR_NFC_STATE_INVALID;
220     }
221     InfoLog("executing task [%{public}d]", param);
222     nfcSwitchHandler_->RemoveAllEvents();
223     nfcSwitchHandler_->SendEvent(param);
224     return ERR_NONE;
225 }
226 
NfcSwitchEventHandler(const std::shared_ptr<AppExecFwk::EventRunner> & runner,std::weak_ptr<NfcService> service)227 NfcService::NfcSwitchEventHandler::NfcSwitchEventHandler(
228     const std::shared_ptr<AppExecFwk::EventRunner>& runner, std::weak_ptr<NfcService> service)
229     : EventHandler(runner), nfcService_(service)
230 {
231 }
232 
~NfcSwitchEventHandler()233 NfcService::NfcSwitchEventHandler::~NfcSwitchEventHandler()
234 {
235 }
236 
CheckNfcState(int param)237 bool NfcService::NfcSwitchEventHandler::CheckNfcState(int param)
238 {
239     if (nfcService_.expired()) {
240         ErrorLog("nfcService_ is nullptr.");
241         return false;
242     }
243     int nfcState = nfcService_.lock()->GetNfcState();
244     if (nfcState == KITS::STATE_TURNING_OFF || nfcState == KITS::STATE_TURNING_ON) {
245         WarnLog("Execute task %{public}d from bad state %{public}d", param, nfcState);
246         return false;
247     }
248     if (param == KITS::TASK_TURN_ON && nfcState == KITS::STATE_ON) {
249         WarnLog("NFC Turn On, already On");
250         ExternalDepsProxy::GetInstance().UpdateNfcState(KITS::STATE_ON);
251         return false;
252     }
253     if (param == KITS::TASK_TURN_OFF && nfcState == KITS::STATE_OFF) {
254         WarnLog("NFC Turn Off, already Off");
255         ExternalDepsProxy::GetInstance().UpdateNfcState(KITS::STATE_OFF);
256         return false;
257     }
258     return true;
259 }
260 
ProcessEvent(const AppExecFwk::InnerEvent::Pointer & event)261 void NfcService::NfcSwitchEventHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event)
262 {
263     if (event == nullptr) {
264         ErrorLog("event nullptr.");
265         return;
266     }
267     if (nfcService_.expired()) {
268         ErrorLog("nfc service expired.");
269         return;
270     }
271     int eventId = static_cast<int>(event->GetInnerEventId());
272     InfoLog("process eventid = [%{public}d]", eventId);
273     if (!CheckNfcState(eventId)) {
274         return;
275     }
276     switch (eventId) {
277         case KITS::TASK_INITIALIZE:
278             nfcService_.lock()->DoInitialize();
279             break;
280         case KITS::TASK_TURN_ON:
281             nfcService_.lock()->DoTurnOn();
282             break;
283         case KITS::TASK_TURN_OFF:
284             nfcService_.lock()->DoTurnOff();
285             break;
286         default:
287             WarnLog("ProcessEvent, unknown eventId %{public}d", eventId);
288             break;
289     }
290     InfoLog("process eventid finished.");
291 }
292 
IsMaxSwitchRetryTime()293 bool NfcService::IsMaxSwitchRetryTime()
294 {
295     int abortRetryTime = ExternalDepsProxy::GetInstance().NfcDataGetInt(ABORT_RETRY_TIME);
296     InfoLog("abort retry time = %{public}d", abortRetryTime);
297     if (abortRetryTime < MAX_ABORT_RETRY_TIME) {
298         ExternalDepsProxy::GetInstance().NfcDataSetInt(ABORT_RETRY_TIME, abortRetryTime + 1);
299         return false;
300     } else {
301         ErrorLog("max retry time reached, turn on err, unload SA in 5 minutes.");
302         UpdateNfcState(KITS::STATE_OFF);
303         ExternalDepsProxy::GetInstance().NfcDataSetInt(ABORT_RETRY_TIME, 0);
304         SetupUnloadNfcSaTimer(true);
305 
306         // write hisysevent
307         NfcFailedParams err;
308         ExternalDepsProxy::GetInstance().BuildFailedParams(
309             err, MainErrorCode::NFC_SWITCH_RETRY_MAX_TIME, SubErrorCode::DEFAULT_ERR_DEF);
310         ExternalDepsProxy::GetInstance().WriteNfcFailedHiSysEvent(&err);
311         return true;
312     }
313 }
314 
DoTurnOn()315 bool NfcService::DoTurnOn()
316 {
317     InfoLog("Nfc do turn on: current state %{public}d", nfcState_);
318 
319     CancelUnloadNfcSaTimer();
320     UpdateNfcState(KITS::STATE_TURNING_ON);
321     NotifyMessageToVendor(KITS::NFC_SWITCH_KEY, std::to_string(KITS::STATE_TURNING_ON));
322 
323     if (IsMaxSwitchRetryTime()) {
324         ErrorLog("max retry time reached, do not try to open nfc.");
325         return false;
326     }
327 
328     NfcWatchDog nfcWatchDog("DoTurnOn", WAIT_MS_INIT, nciNfccProxy_);
329     nfcWatchDog.Run();
330     // Routing WakeLock acquire
331     if (!nciNfccProxy_->Initialize()) {
332         ErrorLog("Nfc do turn on err");
333         UpdateNfcState(KITS::STATE_OFF);
334         // Routing Wake Lock release
335         nfcWatchDog.Cancel();
336         // Do turn on failed, openRequestCnt and openFailedCnt = 1, others = 0
337         ExternalDepsProxy::GetInstance().WriteOpenAndCloseHiSysEvent(DEFAULT_COUNT, DEFAULT_COUNT,
338             NOT_COUNT, NOT_COUNT);
339         // Record failed event
340         ExternalDepsProxy::GetInstance().WriteNfcFailedHiSysEvent(MainErrorCode::NFC_OPEN_FAILED,
341             SubErrorCode::NCI_RESP_ERROR);
342         NotifyMessageToVendor(KITS::NFC_SWITCH_KEY, std::to_string(KITS::STATE_OFF));
343         ExternalDepsProxy::GetInstance().NfcDataSetInt(ABORT_RETRY_TIME, 0);
344         return false;
345     }
346     // Routing Wake Lock release
347     nfcWatchDog.Cancel();
348 
349     ceService_->Initialize();
350     nciVersion_ = nciNfccProxy_->GetNciVersion();
351     InfoLog("Get nci version: ver %{public}d", nciVersion_);
352 
353     UpdateNfcState(KITS::STATE_ON);
354 
355     NfcWatchDog nfcRoutingManagerDog("RoutingManager", WAIT_ROUTING_INIT, nciNfccProxy_);
356     nfcRoutingManagerDog.Run();
357     screenState_ = (int)eventHandler_->CheckScreenState();
358     nciNfccProxy_->SetScreenStatus(screenState_);
359 
360     ceService_->InitConfigAidRouting(true);
361 
362     nfcRoutingManager_->HandleComputeRoutingParams(static_cast<int>(ceService_->GetDefaultPaymentType()));
363     nfcRoutingManager_->HandleCommitRouting();
364     /* Start polling loop */
365     nfcPollingManager_->StartPollingLoop(true);
366     nfcRoutingManagerDog.Cancel();
367     // Do turn on success, openRequestCnt = 1, others = 0
368     ExternalDepsProxy::GetInstance().WriteOpenAndCloseHiSysEvent(DEFAULT_COUNT, NOT_COUNT, NOT_COUNT, NOT_COUNT);
369     // Record success event
370     ExternalDepsProxy::GetInstance().WriteNfcFailedHiSysEvent(
371         MainErrorCode::NFC_OPEN_SUCCEED, SubErrorCode::DEFAULT_ERR_DEF);
372     NotifyMessageToVendor(KITS::NFC_SWITCH_KEY, std::to_string(KITS::STATE_ON));
373     ExternalDepsProxy::GetInstance().NfcDataSetInt(ABORT_RETRY_TIME, 0);
374     InfoLog("Nfc do turn on successfully.");
375     return true;
376 }
377 
DoTurnOff()378 bool NfcService::DoTurnOff()
379 {
380     InfoLog("Nfc do turn off: current state %{public}d", nfcState_);
381     UpdateNfcState(KITS::STATE_TURNING_OFF);
382     NotifyMessageToVendor(KITS::NFC_SWITCH_KEY, std::to_string(KITS::STATE_TURNING_OFF));
383 
384     /* WatchDog to monitor for Deinitialize failed */
385     NfcWatchDog nfcWatchDog("DoTurnOff", WAIT_MS_SET_ROUTE, nciNfccProxy_);
386     nfcWatchDog.Run();
387 
388     bool result = nciNfccProxy_->Deinitialize();
389     InfoLog("Nfcc deinitialize result %{public}d", result);
390 
391     nfcWatchDog.Cancel();
392 
393     nfcPollingManager_->ResetCurrPollingParams();
394     ceService_->Deinitialize();
395     UpdateNfcState(KITS::STATE_OFF);
396 
397     // Do turn off success, closeRequestCnt = 1, others = 0
398     ExternalDepsProxy::GetInstance().WriteOpenAndCloseHiSysEvent(NOT_COUNT, NOT_COUNT, DEFAULT_COUNT, NOT_COUNT);
399     // Record success event
400     ExternalDepsProxy::GetInstance().WriteNfcFailedHiSysEvent(
401         MainErrorCode::NFC_CLOSE_SUCCEED, SubErrorCode::DEFAULT_ERR_DEF);
402     NotifyMessageToVendor(KITS::NFC_SWITCH_KEY, std::to_string(KITS::STATE_OFF));
403     ExternalDepsProxy::GetInstance().NfcDataSetInt(ABORT_RETRY_TIME, 0);
404     InfoLog("Nfc do turn off successfully.");
405     return result;
406 }
407 
DoInitialize()408 void NfcService::DoInitialize()
409 {
410     if (isAlreadyInited_) {
411         DebugLog("already initialized.");
412         return;
413     }
414     InfoLog("first time init.");
415     isAlreadyInited_ = true;
416     int nfcStateFromParam = ExternalDepsProxy::GetInstance().GetNfcStateFromParam();
417     if (nfcStateFromParam == KITS::STATE_ON) {
418         if (nfcState_ != KITS::STATE_ON) {
419             InfoLog("should turn nfc on.");
420             ExecuteTask(KITS::TASK_TURN_ON);
421         }
422     } else {
423         // 5min later unload nfc_service, if nfc state is off
424         WarnLog("nfc state not on, unload SA in 5 minutes.");
425         SetupUnloadNfcSaTimer(false);
426     }
427 }
428 
SetRegisterCallBack(const sptr<INfcControllerCallback> & callback,const std::string & type,Security::AccessToken::AccessTokenID callerToken)429 int NfcService::SetRegisterCallBack(const sptr<INfcControllerCallback> &callback,
430     const std::string& type, Security::AccessToken::AccessTokenID callerToken)
431 {
432     InfoLog("NfcService SetRegisterCallBack");
433     if (callback == nullptr) {
434         ErrorLog("register callback is nullptr");
435         return KITS::ERR_NFC_PARAMETERS;
436     }
437     std::lock_guard<std::mutex> lock(mutex_);
438     bool isExist = false;
439     NfcStateRegistryRecord record;
440     InfoLog("RecordsSize=%{public}zu,isExist=%{public}d,type=%{public}s",
441         stateRecords_.size(), isExist, type.c_str());
442     for (size_t i = 0; i < stateRecords_.size(); i++) {
443         record = stateRecords_[i];
444         InfoLog("record.type_=%{public}s", record.type_.c_str());
445         if (record.type_.compare(type) == 0 && record.callerToken_ == callerToken) {
446             isExist = true;
447             break;
448         }
449     }
450     InfoLog("isExist=%{public}d", isExist);
451     if (!isExist) {
452         record.type_ = type;
453         record.callerToken_ = callerToken;
454         record.nfcStateChangeCallback_ = callback;
455         stateRecords_.push_back(record);
456         // if callback non-STATE_ON when register, the nfc icon of sceneboard will blink
457         if (nfcState_ == KITS::STATE_ON) {
458             callback->OnNfcStateChanged(nfcState_);
459         }
460     }
461     return KITS::ERR_NONE;
462 }
463 
RemoveRegisterCallBack(const std::string & type,Security::AccessToken::AccessTokenID callerToken)464 int NfcService::RemoveRegisterCallBack(const std::string& type,
465     Security::AccessToken::AccessTokenID callerToken)
466 {
467     InfoLog("NfcService RemoveRegisterCallBack");
468     std::lock_guard<std::mutex> lock(mutex_);
469     int32_t result = KITS::ERR_NFC_PARAMETERS;
470     std::vector<NfcStateRegistryRecord>::iterator it;
471     for (it = stateRecords_.begin(); it != stateRecords_.end(); ++it) {
472         if (it->type_.compare(type) == 0 && it->callerToken_ == callerToken) {
473             InfoLog("NfcService RemoveRegisterCallBack success.");
474             stateRecords_.erase(it);
475             result = KITS::ERR_NONE;
476             break;
477         }
478     }
479     return result;
480 }
481 
RemoveAllRegisterCallBack(Security::AccessToken::AccessTokenID callerToken)482 int NfcService::RemoveAllRegisterCallBack(Security::AccessToken::AccessTokenID callerToken)
483 {
484     InfoLog("NfcService RemoveAllRegisterCallBack");
485     std::lock_guard<std::mutex> lock(mutex_);
486     int32_t result = KITS::ERR_NFC_PARAMETERS;
487     std::vector<NfcStateRegistryRecord>::iterator it;
488     for (it = stateRecords_.begin(); it != stateRecords_.end(); ++it) {
489         if (it->callerToken_ == callerToken) {
490             InfoLog("NfcService RemoveAllRegisterCallBack success.");
491             stateRecords_.erase(it);
492             result = KITS::ERR_NONE;
493             break;
494         }
495     }
496     return result;
497 }
498 
UpdateNfcState(int newState)499 void NfcService::UpdateNfcState(int newState)
500 {
501     InfoLog("Update nfc state: oldState %{public}d, newState %{public}d", nfcState_, newState);
502     std::lock_guard<std::mutex> lock(mutex_);
503     if (newState == nfcState_) {
504         return;
505     }
506     nfcState_ = newState;
507 
508     bool shouldBlockNfcStateChange = ExternalDepsProxy::GetInstance().NfcDataGetBool("vendor_block_nfc_state_change");
509     InfoLog("Update nfc state: shouldBlockNfcStateChange = %{public}d", shouldBlockNfcStateChange);
510     if (!shouldBlockNfcStateChange) {
511         ExternalDepsProxy::GetInstance().UpdateNfcState(newState);
512         ExternalDepsProxy::GetInstance().PublishNfcStateChanged(newState);
513         InfoLog("Update nfc state: nfcState_ %{public}d, newState %{public}d succ", nfcState_, newState);
514 
515         // notify the nfc state changed by callback to JS APP
516         InfoLog("stateRecords_.size[%{public}zu]", stateRecords_.size());
517         for (size_t i = 0; i < stateRecords_.size(); i++) {
518             NfcStateRegistryRecord record = stateRecords_[i];
519             if (record.nfcStateChangeCallback_ != nullptr) {
520                 record.nfcStateChangeCallback_->OnNfcStateChanged(newState);
521             }
522         }
523     } else {
524         InfoLog("Update nfc state: do not notify.");
525     }
526 
527     if (nfcState_ == KITS::STATE_OFF && !shouldBlockNfcStateChange) {
528         // 5min later unload nfc_service, if nfc state is off
529         SetupUnloadNfcSaTimer(true);
530     } else {
531         CancelUnloadNfcSaTimer();
532     }
533 }
534 
GetNfcState()535 int NfcService::GetNfcState()
536 {
537     InfoLog("get nfc state[%{public}d]", nfcState_);
538     return nfcState_;
539 }
540 
GetScreenState()541 int NfcService::GetScreenState()
542 {
543     std::lock_guard<std::mutex> lock(mutex_);
544     return screenState_;
545 }
546 
GetNciVersion()547 int NfcService::GetNciVersion()
548 {
549     return nciVersion_;
550 }
551 
IsNfcEnabled()552 bool NfcService::IsNfcEnabled()
553 {
554     InfoLog("IsNfcEnabled, nfcState_=%{public}d", nfcState_);
555     return (nfcState_ == KITS::STATE_ON);
556 }
557 
HandleShutdown()558 void NfcService::HandleShutdown()
559 {
560     std::lock_guard<std::mutex> lock(mutex_);
561     InfoLog("device is shutting down, nfcState_ = %{public}d", nfcState_);
562     nciNfccProxy_->Shutdown();
563 }
564 
RegNdefMsgCb(const sptr<INdefMsgCallback> & callback)565 bool NfcService::RegNdefMsgCb(const sptr<INdefMsgCallback> &callback)
566 {
567     DebugLog("NfcService::RegNdefMsgCb");
568     if (tagDispatcher_ == nullptr) {
569         ErrorLog("tagDispatcher_ nullptr.");
570         return false;
571     }
572     tagDispatcher_->RegNdefMsgCb(callback);
573     return true;
574 }
575 
SetupUnloadNfcSaTimer(bool shouldRestartTimer)576 void NfcService::SetupUnloadNfcSaTimer(bool shouldRestartTimer)
577 {
578     TimeOutCallback timeoutCallback = [this]() { UnloadNfcSa(); };
579     if (unloadStaSaTimerId != 0) {
580         if (!shouldRestartTimer) {
581             InfoLog("timer already started.");
582             return;
583         }
584         NfcTimer::GetInstance()->UnRegister(unloadStaSaTimerId);
585         unloadStaSaTimerId = 0;
586     }
587     NfcTimer::GetInstance()->Register(timeoutCallback, unloadStaSaTimerId, TIMEOUT_UNLOAD_NFC_SA);
588 }
589 
CancelUnloadNfcSaTimer()590 void NfcService::CancelUnloadNfcSaTimer()
591 {
592     if (unloadStaSaTimerId != 0) {
593         NfcTimer::GetInstance()->UnRegister(unloadStaSaTimerId);
594         unloadStaSaTimerId = 0;
595     }
596 }
597 
NotifyMessageToVendor(int key,const std::string & value)598 void NfcService::NotifyMessageToVendor(int key, const std::string &value)
599 {
600     if (nciNfccProxy_ == nullptr) {
601         ErrorLog("nciNfccProxy_ nullptr.");
602         return;
603     }
604     nciNfccProxy_->NotifyMessageToVendor(key, value);
605 }
606 }  // namespace NFC
607 }  // namespace OHOS
608