xref: /ide/tools/previewer/util/TraceTool.cpp (revision 7c804472)
1/*
2 * Copyright (c) 2023 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
16#include "TraceTool.h"
17#include "JsonReader.h"
18#include "CommandParser.h"
19#include "PreviewerEngineLog.h"
20#include "TimeTool.h"
21#include "LocalSocket.h"
22
23void TraceTool::InitPipe()
24{
25    if (socket != nullptr) {
26        socket.reset();
27        ELOG("TraceTool::InitPipe socket is not null");
28    }
29
30    socket = std::make_unique<LocalSocket>();
31    if (socket == nullptr) {
32        FLOG("TraceTool::Connect socket memory allocation failed!");
33    }
34    std::string name = GetTracePipeName();
35    if (!socket->ConnectToServer(socket->GetTracePipeName(name), LocalSocket::READ_WRITE)) {
36        ELOG("TraceTool::pipe connect failed");
37        return;
38    }
39    isReady = true;
40    ELOG("TraceTool::pipe connect successed");
41}
42
43TraceTool& TraceTool::GetInstance()
44{
45    static TraceTool instance;
46    return instance;
47}
48
49void TraceTool::SendTraceData(const Json2::Value& value)
50{
51    *(GetInstance().socket) << value.ToString();
52}
53
54void TraceTool::HandleTrace(const std::string msg) const
55{
56    if (!isReady) {
57        ILOG("Trace pipe is not prepared");
58        return;
59    }
60    Json2::Value val = JsonReader::CreateObject();
61    val.Add("sid", "10007");
62    Json2::Value detail = JsonReader::CreateObject();
63    detail.Add("ProjectId", CommandParser::GetInstance().GetProjectID().c_str());
64    detail.Add("device", CommandParser::GetInstance().GetDeviceType().c_str());
65    detail.Add("time", TimeTool::GetTraceFormatTime().c_str());
66    val.Add("detail", detail);
67    val.Add("action", msg.c_str());
68    SendTraceData(val);
69}
70
71TraceTool::TraceTool() : socket(nullptr), isReady(false)
72{
73    InitPipe();
74}
75
76TraceTool::~TraceTool()
77{
78    if (socket != nullptr) {
79        socket->DisconnectFromServer();
80        socket = nullptr;
81    }
82}
83
84std::string TraceTool::GetTracePipeName() const
85{
86    return CommandParser::GetInstance().Value("ts");
87}
88