From 148318a860150f0a7cc30ef624bd770540943abc Mon Sep 17 00:00:00 2001 From: wangjuntao Date: Tue, 22 Jul 2025 20:14:32 +0800 Subject: [PATCH 1/3] add sp device cmd code Signed-off-by: wangjuntao --- .../cmds/include/client_control.h | 42 +++ .../cmds/include/control_call_cmd.h | 47 +++ .../cmds/include/editor_command.h | 26 ++ .../cmds/include/smartperf_command.h | 106 +++++++ .../cmds/src/client_control.cpp | 119 ++++++++ .../cmds/src/control_call_cmd.cpp | 271 ++++++++++++++++++ .../cmds/src/editor_command.cpp | 31 ++ .../cmds/src/smartperf_command.cpp | 172 +++++++++++ 8 files changed, 814 insertions(+) create mode 100644 smartperf_device/device_command/cmds/include/client_control.h create mode 100644 smartperf_device/device_command/cmds/include/control_call_cmd.h create mode 100644 smartperf_device/device_command/cmds/include/editor_command.h create mode 100644 smartperf_device/device_command/cmds/include/smartperf_command.h create mode 100644 smartperf_device/device_command/cmds/src/client_control.cpp create mode 100644 smartperf_device/device_command/cmds/src/control_call_cmd.cpp create mode 100644 smartperf_device/device_command/cmds/src/editor_command.cpp create mode 100644 smartperf_device/device_command/cmds/src/smartperf_command.cpp diff --git a/smartperf_device/device_command/cmds/include/client_control.h b/smartperf_device/device_command/cmds/include/client_control.h new file mode 100644 index 00000000..d76df53e --- /dev/null +++ b/smartperf_device/device_command/cmds/include/client_control.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef CLIENTCONTROL_H +#define CLIENTCONTROL_H +#include +#include +namespace OHOS { +namespace SmartPerf { +class ClientControl { +public: + int SocketStart(const std::string &args); + int SocketStop(); + int InitSocket(); + void StartSPDaemon() const; + int CloseSocket(); + +private: + int clientSocket = 0; + struct sockaddr_in serverAddress; + static const int arraySize = 1024; + char buffer[arraySize] = {0}; + int protNumber = 8284; + std::string message = "init:::-SESSIONID 1 -INTERVAL 1000 "; + const char *message1 = "start:::"; + const char *message2 = "stop::"; + int numBuff = 1024; +}; +} +} +#endif \ No newline at end of file diff --git a/smartperf_device/device_command/cmds/include/control_call_cmd.h b/smartperf_device/device_command/cmds/include/control_call_cmd.h new file mode 100644 index 00000000..f2583cc2 --- /dev/null +++ b/smartperf_device/device_command/cmds/include/control_call_cmd.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef CONTROL_CALL_CMD_H +#define CONTROL_CALL_CMD_H +#include +#include +#include +#include +#include +namespace OHOS { +namespace SmartPerf { +class ControlCallCmd { +public: + double CompleteTime(); + double ResponseTime(); + std::string GetResult(const std::vector& v); + std::string GetFrame(); + std::string GetAppStartTime() const; + std::string SlideList(); + std::string TimeDelay(); + void IsohTest(const std::vector& v); + +private: + bool isOhTest = false; + std::string result = ""; + int ohType = 4; + int typeName = 2; + double time = 0.0; + double noNameType = -1.0; + std::ostringstream stream; + int two = 2; +}; +} +} +#endif // SMARTPERF_COMMAND_H \ No newline at end of file diff --git a/smartperf_device/device_command/cmds/include/editor_command.h b/smartperf_device/device_command/cmds/include/editor_command.h new file mode 100644 index 00000000..7f485871 --- /dev/null +++ b/smartperf_device/device_command/cmds/include/editor_command.h @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef EDITOR_COMMAND_H +#define EDITOR_COMMAND_H +namespace OHOS { +namespace SmartPerf { +class EditorCommand { +public: + EditorCommand(int argc, const std::vector &v); + ~EditorCommand() {}; +}; +} +} +#endif // SMARTPERF_COMMAND_H \ No newline at end of file diff --git a/smartperf_device/device_command/cmds/include/smartperf_command.h b/smartperf_device/device_command/cmds/include/smartperf_command.h new file mode 100644 index 00000000..e3606977 --- /dev/null +++ b/smartperf_device/device_command/cmds/include/smartperf_command.h @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SMARTPERF_COMMAND_H +#define SMARTPERF_COMMAND_H + +#include +#include +#include "common.h" +#include "sp_utils.h" +#include "GpuCounter.h" +#include "GameEvent.h" +#include "task_manager.h" + +namespace OHOS { +namespace SmartPerf { +class SmartPerfCommand { +public: + const std::string smartPerfExeName = "SP_daemon"; + const std::string smartPerfMsgErr = "error input!\n use command '--help' get more information\n"; + const std::string smartPerfMsg = "OpenHarmony performance testing tool SmartPerf command-line version\n" + "Usage: SP_daemon [options] [arguments]\n\n" + "options:\n" + " -N set the collection times(default value is 0) range[1,2147483647], for example: -N 10 \n" + " -PKG set package name, must add, for example: -PKG ohos.samples.ecg \n" + " -PID set process pid, must add, for example: -PID 3568 \n" + " -threads get threads, must add -PID or -PKG for example: \n" + "\t\t -threads -PID 3568 or -threads -PKG ohos.samples.ecg \n" + " -fds get file descriptor, must add -PID or -PKG for example: \n" + "\t\t -fds -PID 3568 or -fds -PKG ohos.samples.ecg \n" + " -c get device CPU frequency and CPU usage, process CPU usage and CPU load .. \n" + " -ci get cpu instructions and cycles \n" + " -g get device GPU frequency and GPU load \n" + " -f get app refresh fps(frames per second) and fps jitters and refreshrate \n" + " -profilerfps get refresh fps and timestamp \n" + " -sections set collection time period(using with profilerfps)\n" + " -t get remaining battery power and temperature.. \n" + " -p get battery power consumption and voltage(Not supported by some devices) \n" + " -print start mode print log \n" + " -r get process memory and total memory \n" + " -snapshot get screen capture\n" + " -net get uplink and downlink traffic\n" + " -start collection start command \n" + " -stop collection stop command \n" + " -VIEW set layler, for example: -VIEW DisplayNode \n" + " -OUT set csv output path.\n" + " -d get device DDR information \n" + " -screen get screen resolution \n" + " -deviceinfo get device information \n" + " -server start a process to listen to the socket message of the start and stop commands \n" + " -clear clear the process ID \n" + " -ohtestfps used by the vilidator to obtain the fps, the collection times can be set \n" + " -editorServer start a process to listen to the socket message of the editor \n" + " -recordcapacity get the battery level difference \n" + " --version get version \n" + " --help get help \n" + " -editor scenario-based collection identifier, parameter configuration items can be added later \n" + " responseTime get the page response delay after an application is operated \n" + " completeTime get the page completion delay after an application is operated \n" + " fpsohtest used by the vilidator to obtain the fps \n" + "example1:\n" + "SP_daemon -N 20 -c -g -t -p -r -net -snapshot -d \n" + "SP_daemon -N 20 -PKG ohos.samples.ecg -c -g -t -p -f -r -net -snapshot -d \n" + "SP_daemon -start -c \n" + "SP_daemon -stop \n" + "example2: These parameters need to be used separately \n" + "SP_daemon -screen \n" + "SP_daemon -deviceinfo \n" + "SP_daemon -server \n" + "SP_daemon -clear \n" + "SP_daemon -ohtestfps 10 \n" + "SP_daemon -editorServer \n" + "SP_daemon -recordcapacity \n" + "example3: These parameters need to be used separately \n" + "SP_daemon -editor responseTime ohos.samples.ecg app name \n" + "SP_daemon -editor completeTime ohos.samples.ecg app name \n" + "SP_daemon -editor fpsohtest \n"; + + const size_t oneParam = 1; + const size_t twoParam = 2; + const size_t threeParamMore = 3; + const size_t serverCommandLength = 14; // -deviceServer: 与 -editorServer: 的长度 + explicit SmartPerfCommand(std::vector& argv); + ~SmartPerfCommand() {}; + static void InitSomething(); + std::string ExecCommand(); + void HelpCommand(CommandHelp type, const std::string& token) const; + void CreateSocketThread() const; + void DeviceServer(int isNeedDaemon) const; + TaskManager taskMgr_; +}; +} +} +#endif // SMARTPERF_COMMAND_H \ No newline at end of file diff --git a/smartperf_device/device_command/cmds/src/client_control.cpp b/smartperf_device/device_command/cmds/src/client_control.cpp new file mode 100644 index 00000000..11af5dce --- /dev/null +++ b/smartperf_device/device_command/cmds/src/client_control.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include +#include +#include "include/client_control.h" +#include "include/sp_utils.h" +#include "include/startup_delay.h" +#include "include/sp_log.h" +#include "include/common.h" +namespace OHOS { +namespace SmartPerf { +int ClientControl::SocketStart(const std::string &args) +{ + std::string messageInit = message + args; + int resultId = OHOS::SmartPerf::ClientControl::InitSocket(); + if (resultId == 1) { + LOGE("ClientControl::InitSocket() error(%d)", resultId); + return resultId; + } + send(clientSocket, messageInit.c_str(), strlen(messageInit.c_str()), 0); + LOGD("start-stop messageInit : %s", messageInit.c_str()); + read(clientSocket, buffer, numBuff); + LOGD("start-stop recv : %s", buffer); + send(clientSocket, message1, strlen(message1), 0); + LOGD("start-stop send : %s", message1); + read(clientSocket, buffer, numBuff); + LOGD("start-stop recv : %s", buffer); + char dest[arraySize] = {0}; + size_t i; + for (i = 0; buffer[i] != '\0' && i < arraySize - 1; i++) { + dest[i] = buffer[i]; + } + dest[i] = '\0'; + if (strcmp(dest, "start::True") == 0) { + std::cout << "SP_daemon Collection begins" << std::endl; + OHOS::SmartPerf::ClientControl::CloseSocket(); + } else { + std::cout << "SP_daemon Collection begins failed" << std::endl; + OHOS::SmartPerf::StartUpDelay sd; + sd.GetSpClear(false); + } + LOGD("ClientControl::SocketStart() ok"); + return 0; +} +int ClientControl::SocketStop() +{ + OHOS::SmartPerf::ClientControl::InitSocket(); + send(clientSocket, message2, strlen(message2), 0); + read(clientSocket, buffer, numBuff); + char dest[arraySize] = {0}; + size_t i; + for (i = 0; buffer[i] != '\0' && i < arraySize - 1; i++) { + dest[i] = buffer[i]; + } + dest[i] = '\0'; + if (strcmp(dest, "stop::True") == 0) { + std::cout << "SP_daemon Collection ended" << std::endl; + std::cout << "Output Path: data/local/tmp/smartperf/1/t_index_info.csv" << std::endl; + OHOS::SmartPerf::StartUpDelay sd; + OHOS::SmartPerf::ClientControl::CloseSocket(); + sd.GetSpClear(false); + } else { + std::cout << "SP_daemon Collection ended failed" << std::endl; + } + LOGD("ClientControl::SocketStop() ok"); + return 0; +} +int ClientControl::InitSocket() +{ + clientSocket = socket(AF_INET, SOCK_STREAM, 0); + if (clientSocket == -1) { + LOGE("Faild to create socket"); + return -1; + } + serverAddress.sin_family = AF_INET; + serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1"); + serverAddress.sin_port = htons(protNumber); + if (connect(clientSocket, reinterpret_cast(&serverAddress), sizeof(serverAddress)) < 0) { + OHOS::SmartPerf::StartUpDelay sd; + sd.GetSpClear(false); + LOGE("Failed to connect to server"); + return 1; + } + LOGD("ClientControl::SocketInit() ok"); + return 0; +} +void ClientControl::StartSPDaemon() const +{ + std::string result = ""; + std::string server = CMD_COMMAND_MAP.at(CmdCommand::SERVER); + SPUtils::LoadCmd(server, result); + sleep(1); +} +int ClientControl::CloseSocket() +{ + shutdown(clientSocket, SHUT_RD); + close(clientSocket); + clientSocket = -1; + LOGD("ClientControl::CloseSocket() ok"); + return 0; +} +} +} \ No newline at end of file diff --git a/smartperf_device/device_command/cmds/src/control_call_cmd.cpp b/smartperf_device/device_command/cmds/src/control_call_cmd.cpp new file mode 100644 index 00000000..cdf194ba --- /dev/null +++ b/smartperf_device/device_command/cmds/src/control_call_cmd.cpp @@ -0,0 +1,271 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "unistd.h" +#include +#include +#include +#include +#include +#include +#include +#include "include/control_call_cmd.h" +#include "include/startup_delay.h" +#include "include/sp_utils.h" +#include "include/parse_click_complete_trace.h" +#include "include/parse_click_response_trace.h" +#include "include/parse_radar.h" +#include "include/parse_slide_fps_trace.h" +#include "include/sp_log.h" +#include "include/stalling_rate_trace.h" +#include "common.h" + +namespace OHOS { +namespace SmartPerf { +std::string ControlCallCmd::GetResult(const std::vector& v) +{ + IsohTest(v); + if (v[typeName] == "responseTime") { + time = SmartPerf::ControlCallCmd::ResponseTime(); + } else if (v[typeName] == "completeTime") { + time = SmartPerf::ControlCallCmd::CompleteTime(); + } else if (v[typeName] == "fpsohtest") { + std::string ohTestFps = CMD_COMMAND_MAP.at(CmdCommand::OHTESTFPS); + SPUtils::LoadCmd(ohTestFps, result); + } else if (v[typeName] == "frameLoss") { + result = SmartPerf::ControlCallCmd::GetFrame(); + } else if (v[typeName] == "appStartTime") { + result = ControlCallCmd::GetAppStartTime(); + } else if (v[typeName] == "slideList") { + result = ControlCallCmd::SlideList(); + } else if (v[typeName] == "timeDelay") { + result = ControlCallCmd::TimeDelay(); + } + if (time == noNameType) { + std::cout << "Startup error, unknown application or application not responding" << std::endl; + } else { + if (time != 0) { + stream << time; + result = "time:" + stream.str() + "ms"; + } + std::cout << result << std::endl; + } + return result; +} +std::string ControlCallCmd::TimeDelay() +{ + OHOS::SmartPerf::ParseClickResponseTrace pcrt; + OHOS::SmartPerf::StartUpDelay sd; + std::string cmdResult; + OHOS::SmartPerf::ParseRadar radar; + OHOS::SmartPerf::StallingRateTrace srt; + std::string rmTrace = CMD_COMMAND_MAP.at(CmdCommand::RM_FILE) + std::string("sp_trace_") + "delay" + ".ftrace"; + SPUtils::LoadCmd(rmTrace, cmdResult); + std::string traceName = std::string("/data/local/tmp/") + std::string("sp_trace_") + "delay" + ".ftrace"; + std::thread thGetTrace = std::thread([&sd, traceName]() { sd.GetTrace(traceName); }); + std::thread thGetHisysId = std::thread([&sd]() { sd.GetHisysIdAndKill(); }); + std::promise promResponse; + std::promise promComplete; + std::promise promRadarFrame; + std::promise promResponseMoved = std::move(promResponse); + std::promise promCompleteMoved = std::move(promComplete); + std::promise promRadarFrameMoved = std::move(promRadarFrame); + std::future futureResponse = promResponseMoved.get_future(); + std::thread([promiseResponse = std::move(promResponseMoved)]() mutable { + promiseResponse.set_value(SPUtils::GetRadarResponse()); + }).detach(); + std::future futureComplete = promCompleteMoved.get_future(); + std::thread([promiseComplete = std::move(promCompleteMoved)]() mutable { + promiseComplete.set_value(SPUtils::GetRadarComplete()); + }).detach(); + std::future futureRadarFrame = promRadarFrameMoved.get_future(); + std::thread([promiseRadarFrame = std::move(promRadarFrameMoved)]() mutable { + promiseRadarFrame.set_value(SPUtils::GetRadarFrame()); + }).detach(); + std::string responseStr = futureResponse.get(); + std::string completeStr = futureComplete.get(); + std::string radarFrameStr = futureRadarFrame.get(); + thGetTrace.join(); + thGetHisysId.join(); + double strResponseTime = radar.ParseRadarResponse(responseStr); + stream << strResponseTime; + double strCompleteTime = radar.ParseRadarComplete(completeStr); + std::ostringstream streamComplete; + streamComplete << strCompleteTime; + std::string maxFrame = radar.ParseRadarMaxFrame(radarFrameStr); + std::string resultTime = "ResponseTime:" + stream.str() + "ms\n" + "CompleteTime:" + streamComplete.str() + "ms\n"; + double rateResult = srt.StallingRateResult(traceName); + std::ostringstream ss; + ss << std::fixed << std::setprecision(two) << rateResult; + return resultTime + "HitchTimeRate:" + ss.str() + "ms/s \n" + maxFrame; +} +std::string ControlCallCmd::SlideList() +{ + OHOS::SmartPerf::ParseClickResponseTrace pcrt; + OHOS::SmartPerf::StartUpDelay sd; + OHOS::SmartPerf::ParseSlideFpsTrace slideFpsTrace; + std::string cmdResult; + OHOS::SmartPerf::ParseRadar radar; + OHOS::SmartPerf::StallingRateTrace srt; + std::string resultStream = ""; + std::string rmTrace = CMD_COMMAND_MAP.at(CmdCommand::RM_FILE) + std::string("sp_trace_") + "fps" + ".ftrace"; + SPUtils::LoadCmd(rmTrace, cmdResult); + std::string traceName = std::string("/data/local/tmp/") + std::string("sp_trace_") + "fps" + ".ftrace"; + if (isOhTest) { + std::thread thGetTrace = std::thread([&sd, traceName]() { sd.GetTrace(traceName); }); + thGetTrace.join(); + time = pcrt.ParseResponseTrace(traceName); + } else { + std::thread thGetTrace = std::thread([&sd, traceName]() { sd.GetTrace(traceName); }); + std::thread thGetHisysId = std::thread([&sd]() { sd.GetHisysIdAndKill(); }); + std::promise promResponse; + std::promise promRadarFrame; + std::promise promResponseMoved = std::move(promResponse); + std::promise promRadarFrameMoved = std::move(promRadarFrame); + std::future futureResponse = promResponseMoved.get_future(); + std::thread([promiseResponse = std::move(promResponseMoved)]() mutable { + promiseResponse.set_value(SPUtils::GetRadarResponse()); + }).detach(); + std::future futureRadarFrame = promRadarFrameMoved.get_future(); + std::thread([promiseRadarFrame = std::move(promRadarFrameMoved)]() mutable { + promiseRadarFrame.set_value(SPUtils::GetRadarFrame()); + }).detach(); + std::string responseStr = futureResponse.get(); + std::string radarFrameStr = futureRadarFrame.get(); + thGetTrace.join(); + thGetHisysId.join(); + double responseTime = radar.ParseRadarResponse(responseStr); + stream << responseTime; + std::string maxFrame = radar.ParseRadarMaxFrame(radarFrameStr); + std::string responseSlide = "ResponseTime:" + stream.str() + "ms\n"; + double sFps = slideFpsTrace.ParseSlideFpsTraceNoh(traceName); + std::ostringstream streamFps; + streamFps << sFps; + double stallingRateResult = srt.StallingRateResult(traceName); + std::ostringstream ss; + ss << std::fixed << std::setprecision(two) << stallingRateResult; + std::string ssResult = ss.str(); + std::string hitchTimeRate = "HitchTimeRate:" + ssResult + "ms/s \n"; + resultStream = "FPS:" + streamFps.str() + "fps\n" + responseSlide + hitchTimeRate + maxFrame; + } + return resultStream; +} +std::string ControlCallCmd::GetFrame() +{ + OHOS::SmartPerf::StartUpDelay sd; + std::string cmdResult; + OHOS::SmartPerf::ParseRadar radar; + std::string rmTrace = CMD_COMMAND_MAP.at(CmdCommand::RM_FILE) + std::string("sp_trace_") + "frame" + ".ftrace"; + SPUtils::LoadCmd(rmTrace, cmdResult); + std::string traceName = std::string("/data/local/tmp/") + std::string("sp_trace_") + "frame" + ".ftrace"; + std::thread thGetTrace = std::thread([&sd, traceName]() { sd.GetTrace(traceName); }); + std::thread thGetHisysId = std::thread([&sd]() { sd.GetHisysIdAndKill(); }); + std::string str = SPUtils::GetRadarFrame(); + thGetTrace.join(); + thGetHisysId.join(); + std::string reslut = radar.ParseRadarFrame(str); + return result; +} +double ControlCallCmd::ResponseTime() +{ + OHOS::SmartPerf::ParseClickResponseTrace pcrt; + OHOS::SmartPerf::StartUpDelay sd; + std::string cmdResult; + OHOS::SmartPerf::ParseRadar radar; + std::string rmTrace = CMD_COMMAND_MAP.at(CmdCommand::RM_FILE) + "*" + ".ftrace"; + SPUtils::LoadCmd(rmTrace, cmdResult); + std::string traceName = std::string("/data/local/tmp/") + std::string("sp_trace_") + "response" + ".ftrace"; + if (isOhTest) { + std::thread([&sd, traceName]() { sd.GetTrace(traceName); }).join(); + time = pcrt.ParseResponseTrace(traceName); + } else { + std::thread thGetTrace = std::thread([&sd, traceName]() { sd.GetTrace(traceName); }); + std::thread thGetHisysId = std::thread([&sd]() { sd.GetHisysId(); }); + std::string str = SPUtils::GetRadarResponse(); + thGetTrace.join(); + thGetHisysId.join(); + time = radar.ParseRadarResponse(str); + } + LOGD("ResponseTime = %d", time); + return time; +} +double ControlCallCmd::CompleteTime() +{ + OHOS::SmartPerf::StartUpDelay sd; + OHOS::SmartPerf::ParseClickCompleteTrace pcct; + std::string cmdResult; + OHOS::SmartPerf::ParseRadar radar; + std::string rmTrace = CMD_COMMAND_MAP.at(CmdCommand::RM_FILE) + "*" + ".ftrace"; + SPUtils::LoadCmd(rmTrace, cmdResult); + std::string traceName = std::string("/data/local/tmp/") + std::string("sp_trace_") + "complete" + ".ftrace"; + if (isOhTest) { + std::thread([&sd, traceName]() { sd.GetTrace(traceName); }).join(); + time = pcct.ParseCompleteTrace(traceName); + } else { + std::thread thGetTrace = std::thread([&sd, traceName]() { sd.GetTrace(traceName); }); + std::thread thGetHisysId = std::thread([&sd]() { sd.GetHisysId(); }); + std::string str = SPUtils::GetRadarComplete(); + thGetTrace.join(); + thGetHisysId.join(); + time = radar.ParseRadarComplete(str); + } + LOGD("CompleteTime = %d", time); + return time; +} +std::string ControlCallCmd::GetAppStartTime() const +{ + OHOS::SmartPerf::StartUpDelay sd; + std::string cmdResult; + OHOS::SmartPerf::ParseRadar radar; + OHOS::SmartPerf::StallingRateTrace srt; + std::string rmTrace = CMD_COMMAND_MAP.at(CmdCommand::RM_FILE) + std::string("sp_trace_") + "start" + ".ftrace"; + SPUtils::LoadCmd(rmTrace, cmdResult); + std::string traceName = std::string("/data/local/tmp/") + std::string("sp_trace_") + "start" + ".ftrace"; + std::thread thGetTrace = std::thread([&sd, traceName]() { sd.GetTrace(traceName); }); + std::thread thGetHisysId = std::thread([&sd]() { sd.GetHisysIdAndKill(); }); + + std::promise promRadar; + std::promise promRadarFrame; + std::promise promRadarMoved = std::move(promRadar); + std::promise promRadarFrameMoved = std::move(promRadarFrame); + std::future futureRadar = promRadarMoved.get_future(); + std::thread([promiseRadar = std::move(promRadarMoved)]() mutable { + promiseRadar.set_value(SPUtils::GetRadar()); + }).detach(); + std::future futureRadarFrame = promRadarFrameMoved.get_future(); + std::thread([promiseRadarFrame = std::move(promRadarFrameMoved)]() mutable { + promiseRadarFrame.set_value(SPUtils::GetRadarFrame()); + }).detach(); + std::string radarStr = futureRadar.get(); + std::string radarFrameStr = futureRadarFrame.get(); + thGetTrace.join(); + thGetHisysId.join(); + std::string resultStream = radar.ParseRadarAppStrart(radarStr); + std::string resultStream2 = radar.ParseRadarMaxFrame(radarFrameStr); + double stallingRateResult2 = srt.StallingRateResult(traceName); + std::ostringstream ss; + ss << std::fixed << std::setprecision(two) << stallingRateResult2; + std::string ssResult = ss.str(); + std::string hitchTimeRate = "HitchTimeRate:" + ssResult + "ms/s \n"; + resultStream = resultStream + hitchTimeRate + resultStream2; + return resultStream; +} +void ControlCallCmd::IsohTest(const std::vector& v) +{ + if (v[ohType] == "ohtest") { + isOhTest = true; + } +} +} +} diff --git a/smartperf_device/device_command/cmds/src/editor_command.cpp b/smartperf_device/device_command/cmds/src/editor_command.cpp new file mode 100644 index 00000000..faa6872a --- /dev/null +++ b/smartperf_device/device_command/cmds/src/editor_command.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "unistd.h" +#include +#include +#include +#include "include/editor_command.h" +#include "include/control_call_cmd.h" + + +namespace OHOS { +namespace SmartPerf { +EditorCommand::EditorCommand(int argc, const std::vector &v) +{ + OHOS::SmartPerf::ControlCallCmd controlCallCmd; + controlCallCmd.GetResult(v); +} +} +} diff --git a/smartperf_device/device_command/cmds/src/smartperf_command.cpp b/smartperf_device/device_command/cmds/src/smartperf_command.cpp new file mode 100644 index 00000000..0ed20959 --- /dev/null +++ b/smartperf_device/device_command/cmds/src/smartperf_command.cpp @@ -0,0 +1,172 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include "include/GameEvent.h" +#include "unistd.h" +#include "include/heartbeat.h" +#include "include/sp_utils.h" +#include "include/sp_csv_util.h" +#include "include/sp_profiler_factory.h" +#include "include/sp_thread_socket.h" +#include "include/startup_delay.h" +#include "include/ByTrace.h" +#include "include/smartperf_command.h" +#include "include/sp_log.h" +#include "include/RAM.h" +#include "include/common.h" +#include "include/FPS.h" +#include "include/sp_task.h" +#include "cpu_info.h" +#include "AI_schedule.h" + +namespace OHOS { +namespace SmartPerf { +SmartPerfCommand::SmartPerfCommand(std::vector& argv) +{ + taskMgr_.AddTask(argv); + LOGD("SmartPerfCommand::SmartPerfCommand size(%u)", argv.size()); + if (argv.size() == oneParam) { + SpThreadSocket::GetInstance().SetNeedUdpToken(false); + DeviceServer(true); + } + if (argv.size() == twoParam) { + auto iterator = COMMAND_HELP_MAP.begin(); + while (iterator != COMMAND_HELP_MAP.end()) { + if (iterator->second.compare(argv[1]) == 0) { + HelpCommand(iterator->first, ""); + break; + } + if (argv[1].find("-editorServer") != std::string::npos) { + WLOGI("############################# Found '-editorServer' argument in argv"); + SPUtils::KillStartDaemon(); + const size_t tokenStartPosition = 14; + std::string token = argv[1].substr(tokenStartPosition, argv[1].length() - tokenStartPosition); + HelpCommand(CommandHelp::EDITORSERVER, token); + } else if (argv[1].find("-deviceServer") != std::string::npos) { + WLOGI("############################# Found '-deviceServer' argument in argv"); + std::string token = argv[1].substr(serverCommandLength, argv[1].length() - serverCommandLength); + HelpCommand(CommandHelp::DEVICESERVER, token); + } + ++iterator; + } + } + LOGD("SmartPerfCommand::SmartPerfCommand complete"); +} +void SmartPerfCommand::DeviceServer(int isNeedDaemon) const +{ + EnableWriteLogAndDeleteOldLogFiles(); + OHOS::SmartPerf::StartUpDelay sd; + sd.KillSpProcess(); + std::string pidStr = sd.GetPidByPkg("SP_daemon"); + std::string cmdStr = CMD_COMMAND_MAP.at(CmdCommand::TASKSET); + std::string result = ""; + SPUtils::LoadCmd(cmdStr + pidStr, result); + if (isNeedDaemon) { + daemon(0, 0); + } + CreateSocketThread(); +} +void SmartPerfCommand::HelpCommand(CommandHelp type, const std::string& token) const +{ + LOGD("SmartPerfCommand::HelpCommand type(%d)", type); + if (type == CommandHelp::HELP) { + std::cout << smartPerfMsg << std::endl; + } + if (type == CommandHelp::VERSION) { + std::cout << "Version: " << SPUtils::GetVersion() << std::endl; + } + if (type == CommandHelp::SCREEN) { + std::string result = SPUtils::GetScreen(); + std::cout << result << std::endl; + } + OHOS::SmartPerf::StartUpDelay sd; + if (type == CommandHelp::CLEAR || type == CommandHelp::CLEARALL) { + bool isClearTestServer = (type == CommandHelp::CLEARALL); + sd.GetSpClear(isClearTestServer); + } + if (type == CommandHelp::SERVER || type == CommandHelp::EDITORSERVER) { + sd.ClearOldServer(); + SPUtils::GetTtyDeviceFd(); + std::string pidStr = sd.GetPidByPkg("SP_daemon"); + std::string cmdStr = CMD_COMMAND_MAP.at(CmdCommand::TASKSET); + std::string result = ""; + SPUtils::LoadCmd(cmdStr + pidStr, result); + if (type == CommandHelp::SERVER) { + daemon(0, 0); + } else { + // Editor 拉起 daemon 测试 + EnableWriteLogAndDeleteOldLogFiles(); + if (token.empty()) { + WLOGE("Error: token is empty when setting TCP token."); + return; + } + SpThreadSocket::GetInstance().SetToken(token); + WLOGI("############################# EditorServer Socket Create Start, Ready to Start Collector..."); + } + CreateSocketThread(); + } + if (type == CommandHelp::DEVICESERVER) { + // device 拉起 daemon 测试 + if (token.empty()) { + WLOGE("Error: token is empty when setting UDP token."); + return; + } + SpThreadSocket::GetInstance().SetToken(token); + DeviceServer(false); + WLOGI("############################# DeviceServer Socket Create Start, Ready to Start Collector..."); + } +} + +void SmartPerfCommand::CreateSocketThread() const +{ + InitSomething(); + auto tcpSocket = std::thread([]() { SpThreadSocket::GetInstance().Process(ProtoType::TCP); }); + sleep(1); + auto udpSocket = std::thread([]() { SpThreadSocket::GetInstance().Process(ProtoType::UDP); }); + sleep(1); + auto udpexSocket = std::thread([]() { SpThreadSocket::GetInstance().Process(ProtoType::UDPEX); }); + Heartbeat::GetInstance().UpdatestartTime(); + std::thread([]() { Heartbeat::GetInstance().HeartbeatRule(); }).detach(); + tcpSocket.join(); + udpSocket.join(); + udpexSocket.join(); +} + +std::string SmartPerfCommand::ExecCommand() +{ + RAM &ram = RAM::GetInstance(); + ram.SetFirstFlag(); + taskMgr_.DeleteTask(&AISchedule::GetInstance()); + taskMgr_.InitDataCsv(); + taskMgr_.Start(); + taskMgr_.Wait(); + taskMgr_.Stop(); + taskMgr_.WriteToCSV(); + return std::string("command exec finished!"); +} + +void SmartPerfCommand::InitSomething() +{ + std::string cmdResult; + std::string stat = CMD_COMMAND_MAP.at(CmdCommand::PROC_STAT); + if (SPUtils::LoadCmd(stat, cmdResult)) { + LOGE("SmartPerfCommand::InitSomething Privilege escalation!"); + }; +} +} +} -- Gitee From 0616795b2fcc9e82ab4604b87a7b8c89f6ce3d73 Mon Sep 17 00:00:00 2001 From: wangjuntao Date: Tue, 22 Jul 2025 20:21:56 +0800 Subject: [PATCH 2/3] add sp device sp main and readme Signed-off-by: wangjuntao --- smartperf_device/device_command/README_zh.md | 256 ++++++++++++++++++ smartperf_device/device_command/heartbeat.cpp | 70 +++++ .../device_command/smartperf_main.cpp | 255 +++++++++++++++++ 3 files changed, 581 insertions(+) create mode 100644 smartperf_device/device_command/README_zh.md create mode 100644 smartperf_device/device_command/heartbeat.cpp create mode 100644 smartperf_device/device_command/smartperf_main.cpp diff --git a/smartperf_device/device_command/README_zh.md b/smartperf_device/device_command/README_zh.md new file mode 100644 index 00000000..d94e5aeb --- /dev/null +++ b/smartperf_device/device_command/README_zh.md @@ -0,0 +1,256 @@ +## 简介 +# SP_daemon + +- OpenHarmony性能测试工具SmartPerf 命令行版本,可采集CPU、GPU、Temperature、Power、应用RAM、FPS等指标,通过设置采集指标,对采集数据进行实时打印、导出csv。 + +- 性能较差或无屏幕设备请使用命令行版本,带屏幕的设备且性能较好的设备推荐使用[UI版本](../device_ui/README_zh.md)。 + +## 代码目录 +``` +developtools/smartperf_host/smartperf_device/device_command +├── include # 头文件目录 +├── BUILD.gn # SP_daemon bin打包配置文件 +├── ByTrace.cpp # trace抓取代码文件 +├── Capture.cpp # 截图代码文件 +├── CPU.cpp # CPU采集代码文件 +├── DDR.cpp # DDR采集代码文件 +├── FPS.cpp # FPS采集代码文件 +├── GPU.cpp # GPU采集代码文件 +├── GpuCounter.cpp # GpuCounter采集代码文件 +├── GpuCounterCallback.cpp # GpuCounterCallback采集代码文件 +├── Network.cpp # 网络上下行速率采集代码文件 +├── Power.cpp # 功耗采集代码文件 +├── RAM.cpp # 内存采集代码文件 +├── smartperf_command.cpp # 程序执行文件 +├── smartperf_main.cpp # 程序入口文件 +├── sp_log.cpp # log文件 +├── sp_profiler_factory.cpp # 采集工厂文件 +├── sp_server_socket.cpp # 与SmartPerf hap通讯代码文件 +├── sp_task.cpp # 与SmartPerf editor通讯代码文件 +├── sp_utils.cpp # 工具类 +├── Temperature.cpp # 温度采集代码文件 +``` + +## 约束条件 + SmartPerf应用在3.2系统版本后开始预制使用。 + +## 功能特性 + +**1. 参数说明** +**1.1 基础采集命令参数** + +| 命令 | 功能 |必选| +| :-----| :--------------------- |:-----| +| -N | 设置采集次数(一秒采集一次)|是| +| -PKG | 设置包名 | 否| +| -c | 采集cpu的频点和使用率,设置应用包名:采集整机和应用CPU信息,不设置应用包名:采集整机CPU信息 | 否| +| -g | 采集gpu的频点和负载信息 |否| +| -f | 采集指定应用的fps,必须设置应用包名 |否| +| -profilerfps | 采集当前界面fps |否| +| -t | 采集电池等温度 |否| +| -p | 采集电流 |否| +| -r | 采集内存,设置应用包名:采集整机和应用内存信息,不设置应用包名:采集整机内存信息 |否| +| -snapshot | 屏幕截图 |否| +| -net | 采集网络速率 |否| +| -VIEW | 设置图层,需要先获取应用图层名 |否| +| -screen | 采集屏幕分辨率和刷新率 |否| +| -d | 采集DDR |否| +| -sections| 设置分段采集 |否| + +**1.2 启停采集命令参数** +| 命令 | 功能 |必选| +| :-----| :--------------------- |:-----| +| -start | 开始采集,该命令后可添加基础采集命令 |是| +| -stop | 结束采集,执行后会生成采集报告 |是| +--- + +**2. 使用方式**
+1)目前命令行版本已系统预制,可以进入shell,执行SP_daemon --help查看。 + +```bash +C:\Users\test>hdc_std shell +# SP_daemon --help +OpenHarmony performance testing tool SmartPerf command-line version +Usage: SP_daemon +options: + -N set the collection times(default value is 0) range[1,2147483647], for example: -N 10 + -PKG set package name, must add, for example: -PKG ohos.samples.ecg + -c get device CPU frequency and CPU usage, process CPU usage and CPU load .. + -g get device GPU frequency and GPU load + -f get app refresh fps(frames per second) and fps jitters and refreshrate + -profilerfps get refresh fps and timestamp + -sections set collection time period(using with profilerfps) + -t get remaining battery power and temperature.. + -p get battery power consumption and voltage + -r get process memory and total memory + -snapshot get screen capture + -net get uplink and downlink traffic + -start collection start command + -stop collection stop command + -VIEW set layler, for example: -VIEW DisplayNode + -OUT set csv output path. + -d get device DDR information + -ci get cpu instructions and cycles + -screen get screen resolution + -deviceinfo get device information + -server start a process to listen to the socket message of the start and stop commands + -clear clear the process ID + -ohtestfps used by the vilidator to obtain the fps, the collection times can be set + -editorServer start a process to listen to the socket message of the editor + -recordcapacity get the battery level difference + --version get version + --help get help + -editor scenario-based collection identifier, parameter configuration items can be added later + responseTime get the page response delay after an application is operated + completeTime get the page completion delay after an application is operated + fpsohtest used by the vilidator to obtain the fps + example1: + SP_daemon -N 20 -c -g -t -p -r -net -snapshot -d + SP_daemon -N 20 -PKG ohos.samples.ecg -c -g -t -p -f -r -net -snapshot -d + SP_daemon -start -c + SP_daemon -stop + example2: These parameters need to be used separately + SP_daemon -screen + SP_daemon -deviceinfo + SP_daemon -server + SP_daemon -clear + SP_daemon -ohtestfps + SP_daemon -editorServer + SP_daemon -recordcapacity + example3: These parameters need to be used separately + SP_daemon -editor responseTime ohos.samples.ecg app name + SP_daemon -editor completeTime ohos.samples.ecg app name + SP_daemon -editor fpsohtest + +command exec finished! +# +``` +2)执行示例命令:SP_daemon -N 20 -PKG ohos.samples.ecg -c -g -t -p -f -r -d -net -snapshot +``` +----------------------------------Print START------------------------------------ +order:0 timestamp=1710916175201 +order:1 ProcAppName=ohos.samples.ecg +order:2 ProcCpuLoad=0.0015567 +order:3 ProcCpuUsage=0.000000 +order:4 ProcId=18510 +order:5 ProcSCpuUsage=0.000000 +order:6 ProcUCpuUsage=0.000000 +order:7 cpu0Frequency=418000 +order:8 cpu0Usage=0.000000 +order:9 cpu0idleUsage=0.000000 +order:10 cpu0ioWaitUsage=0.000000 +order:11 cpu0irqUsage=0.000000 +order:12 cpu0niceUsage=0.000000 +order:13 cpu0softIrqUsage=0.000000 +order:14 cpu0systemUsage=0.000000 +order:15 cpu0userUsage=0.000000 +... +order:115 gpuFrequency=279000000 +order:116 gpuload=61.000000 +order:117 Battery=28.000000 +order:118 shell_back=31.529000 +order:119 shell_frame=30.529000 +order:120 shell_front=30.548000 +order:121 soc_thermal=49.624000 +order:122 system_h=30.150000 +order:123 currentNow=278 +order:124 voltageNow=4250532 +order:125 fps=3 +order:126 fpsJitters=881659966;;108846354;;8289583 +order:127 refreshrate=120 +order:128 memAvailable=6354252 +order:129 memFree=5971776 +order:130 memTotal=11530092 +order:131 pss=78045 +order:132 arktsHeapPss=13394 +order:133 gpuPss=280 +order:134 graphicPss=0 +order:135 heapAlloc=48080 +order:136 heapFree=2576 +order:137 heapSize=50788 +order:138 nativeHeapPss=41897 +order:139 privateClean=67232 +order:140 privateDirty=12848 +order:141 sharedClean=76224 +order:142 sharedDirty=12848 +order:143 stackPss=1096 +order:144 swap=0 +order:145 swapPss=0 +order:146 ddrFrequency=1531000000 +order:147 networkDown=0 +order:148 networkUp=0 +order:149 capture=data/local/tmp/capture/screenCap_1711190737580.png + + +----------------------------------Print END-------------------------------------- +----------------------------------Print START------------------------------------ +order:0 timestamp=1710916175201 +order:1 ProcAppName=ohos.samples.ecg +order:2 ProcCpuLoad=0.001379 +order:3 ProcCpuUsage=0.008162 +order:4 ProcId=18510 +order:5 ProcSCpuUsage=0.008162 +order:6 ProcUCpuUsage=0.000000 +order:7 cpu0Frequency=418000 +order:8 cpu0Usage=16.346154 +order:9 cpu0idleUsage=83.653846 +order:10 cpu0ioWaitUsage=0.961538 +order:11 cpu0irqUsage=4.807692 +order:12 cpu0niceUsage=0.000000 +order:13 cpu0softIrqUsage=0.000000 +order:14 cpu0systemUsage=5.769231 +order:15 cpu0userUsage=4.807692 +... +order:115 gpuFrequency=279000000 +order:116 gpuload=61.000000 +order:117 Battery=28.000000 +order:118 shell_back=31.529000 +order:119 shell_frame=30.529000 +order:120 shell_front=30.548000 +order:121 soc_thermal=47.810000 +order:122 system_h=30.200000 +order:123 currentNow=303 +order:124 voltageNow=4251570 +order:125 fps=12 +order:126 fpsJitters=122794860;;8372396;;8375521;;8448958;;16691667;;8357812;;8367188;;8364062;;8383855;;8514062;;8238542;;849062 +order:127 refreshrate=120 +order:128 memAvailable=6370048 +order:129 memFree=5990136 +order:130 memTotal=11530092 +order:131 pss=78217 +order:132 arktsHeapPss=13586 +order:133 gpuPss=280 +order:134 graphicPss=0 +order:135 heapAlloc=48156 +order:136 heapFree=2648 +order:137 heapSize=50780 +order:138 nativeHeapPss=41877 +order:139 privateClean=67404 +order:140 privateDirty=2920 +order:141 sharedClean=76224 +order:142 sharedDirty=12848 +order:143 stackPss=1096 +order:144 swap=0 +order:145 swapPss=0 +order:146 ddrFrequency=1531000000 +order:147 networkDown=0 +order:148 networkUp=0 +order:149 capture=data/local/tmp/capture/screenCap_1711190738589.png + +command exec finished! +# +----------------------------------Print END-------------------------------------- +``` +3)执行完毕后会在data/local/tmp生成data.csv文件,每次执行命令覆盖写入,可导出到本地查看。 +```bash +c:\Users\xxx>hdc file recv data/local/tmp/data.csv D:\ +[I][2024-03-20 18:27:07] HdcFile::TransferSummary success +FileTransfer finish, Size:7306, File count = 1, time:377ms rate:19.38kB/s +--- + +## 发布版本 + +**3.2.0.0版本发布内容:预制SP_daemon bin文件,支持以下功能:**
+1. 支持RK3568、Hi3516。
+2. 支持Shell启动。
+3. 支持采集整机CPU、GPU、POWER、TEMPERATURE、应用的FPS、RAM、CPU等 \ No newline at end of file diff --git a/smartperf_device/device_command/heartbeat.cpp b/smartperf_device/device_command/heartbeat.cpp new file mode 100644 index 00000000..70f27023 --- /dev/null +++ b/smartperf_device/device_command/heartbeat.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include "include/heartbeat.h" +#include "include/sp_utils.h" +#include "sp_log.h" +#include "include/startup_delay.h" +#include "include/common.h" +namespace OHOS { +namespace SmartPerf { +void Heartbeat::KillSpId() +{ + std::string str; + std::string resultPid; + std::string cmd = CMD_COMMAND_MAP.at(CmdCommand::PIDOF_SP); + SPUtils::LoadCmd(cmd, resultPid); + std::vector vec; + std::string token; + size_t pos = resultPid.find(' '); + do { + token = resultPid.substr(0, pos); + vec.push_back(token); + resultPid.erase(0, pos + 1); + } while ((pos = resultPid.find(' ')) != std::string::npos); + if (vec.size() > 0) { + std::string killCmd = CMD_COMMAND_MAP.at(CmdCommand::KILL_CMD); + for (size_t i = 0; i < vec.size(); i++) { + SPUtils::LoadCmd(killCmd + vec[i], str); + } + } +} + +void Heartbeat::HeartbeatRule() +{ + while (isrunning) { + auto end = std::chrono::steady_clock::now(); + auto duration = std::chrono::duration_cast(end - updateStart).count(); + if (duration > timeout) { + LOGD("Socket disconnected!"); + KillSpId(); + } + sleep(checkMessageTime); + } +} + +void Heartbeat::UpdatestartTime() +{ + std::unique_lock lock(mtx); + updateStart = std::chrono::steady_clock::now(); +} + +} +} \ No newline at end of file diff --git a/smartperf_device/device_command/smartperf_main.cpp b/smartperf_device/device_command/smartperf_main.cpp new file mode 100644 index 00000000..9c628c91 --- /dev/null +++ b/smartperf_device/device_command/smartperf_main.cpp @@ -0,0 +1,255 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include "unistd.h" +#include +#include +#include "include/smartperf_command.h" +#include "include/editor_command.h" +#include "include/FPS.h" +#include "include/client_control.h" +#include "include/sp_utils.h" +#include "include/sp_log.h" +#include "include/common.h" +#include "parameters.h" +#include "task_manager.h" +#include "include/startup_delay.h" + +constexpr const char *VERSION_TYPE = "const.logsystem.versiontype"; +static std::string GetOptions(const std::vector &argv) +{ + std::string str = ""; + std::string strFlag; + bool isFill = false; + for (std::size_t i = 0; i < argv.size(); i++) { + if (!isFill) { + strFlag = argv[i]; + if (strFlag.find("SP_daemon") != std::string::npos) { + isFill = true; + } + } else { + str += argv[i]; + if (i + 1 != argv.size()) { + str += " "; + } + } + } + return str; +} +static void KeyInsert(std::set &keysMap) +{ + keysMap.insert("editor"); + keysMap.insert("profilerfps"); + keysMap.insert("start"); + keysMap.insert("stop"); + keysMap.insert("screen"); + keysMap.insert("clear"); + keysMap.insert("clearAll"); + keysMap.insert("server"); + keysMap.insert("sections"); + keysMap.insert("deviceinfo"); + keysMap.insert("ohtestfps"); + keysMap.insert("editorServer"); + keysMap.insert("deviceServer"); + keysMap.insert("recordcapacity"); +} +static bool g_checkCmdParam(std::vector &argv, std::string &errorInfo) +{ + std::string str = GetOptions(argv); + std::set keys; // Includes three parts "SP_daemon" CommandType and CommandHelp + if (str.empty()) { + return true; + } + // 'help' and 'version' start with "--" and are processed separately + if (str.find("--help") != std::string::npos || str.find("--version") != std::string::npos) { + std::vector out; + OHOS::SmartPerf::SPUtils::StrSplit(str, "-", out); + if (out.size() != 1) { + errorInfo = "--help and --version cannot be used together with other options"; + return false; + } else { + return true; + } + } + if (str.find("-PKG") != std::string::npos && str.find("-PID") != std::string::npos) { + errorInfo = "-PKG and -PID cannot be used together with"; + return false; + } + KeyInsert(keys); + // editor 与 device 的拉起命令与 token 一起加入白名单 + if (argv[1].find("editorServer:") != std::string::npos || + argv[1].find("deviceServer:") != std::string::npos + ) { + keys.insert(argv[1].substr(1).c_str()); + } + for (auto& a : OHOS::SmartPerf::COMMAND_MAP) { + keys.insert(a.first.substr(1)); // No prefix required '-' + } + + /* ************The command line for the following parameters is not implemented****************** */ + keys.erase("f1"); + keys.erase("f2"); + keys.erase("fl"); + keys.erase("ftl"); + return OHOS::SmartPerf::SPUtils::VeriyParameter(keys, str, errorInfo); +} + +static void SocketStopCommand() +{ + OHOS::SmartPerf::ClientControl cc; + cc.SocketStop(); +} + +static void RecordCapacity() +{ + const std::string capacityRmPath = "/sys/class/power_supply/Battery/capacity_rm"; + const std::string rkCapacityRmPath = "/data/service/el0/battery/battery/capacity"; + const std::string capacitySavePath = "/data/local/tmp/powerLeftRecord.csv"; + std::string capacityString; + std::ifstream infile(capacitySavePath.c_str()); + if (infile.is_open()) { + std::stringstream buffer; + int capacityLine = 0; + std::string line; + const int MAX_RECORD_COUNT = 100; + buffer << infile.rdbuf(); + capacityString = buffer.str(); + infile.close(); + + while (std::getline(buffer, line)) { + capacityLine++; + } + if (capacityLine == MAX_RECORD_COUNT) { + std::size_t pos = capacityString.find('\n'); + if (pos != std::string::npos) { + capacityString = capacityString.substr(pos + 1); + } + } + } + std::ofstream outFile(capacitySavePath.c_str(), std::ios::out | std::ios::trunc); + if (!outFile.is_open()) { + std::cout << "Error opening capacity file!" << std::endl; + return; + } + std::string recordPower; + auto recordTime = std::to_string(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())); + OHOS::SmartPerf::SPUtils::LoadFile(capacityRmPath, recordPower); + if (recordPower.empty()) { + std::string rkRecordPower; + int maxBat = 60; + OHOS::SmartPerf::SPUtils::LoadFile(rkCapacityRmPath, rkRecordPower); + recordPower = std::to_string(OHOS::SmartPerf::SPUtilesTye::StringToSometype(rkRecordPower) * maxBat); + } + std::cout << "recordTime: " << recordTime << std::endl << "recordPower: " << recordPower << std::endl; + capacityString += recordTime + "," + recordPower; + outFile << capacityString << std::endl; + if (outFile.fail()) { + const int bufSize = 256; + char buf[bufSize] = { 0 }; + std::cout << "Error writing capacity failed:" << strerror_r(errno, buf, bufSize) << std::endl; + } + outFile.close(); +} + +static int ProcessSpecificParameter(int argc, char *argv[], std::vector &vec) +{ + if (argc > 1 && strcmp(argv[1], "-editor") == 0) { + OHOS::SmartPerf::EditorCommand(argc, vec); + return 0; + } else if (argc > 1 && strcmp(argv[1], "-profilerfps") == 0) { + OHOS::SmartPerf::FPS::GetInstance().GetFPS(vec); + return 0; + } else if (argc > 1 && strcmp(argv[1], "-start") == 0) { + OHOS::SmartPerf::SPUtils::KillStartDaemon(); + std::string startStr = ""; + std::string endStr = ""; + std::string pidCmd = OHOS::SmartPerf::CMD_COMMAND_MAP.at(OHOS::SmartPerf::CmdCommand::PIDOF_SP); + OHOS::SmartPerf::SPUtils::LoadCmd(pidCmd, startStr); + OHOS::SmartPerf::ClientControl cc; + cc.StartSPDaemon(); + OHOS::SmartPerf::SPUtils::LoadCmd(pidCmd, endStr); + std::vector startParams; + std::vector endParams; + OHOS::SmartPerf::SPUtils::StrSplit(startStr, " ", startParams); + OHOS::SmartPerf::SPUtils::StrSplit(endStr, " ", endParams); + std::string result; + const int maxExpectedArgs = 100; + for (int i = 2; i < argc && i < maxExpectedArgs; i++) { + result += argv[i]; + if (i != argc - 1) { + result += " "; + } + } + if (startParams.size() == endParams.size()) { + std::cout << "The last collection is interrupted." << std::endl; + std::cout << "SP_daemon -start " << result << " started collecting..." << std::endl; + } + cc.SocketStart(result); + std::cout << "command exec finished!" << std::endl; + return 0; + } else if (argc > 1 && strcmp(argv[1], "-stop") == 0) { + SocketStopCommand(); + std::cout << "command exec finished!" << std::endl; + return 0; + } else if (argc > 1 && strcmp(argv[1], "-deviceinfo") == 0) { + std::cout << OHOS::SmartPerf::SPUtils::GetDeviceInfoMap() << std::endl; + return 0; + } else if (argc > 1 && strcmp(argv[1], "-ohtestfps") == 0) { + OHOS::SmartPerf::FPS::GetInstance().GetOhFps(vec); + return 0; + } else if (argc > 1 && strcmp(argv[1], "-recordcapacity") == 0) { + RecordCapacity(); + return 0; + } + + return 1; +} + +int main(int argc, char *argv[]) +{ + if (OHOS::system::GetParameter(VERSION_TYPE, "Unknown") != "beta") { + if (!OHOS::system::GetBoolParameter("const.security.developermode.state", true)) { + std::cout << "Not a development mode state" << std::endl; + return 0; + } + } + const int maxExpectedArgs = 100; + std::string errorInfo; + std::vector vec; + if (argc < 0 || argc > maxExpectedArgs) { + std::cout << "Invalid argument count" << std::endl; + return -1; + } + for (int i = 0; i < argc; i++) { + vec.push_back(argv[i]); + } + if (!g_checkCmdParam(vec, errorInfo)) { + std::cout << "SP_daemon:" << errorInfo << std::endl << + "Usage: SP_daemon [options] [arguments]" << std::endl << std::endl << + "Try `SP_daemon --help' for more options." << std::endl; + return 0; + } + OHOS::SmartPerf::SPUtils::SetRkFlag(); + if (ProcessSpecificParameter(argc, argv, vec) == 0) { + return 0; + } + + OHOS::SmartPerf::SmartPerfCommand cmd(vec); + OHOS::SmartPerf::StartUpDelay sd; + sd.KillSpProcess(); + std::cout << cmd.ExecCommand() << std::endl; + return 0; +} -- Gitee From e4e941e9873577ec7205899f229b15178a2af310 Mon Sep 17 00:00:00 2001 From: wangjuntao Date: Tue, 22 Jul 2025 20:25:05 +0800 Subject: [PATCH 3/3] delete sp device sp main and readme Signed-off-by: wangjuntao --- smartperf_device/device_command/README_zh.md | 256 ------------------ smartperf_device/device_command/heartbeat.cpp | 70 ----- .../device_command/smartperf_main.cpp | 255 ----------------- 3 files changed, 581 deletions(-) delete mode 100644 smartperf_device/device_command/README_zh.md delete mode 100644 smartperf_device/device_command/heartbeat.cpp delete mode 100644 smartperf_device/device_command/smartperf_main.cpp diff --git a/smartperf_device/device_command/README_zh.md b/smartperf_device/device_command/README_zh.md deleted file mode 100644 index d94e5aeb..00000000 --- a/smartperf_device/device_command/README_zh.md +++ /dev/null @@ -1,256 +0,0 @@ -## 简介 -# SP_daemon - -- OpenHarmony性能测试工具SmartPerf 命令行版本,可采集CPU、GPU、Temperature、Power、应用RAM、FPS等指标,通过设置采集指标,对采集数据进行实时打印、导出csv。 - -- 性能较差或无屏幕设备请使用命令行版本,带屏幕的设备且性能较好的设备推荐使用[UI版本](../device_ui/README_zh.md)。 - -## 代码目录 -``` -developtools/smartperf_host/smartperf_device/device_command -├── include # 头文件目录 -├── BUILD.gn # SP_daemon bin打包配置文件 -├── ByTrace.cpp # trace抓取代码文件 -├── Capture.cpp # 截图代码文件 -├── CPU.cpp # CPU采集代码文件 -├── DDR.cpp # DDR采集代码文件 -├── FPS.cpp # FPS采集代码文件 -├── GPU.cpp # GPU采集代码文件 -├── GpuCounter.cpp # GpuCounter采集代码文件 -├── GpuCounterCallback.cpp # GpuCounterCallback采集代码文件 -├── Network.cpp # 网络上下行速率采集代码文件 -├── Power.cpp # 功耗采集代码文件 -├── RAM.cpp # 内存采集代码文件 -├── smartperf_command.cpp # 程序执行文件 -├── smartperf_main.cpp # 程序入口文件 -├── sp_log.cpp # log文件 -├── sp_profiler_factory.cpp # 采集工厂文件 -├── sp_server_socket.cpp # 与SmartPerf hap通讯代码文件 -├── sp_task.cpp # 与SmartPerf editor通讯代码文件 -├── sp_utils.cpp # 工具类 -├── Temperature.cpp # 温度采集代码文件 -``` - -## 约束条件 - SmartPerf应用在3.2系统版本后开始预制使用。 - -## 功能特性 - -**1. 参数说明** -**1.1 基础采集命令参数** - -| 命令 | 功能 |必选| -| :-----| :--------------------- |:-----| -| -N | 设置采集次数(一秒采集一次)|是| -| -PKG | 设置包名 | 否| -| -c | 采集cpu的频点和使用率,设置应用包名:采集整机和应用CPU信息,不设置应用包名:采集整机CPU信息 | 否| -| -g | 采集gpu的频点和负载信息 |否| -| -f | 采集指定应用的fps,必须设置应用包名 |否| -| -profilerfps | 采集当前界面fps |否| -| -t | 采集电池等温度 |否| -| -p | 采集电流 |否| -| -r | 采集内存,设置应用包名:采集整机和应用内存信息,不设置应用包名:采集整机内存信息 |否| -| -snapshot | 屏幕截图 |否| -| -net | 采集网络速率 |否| -| -VIEW | 设置图层,需要先获取应用图层名 |否| -| -screen | 采集屏幕分辨率和刷新率 |否| -| -d | 采集DDR |否| -| -sections| 设置分段采集 |否| - -**1.2 启停采集命令参数** -| 命令 | 功能 |必选| -| :-----| :--------------------- |:-----| -| -start | 开始采集,该命令后可添加基础采集命令 |是| -| -stop | 结束采集,执行后会生成采集报告 |是| ---- - -**2. 使用方式**
-1)目前命令行版本已系统预制,可以进入shell,执行SP_daemon --help查看。 - -```bash -C:\Users\test>hdc_std shell -# SP_daemon --help -OpenHarmony performance testing tool SmartPerf command-line version -Usage: SP_daemon -options: - -N set the collection times(default value is 0) range[1,2147483647], for example: -N 10 - -PKG set package name, must add, for example: -PKG ohos.samples.ecg - -c get device CPU frequency and CPU usage, process CPU usage and CPU load .. - -g get device GPU frequency and GPU load - -f get app refresh fps(frames per second) and fps jitters and refreshrate - -profilerfps get refresh fps and timestamp - -sections set collection time period(using with profilerfps) - -t get remaining battery power and temperature.. - -p get battery power consumption and voltage - -r get process memory and total memory - -snapshot get screen capture - -net get uplink and downlink traffic - -start collection start command - -stop collection stop command - -VIEW set layler, for example: -VIEW DisplayNode - -OUT set csv output path. - -d get device DDR information - -ci get cpu instructions and cycles - -screen get screen resolution - -deviceinfo get device information - -server start a process to listen to the socket message of the start and stop commands - -clear clear the process ID - -ohtestfps used by the vilidator to obtain the fps, the collection times can be set - -editorServer start a process to listen to the socket message of the editor - -recordcapacity get the battery level difference - --version get version - --help get help - -editor scenario-based collection identifier, parameter configuration items can be added later - responseTime get the page response delay after an application is operated - completeTime get the page completion delay after an application is operated - fpsohtest used by the vilidator to obtain the fps - example1: - SP_daemon -N 20 -c -g -t -p -r -net -snapshot -d - SP_daemon -N 20 -PKG ohos.samples.ecg -c -g -t -p -f -r -net -snapshot -d - SP_daemon -start -c - SP_daemon -stop - example2: These parameters need to be used separately - SP_daemon -screen - SP_daemon -deviceinfo - SP_daemon -server - SP_daemon -clear - SP_daemon -ohtestfps - SP_daemon -editorServer - SP_daemon -recordcapacity - example3: These parameters need to be used separately - SP_daemon -editor responseTime ohos.samples.ecg app name - SP_daemon -editor completeTime ohos.samples.ecg app name - SP_daemon -editor fpsohtest - -command exec finished! -# -``` -2)执行示例命令:SP_daemon -N 20 -PKG ohos.samples.ecg -c -g -t -p -f -r -d -net -snapshot -``` -----------------------------------Print START------------------------------------ -order:0 timestamp=1710916175201 -order:1 ProcAppName=ohos.samples.ecg -order:2 ProcCpuLoad=0.0015567 -order:3 ProcCpuUsage=0.000000 -order:4 ProcId=18510 -order:5 ProcSCpuUsage=0.000000 -order:6 ProcUCpuUsage=0.000000 -order:7 cpu0Frequency=418000 -order:8 cpu0Usage=0.000000 -order:9 cpu0idleUsage=0.000000 -order:10 cpu0ioWaitUsage=0.000000 -order:11 cpu0irqUsage=0.000000 -order:12 cpu0niceUsage=0.000000 -order:13 cpu0softIrqUsage=0.000000 -order:14 cpu0systemUsage=0.000000 -order:15 cpu0userUsage=0.000000 -... -order:115 gpuFrequency=279000000 -order:116 gpuload=61.000000 -order:117 Battery=28.000000 -order:118 shell_back=31.529000 -order:119 shell_frame=30.529000 -order:120 shell_front=30.548000 -order:121 soc_thermal=49.624000 -order:122 system_h=30.150000 -order:123 currentNow=278 -order:124 voltageNow=4250532 -order:125 fps=3 -order:126 fpsJitters=881659966;;108846354;;8289583 -order:127 refreshrate=120 -order:128 memAvailable=6354252 -order:129 memFree=5971776 -order:130 memTotal=11530092 -order:131 pss=78045 -order:132 arktsHeapPss=13394 -order:133 gpuPss=280 -order:134 graphicPss=0 -order:135 heapAlloc=48080 -order:136 heapFree=2576 -order:137 heapSize=50788 -order:138 nativeHeapPss=41897 -order:139 privateClean=67232 -order:140 privateDirty=12848 -order:141 sharedClean=76224 -order:142 sharedDirty=12848 -order:143 stackPss=1096 -order:144 swap=0 -order:145 swapPss=0 -order:146 ddrFrequency=1531000000 -order:147 networkDown=0 -order:148 networkUp=0 -order:149 capture=data/local/tmp/capture/screenCap_1711190737580.png - - -----------------------------------Print END-------------------------------------- -----------------------------------Print START------------------------------------ -order:0 timestamp=1710916175201 -order:1 ProcAppName=ohos.samples.ecg -order:2 ProcCpuLoad=0.001379 -order:3 ProcCpuUsage=0.008162 -order:4 ProcId=18510 -order:5 ProcSCpuUsage=0.008162 -order:6 ProcUCpuUsage=0.000000 -order:7 cpu0Frequency=418000 -order:8 cpu0Usage=16.346154 -order:9 cpu0idleUsage=83.653846 -order:10 cpu0ioWaitUsage=0.961538 -order:11 cpu0irqUsage=4.807692 -order:12 cpu0niceUsage=0.000000 -order:13 cpu0softIrqUsage=0.000000 -order:14 cpu0systemUsage=5.769231 -order:15 cpu0userUsage=4.807692 -... -order:115 gpuFrequency=279000000 -order:116 gpuload=61.000000 -order:117 Battery=28.000000 -order:118 shell_back=31.529000 -order:119 shell_frame=30.529000 -order:120 shell_front=30.548000 -order:121 soc_thermal=47.810000 -order:122 system_h=30.200000 -order:123 currentNow=303 -order:124 voltageNow=4251570 -order:125 fps=12 -order:126 fpsJitters=122794860;;8372396;;8375521;;8448958;;16691667;;8357812;;8367188;;8364062;;8383855;;8514062;;8238542;;849062 -order:127 refreshrate=120 -order:128 memAvailable=6370048 -order:129 memFree=5990136 -order:130 memTotal=11530092 -order:131 pss=78217 -order:132 arktsHeapPss=13586 -order:133 gpuPss=280 -order:134 graphicPss=0 -order:135 heapAlloc=48156 -order:136 heapFree=2648 -order:137 heapSize=50780 -order:138 nativeHeapPss=41877 -order:139 privateClean=67404 -order:140 privateDirty=2920 -order:141 sharedClean=76224 -order:142 sharedDirty=12848 -order:143 stackPss=1096 -order:144 swap=0 -order:145 swapPss=0 -order:146 ddrFrequency=1531000000 -order:147 networkDown=0 -order:148 networkUp=0 -order:149 capture=data/local/tmp/capture/screenCap_1711190738589.png - -command exec finished! -# -----------------------------------Print END-------------------------------------- -``` -3)执行完毕后会在data/local/tmp生成data.csv文件,每次执行命令覆盖写入,可导出到本地查看。 -```bash -c:\Users\xxx>hdc file recv data/local/tmp/data.csv D:\ -[I][2024-03-20 18:27:07] HdcFile::TransferSummary success -FileTransfer finish, Size:7306, File count = 1, time:377ms rate:19.38kB/s ---- - -## 发布版本 - -**3.2.0.0版本发布内容:预制SP_daemon bin文件,支持以下功能:**
-1. 支持RK3568、Hi3516。
-2. 支持Shell启动。
-3. 支持采集整机CPU、GPU、POWER、TEMPERATURE、应用的FPS、RAM、CPU等 \ No newline at end of file diff --git a/smartperf_device/device_command/heartbeat.cpp b/smartperf_device/device_command/heartbeat.cpp deleted file mode 100644 index 70f27023..00000000 --- a/smartperf_device/device_command/heartbeat.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include -#include -#include "include/heartbeat.h" -#include "include/sp_utils.h" -#include "sp_log.h" -#include "include/startup_delay.h" -#include "include/common.h" -namespace OHOS { -namespace SmartPerf { -void Heartbeat::KillSpId() -{ - std::string str; - std::string resultPid; - std::string cmd = CMD_COMMAND_MAP.at(CmdCommand::PIDOF_SP); - SPUtils::LoadCmd(cmd, resultPid); - std::vector vec; - std::string token; - size_t pos = resultPid.find(' '); - do { - token = resultPid.substr(0, pos); - vec.push_back(token); - resultPid.erase(0, pos + 1); - } while ((pos = resultPid.find(' ')) != std::string::npos); - if (vec.size() > 0) { - std::string killCmd = CMD_COMMAND_MAP.at(CmdCommand::KILL_CMD); - for (size_t i = 0; i < vec.size(); i++) { - SPUtils::LoadCmd(killCmd + vec[i], str); - } - } -} - -void Heartbeat::HeartbeatRule() -{ - while (isrunning) { - auto end = std::chrono::steady_clock::now(); - auto duration = std::chrono::duration_cast(end - updateStart).count(); - if (duration > timeout) { - LOGD("Socket disconnected!"); - KillSpId(); - } - sleep(checkMessageTime); - } -} - -void Heartbeat::UpdatestartTime() -{ - std::unique_lock lock(mtx); - updateStart = std::chrono::steady_clock::now(); -} - -} -} \ No newline at end of file diff --git a/smartperf_device/device_command/smartperf_main.cpp b/smartperf_device/device_command/smartperf_main.cpp deleted file mode 100644 index 9c628c91..00000000 --- a/smartperf_device/device_command/smartperf_main.cpp +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include "unistd.h" -#include -#include -#include "include/smartperf_command.h" -#include "include/editor_command.h" -#include "include/FPS.h" -#include "include/client_control.h" -#include "include/sp_utils.h" -#include "include/sp_log.h" -#include "include/common.h" -#include "parameters.h" -#include "task_manager.h" -#include "include/startup_delay.h" - -constexpr const char *VERSION_TYPE = "const.logsystem.versiontype"; -static std::string GetOptions(const std::vector &argv) -{ - std::string str = ""; - std::string strFlag; - bool isFill = false; - for (std::size_t i = 0; i < argv.size(); i++) { - if (!isFill) { - strFlag = argv[i]; - if (strFlag.find("SP_daemon") != std::string::npos) { - isFill = true; - } - } else { - str += argv[i]; - if (i + 1 != argv.size()) { - str += " "; - } - } - } - return str; -} -static void KeyInsert(std::set &keysMap) -{ - keysMap.insert("editor"); - keysMap.insert("profilerfps"); - keysMap.insert("start"); - keysMap.insert("stop"); - keysMap.insert("screen"); - keysMap.insert("clear"); - keysMap.insert("clearAll"); - keysMap.insert("server"); - keysMap.insert("sections"); - keysMap.insert("deviceinfo"); - keysMap.insert("ohtestfps"); - keysMap.insert("editorServer"); - keysMap.insert("deviceServer"); - keysMap.insert("recordcapacity"); -} -static bool g_checkCmdParam(std::vector &argv, std::string &errorInfo) -{ - std::string str = GetOptions(argv); - std::set keys; // Includes three parts "SP_daemon" CommandType and CommandHelp - if (str.empty()) { - return true; - } - // 'help' and 'version' start with "--" and are processed separately - if (str.find("--help") != std::string::npos || str.find("--version") != std::string::npos) { - std::vector out; - OHOS::SmartPerf::SPUtils::StrSplit(str, "-", out); - if (out.size() != 1) { - errorInfo = "--help and --version cannot be used together with other options"; - return false; - } else { - return true; - } - } - if (str.find("-PKG") != std::string::npos && str.find("-PID") != std::string::npos) { - errorInfo = "-PKG and -PID cannot be used together with"; - return false; - } - KeyInsert(keys); - // editor 与 device 的拉起命令与 token 一起加入白名单 - if (argv[1].find("editorServer:") != std::string::npos || - argv[1].find("deviceServer:") != std::string::npos - ) { - keys.insert(argv[1].substr(1).c_str()); - } - for (auto& a : OHOS::SmartPerf::COMMAND_MAP) { - keys.insert(a.first.substr(1)); // No prefix required '-' - } - - /* ************The command line for the following parameters is not implemented****************** */ - keys.erase("f1"); - keys.erase("f2"); - keys.erase("fl"); - keys.erase("ftl"); - return OHOS::SmartPerf::SPUtils::VeriyParameter(keys, str, errorInfo); -} - -static void SocketStopCommand() -{ - OHOS::SmartPerf::ClientControl cc; - cc.SocketStop(); -} - -static void RecordCapacity() -{ - const std::string capacityRmPath = "/sys/class/power_supply/Battery/capacity_rm"; - const std::string rkCapacityRmPath = "/data/service/el0/battery/battery/capacity"; - const std::string capacitySavePath = "/data/local/tmp/powerLeftRecord.csv"; - std::string capacityString; - std::ifstream infile(capacitySavePath.c_str()); - if (infile.is_open()) { - std::stringstream buffer; - int capacityLine = 0; - std::string line; - const int MAX_RECORD_COUNT = 100; - buffer << infile.rdbuf(); - capacityString = buffer.str(); - infile.close(); - - while (std::getline(buffer, line)) { - capacityLine++; - } - if (capacityLine == MAX_RECORD_COUNT) { - std::size_t pos = capacityString.find('\n'); - if (pos != std::string::npos) { - capacityString = capacityString.substr(pos + 1); - } - } - } - std::ofstream outFile(capacitySavePath.c_str(), std::ios::out | std::ios::trunc); - if (!outFile.is_open()) { - std::cout << "Error opening capacity file!" << std::endl; - return; - } - std::string recordPower; - auto recordTime = std::to_string(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())); - OHOS::SmartPerf::SPUtils::LoadFile(capacityRmPath, recordPower); - if (recordPower.empty()) { - std::string rkRecordPower; - int maxBat = 60; - OHOS::SmartPerf::SPUtils::LoadFile(rkCapacityRmPath, rkRecordPower); - recordPower = std::to_string(OHOS::SmartPerf::SPUtilesTye::StringToSometype(rkRecordPower) * maxBat); - } - std::cout << "recordTime: " << recordTime << std::endl << "recordPower: " << recordPower << std::endl; - capacityString += recordTime + "," + recordPower; - outFile << capacityString << std::endl; - if (outFile.fail()) { - const int bufSize = 256; - char buf[bufSize] = { 0 }; - std::cout << "Error writing capacity failed:" << strerror_r(errno, buf, bufSize) << std::endl; - } - outFile.close(); -} - -static int ProcessSpecificParameter(int argc, char *argv[], std::vector &vec) -{ - if (argc > 1 && strcmp(argv[1], "-editor") == 0) { - OHOS::SmartPerf::EditorCommand(argc, vec); - return 0; - } else if (argc > 1 && strcmp(argv[1], "-profilerfps") == 0) { - OHOS::SmartPerf::FPS::GetInstance().GetFPS(vec); - return 0; - } else if (argc > 1 && strcmp(argv[1], "-start") == 0) { - OHOS::SmartPerf::SPUtils::KillStartDaemon(); - std::string startStr = ""; - std::string endStr = ""; - std::string pidCmd = OHOS::SmartPerf::CMD_COMMAND_MAP.at(OHOS::SmartPerf::CmdCommand::PIDOF_SP); - OHOS::SmartPerf::SPUtils::LoadCmd(pidCmd, startStr); - OHOS::SmartPerf::ClientControl cc; - cc.StartSPDaemon(); - OHOS::SmartPerf::SPUtils::LoadCmd(pidCmd, endStr); - std::vector startParams; - std::vector endParams; - OHOS::SmartPerf::SPUtils::StrSplit(startStr, " ", startParams); - OHOS::SmartPerf::SPUtils::StrSplit(endStr, " ", endParams); - std::string result; - const int maxExpectedArgs = 100; - for (int i = 2; i < argc && i < maxExpectedArgs; i++) { - result += argv[i]; - if (i != argc - 1) { - result += " "; - } - } - if (startParams.size() == endParams.size()) { - std::cout << "The last collection is interrupted." << std::endl; - std::cout << "SP_daemon -start " << result << " started collecting..." << std::endl; - } - cc.SocketStart(result); - std::cout << "command exec finished!" << std::endl; - return 0; - } else if (argc > 1 && strcmp(argv[1], "-stop") == 0) { - SocketStopCommand(); - std::cout << "command exec finished!" << std::endl; - return 0; - } else if (argc > 1 && strcmp(argv[1], "-deviceinfo") == 0) { - std::cout << OHOS::SmartPerf::SPUtils::GetDeviceInfoMap() << std::endl; - return 0; - } else if (argc > 1 && strcmp(argv[1], "-ohtestfps") == 0) { - OHOS::SmartPerf::FPS::GetInstance().GetOhFps(vec); - return 0; - } else if (argc > 1 && strcmp(argv[1], "-recordcapacity") == 0) { - RecordCapacity(); - return 0; - } - - return 1; -} - -int main(int argc, char *argv[]) -{ - if (OHOS::system::GetParameter(VERSION_TYPE, "Unknown") != "beta") { - if (!OHOS::system::GetBoolParameter("const.security.developermode.state", true)) { - std::cout << "Not a development mode state" << std::endl; - return 0; - } - } - const int maxExpectedArgs = 100; - std::string errorInfo; - std::vector vec; - if (argc < 0 || argc > maxExpectedArgs) { - std::cout << "Invalid argument count" << std::endl; - return -1; - } - for (int i = 0; i < argc; i++) { - vec.push_back(argv[i]); - } - if (!g_checkCmdParam(vec, errorInfo)) { - std::cout << "SP_daemon:" << errorInfo << std::endl << - "Usage: SP_daemon [options] [arguments]" << std::endl << std::endl << - "Try `SP_daemon --help' for more options." << std::endl; - return 0; - } - OHOS::SmartPerf::SPUtils::SetRkFlag(); - if (ProcessSpecificParameter(argc, argv, vec) == 0) { - return 0; - } - - OHOS::SmartPerf::SmartPerfCommand cmd(vec); - OHOS::SmartPerf::StartUpDelay sd; - sd.KillSpProcess(); - std::cout << cmd.ExecCommand() << std::endl; - return 0; -} -- Gitee