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