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_watch_dog.h"
16 #include <chrono>
17 #include "loghelper.h"
18
19 namespace OHOS {
20 namespace NFC {
NfcWatchDog(const std::string & threadName,int timeout,std::weak_ptr<NCI::INciNfccInterface> nfccProxy)21 NfcWatchDog::NfcWatchDog(const std::string& threadName, int timeout, std::weak_ptr<NCI::INciNfccInterface> nfccProxy)
22 : threadName_(threadName), timeout_(timeout), canceled_(false), thread_(nullptr), nciNfccProxy_(nfccProxy)
23 {
24 }
25
~NfcWatchDog()26 NfcWatchDog::~NfcWatchDog()
27 {
28 if (thread_ && thread_->joinable()) {
29 conditionVariable_.notify_one();
30 thread_->join();
31 }
32 }
33
MainLoop()34 void NfcWatchDog::MainLoop()
35 {
36 std::unique_lock<std::mutex> lock(mutex_);
37 conditionVariable_.wait_for(lock, std::chrono::milliseconds(timeout_), [this] { return canceled_; });
38 if (canceled_) {
39 return;
40 }
41 // If Routing Wake Lock is held, Routing Wake Lock release. Watchdog triggered, release lock before aborting.
42 if (nciNfccProxy_.expired()) {
43 return;
44 }
45 InfoLog("Watchdog triggered, aborting.");
46 nciNfccProxy_.lock()->Abort();
47 }
48
Run()49 void NfcWatchDog::Run()
50 {
51 thread_ = std::make_unique<std::thread>(&NfcWatchDog::MainLoop, this);
52 }
53
Cancel()54 void NfcWatchDog::Cancel()
55 {
56 std::unique_lock<std::mutex> lock(mutex_);
57 canceled_ = true;
58 conditionVariable_.notify_one();
59 }
60 } // namespace NFC
61 } // namespace OHOS
62