Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011 #include <opc/ua/client/client.h>
00012 #include <opc/ua/node.h>
00013 #include <opc/ua/subscription.h>
00014
00015 #include <iostream>
00016 #include <stdexcept>
00017 #include <thread>
00018
00019 using namespace OpcUa;
00020
00021 class SubClient : public SubscriptionHandler
00022 {
00023 void DataChange(uint32_t handle, const Node& node, const Variant& val, AttributeId attr) override
00024 {
00025 std::cout << "Received DataChange event, value of Node " << node << " is now: " << val.ToString() << std::endl;
00026 }
00027 };
00028
00029 int main(int argc, char** argv)
00030 {
00031 try
00032 {
00033
00034
00035 std::string endpoint = "opc.tcp://127.0.0.1:4841/freeopcua/server/";
00036
00037
00038
00039 if (argc > 1)
00040 endpoint = argv[1];
00041
00042 std::cout << "Connecting to: " << endpoint << std::endl;
00043 bool debug = false;
00044 OpcUa::UaClient client(debug);
00045 client.Connect(endpoint);
00046
00047
00048 OpcUa::Node root = client.GetRootNode();
00049 std::cout << "Root node is: " << root << std::endl;
00050
00051
00052 std::cout << "Child of objects node are: " << std::endl;
00053 Node objects = client.GetObjectsNode();
00054 for (OpcUa::Node node : objects.GetChildren())
00055 std::cout << " " << node << std::endl;
00056
00057
00058 std::cout << "NamespaceArray is: " << std::endl;
00059 OpcUa::Node nsnode = client.GetNode(ObjectId::Server_NamespaceArray);
00060 OpcUa::Variant ns = nsnode.GetValue();
00061
00062 for (std::string d : ns.As<std::vector<std::string>>())
00063 std::cout << " " << d << std::endl;
00064
00065 OpcUa::Node myvar;
00066
00067
00068
00069
00070
00071
00072
00074
00075
00076
00077
00078
00079
00080
00081
00082 std::vector<std::string> varpath{ "Objects", "Server", "ServerStatus", "CurrentTime" };
00083 myvar = root.GetChild(varpath);
00084
00085 std::cout << "got node: " << myvar << std::endl;
00086
00087
00088 SubClient sclt;
00089 std::unique_ptr<Subscription> sub = client.CreateSubscription(100, sclt);
00090 uint32_t handle = sub->SubscribeDataChange(myvar);
00091 std::cout << "Got sub handle: " << handle << ", sleeping 5 seconds" << std::endl;
00092 std::this_thread::sleep_for(std::chrono::seconds(5));
00093
00094 std::cout << "Disconnecting" << std::endl;
00095 client.Disconnect();
00096 return 0;
00097 }
00098 catch (const std::exception& exc)
00099 {
00100 std::cout << exc.what() << std::endl;
00101 }
00102 catch (...)
00103 {
00104 std::cout << "Unknown error." << std::endl;
00105 }
00106 return -1;
00107 }
00108