UniSet @VERSION@
JSOPCUAClient.h
1/*
2 * Copyright (c) 2025 Pavel Vainerman.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License as
6 * published by the Free Software Foundation, version 2.1.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Lesser Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16// --------------------------------------------------------------------------
17#ifndef JSOPCUAClient_H_
18#define JSOPCUAClient_H_
19// --------------------------------------------------------------------------
20#include <memory>
21#include <string>
22#include <vector>
23#include <variant>
24
25#include <open62541/client_highlevel.h>
26#include <open62541/types_generated_handling.h>
27#include <open62541pp/open62541pp.hpp>
28#include <open62541pp/ua/types.hpp>
29
30#include "DebugStream.h"
31
32namespace uniset
33{
39 {
40 public:
43
44 void setLog(const std::shared_ptr<DebugStream>& log);
45
46 bool connect(const std::string& endpoint);
47 bool connect(const std::string& endpoint, const std::string& user, const std::string& passwd);
48 void disconnect() noexcept;
49
50 bool isConnected() const noexcept;
51
52 enum class VarType : int
53 {
54 Int32 = 0,
55 Float = 1
56 };
57
58 struct ResultVar
59 {
60 std::variant<int32_t, float> value = {0};
61 UA_StatusCode status = UA_STATUSCODE_BAD;
62 VarType type = VarType::Int32;
63
64 bool statusOk() const noexcept
65 {
66 return status == UA_STATUSCODE_GOOD;
67 }
68
69 template<class VType>
70 VType as() const
71 {
72 try
73 {
74 return std::get<VType>(value);
75 }
76 catch(const std::bad_variant_access&)
77 {
78 return {};
79 }
80 }
81 };
82
83 struct WriteItem
84 {
85 std::string nodeId;
86 std::variant<int32_t, float, bool> value;
87 };
88
89 using ErrorCode = UA_StatusCode;
90
91 std::vector<ResultVar> read(const std::vector<std::string>& nodeIds);
92 ErrorCode write(const std::vector<WriteItem>& items);
93
94 private:
95 UA_ReadValueId makeReadValue(const std::string& nodeId);
96 void logError(const std::string& msg) const;
97
98 std::shared_ptr<DebugStream> log;
99 opcua::Client client;
100 bool connected = false;
101 };
102} // namespace uniset
103
104#endif // JSOPCUAClient_H_
Definition JSOPCUAClient.h:39
Definition AccessConfig.h:30
Definition JSOPCUAClient.h:59
Definition JSOPCUAClient.h:84