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
16 #include "client.h"
17 #include "test_server.h"
18
19 #include "utils/logger.h"
20 #include "websocketpp/close.hpp"
21 #include "websocketpp/uri.hpp"
22
23 #include <memory>
24 #include <system_error>
25 #include <utility>
26
27 namespace panda::tooling::inspector::test {
28 class ClientCategory : public std::error_category {
29 public:
name() const30 const char *name() const noexcept override
31 {
32 return "client";
33 }
34
message(int code) const35 std::string message(int code) const override
36 {
37 switch (code) {
38 case Client::Error::CONNECTION_ALREADY_PINNED:
39 return "Connection already pinned";
40 case Client::Error::CONNECTION_FAILED:
41 return "Connection failed";
42 default:
43 return "Unknown";
44 }
45 }
46
Encode(Client::Error error)47 static std::error_code Encode(Client::Error error)
48 {
49 static ClientCategory category;
50 return {error, category};
51 }
52 };
53
Call(const char * method,std::function<void (JsonObjectBuilder &)> && params,std::function<void (const JsonObject &)> && handler)54 void Client::Call(const char *method, std::function<void(JsonObjectBuilder &)> &¶ms,
55 std::function<void(const JsonObject &)> &&handler)
56 {
57 Endpoint::Call(++id_, method, std::move(params));
58 OnResult(id_, std::move(handler));
59 }
60
Close()61 std::error_code Client::Close()
62 {
63 std::error_code ec;
64 GetPinnedConnection()->close(websocketpp::close::status::normal, "", ec);
65 return ec;
66 }
67
Connect(TestServer & server,std::function<void (std::error_code)> && cb)68 void Client::Connect(TestServer &server, std::function<void(std::error_code)> &&cb)
69 {
70 std::error_code ec;
71
72 auto connection = endpoint_.get_connection(std::make_shared<websocketpp::uri>(false, server.GetName(), ""), ec);
73
74 if (ec) {
75 return cb(ec);
76 }
77
78 connection->set_open_handler([this, cb](auto hdl) {
79 if (!Pin(hdl)) {
80 return cb(ClientCategory::Encode(CONNECTION_ALREADY_PINNED));
81 }
82
83 cb(std::error_code());
84 });
85
86 connection->set_fail_handler([this, cb](auto hdl) {
87 LOG(INFO, DEBUGGER) << "Failed to connect: " << endpoint_.get_con_from_hdl(hdl)->get_response().get_body();
88
89 cb(ClientCategory::Encode(CONNECTION_FAILED));
90 });
91
92 server.Connect(connection, *this);
93 }
94 } // namespace panda::tooling::inspector::test
95