1 /*
2  * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved.
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 <thread>
17 #include <iostream>
18 #include <chrono>
19 #include <cstdlib>
20 #include <unistd.h>
21 #include <mutex>
22 #include "include/heartbeat.h"
23 #include "include/sp_utils.h"
24 #include "sp_log.h"
25 #include "include/startup_delay.h"
26 #include "include/common.h"
27 namespace OHOS {
28 namespace SmartPerf {
KillSpId()29 void Heartbeat::KillSpId()
30 {
31     std::string str;
32     std::string resultPid;
33     std::string cmd = CMD_COMMAND_MAP.at(CmdCommand::PIDOF_SP);
34     SPUtils::LoadCmd(cmd, resultPid);
35     std::vector<std::string> vec;
36     std::string token;
37     size_t pos = resultPid.find(' ');
38     do {
39         token = resultPid.substr(0, pos);
40         vec.push_back(token);
41         resultPid.erase(0, pos + 1);
42     } while ((pos = resultPid.find(' ')) != std::string::npos);
43     if (vec.size() > 0) {
44         std::string killCmd = CMD_COMMAND_MAP.at(CmdCommand::KILL_CMD);
45         for (size_t i = 0; i < vec.size(); i++) {
46             SPUtils::LoadCmd(killCmd + vec[i], str);
47         }
48     }
49 }
50 
HeartbeatRule()51 void Heartbeat::HeartbeatRule()
52 {
53     while (isrunning) {
54         auto end = std::chrono::steady_clock::now();
55         LOGI("endTime: %lld", std::chrono::time_point_cast<std::chrono::microseconds>(end).time_since_epoch().count());
56         auto duration = std::chrono::duration_cast<std::chrono::seconds>(end - updateStart).count();
57         LOGI("ListeningTimeJitter: %lld", duration);
58         if (duration > timeout) {
59             LOGI("editor connect timeout have Disconnected successfully!");
60             KillSpId();
61         }
62         sleep(checkMessageTime);
63     }
64 }
65 
UpdatestartTime()66 void Heartbeat::UpdatestartTime()
67 {
68     std::unique_lock<std::mutex> lock(mtx);
69     updateStart = std::chrono::steady_clock::now();
70     LOGI("Listening to messages from edtior or device");
71     lock.unlock();
72 }
73 }
74 }