示例#1
0
        public static void Main(string[] args)
        {
            //// If the server domain name does not match localhost just replace it
            //// e.g. with the IP address or name of the server machine.

            var client = new OpcClient("opc.tcp://localhost:4840/SampleServer");

            client.Connect();

            // The class OpcObjectTypes contains all default OpcNodeId's of all nodes typically
            // provided by default by every OPC UA server. Here we start browsing at the top most
            // node the ObjectsFolder. Beneath this node there are all further nodes in an
            // OPC UA server registered.
            // Creating an OpcBrowseNode does only prepare an OpcBrowseNodeContext which is linked
            // to the OpcClient which creates it and contains all further browsing relevant
            // contextual metadata (e.g. the view and the referenceTypeIds). The used overload of
            // CreateBrowseNode(...) browses the default view of the server while it takes care of
            // HierarchicalReferences(see ReferenceTypeIds).
            // After creating the browse node for the ObjectsFolder we traverse the whole node
            // tree in preorder.
            // In case there you have the OpcNodeId of a specific node (e.g. after browsing for a
            // specific node) it is also possible to pass that OpcNodeId to CreateBrowseNode(...)
            // to browse starting at that node.
            var node = client.BrowseNode(OpcObjectTypes.ObjectsFolder);

            Program.Browse(node);

            client.Disconnect();
            Console.ReadKey(true);
        }
示例#2
0
        public static void Main(string[] args)
        {
            //// If the server domain name does not match localhost just replace it
            //// e.g. with the IP address or name of the server machine.

            var client = new OpcClient("opc.tcp://localhost:4840/SampleServer");

            // Just configure the OpcClient instance with an appropriate user identity with
            // the name of the user and its password to use to authenticate.
            client.Security.UserIdentity = new OpcClientIdentity("username", "password");

            client.Connect();
            Console.WriteLine("ReadNode: {0}", client.ReadNode("ns=2;s=Machine_1/IsActive"));

            try {
                client.WriteNode("ns=2;s=Machine_1/IsActive", false);
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("ReadNode: {0}", client.ReadNode("ns=2;s=Machine_1/IsActive"));

            client.Disconnect();
            Console.ReadKey(true);
        }
示例#3
0
        public static void Main(string[] args)
        {
            //// If the server domain name does not match localhost just replace it
            //// e.g. with the IP address or name of the server machine.

            #region 1st Way: Use the OpcClient class.
            {
                // The OpcClient class interacts with one OPC UA server. While this class
                // provides session based access to the different OPC UA services of the
                // server, it does not implement a main loop.
                var client = new OpcClient("opc.tcp://localhost:4840/SampleServer");

                client.Connect();
                Program.CommunicateWithServer(client);
                client.Disconnect();
            }
            #endregion

            #region 2nd Way: Use the OpcClientApplication class.
            {
                //// The OpcClientApplication class uses a single OpcClient instance which is
                //// wrapped within a main loop.
                ////
                //// Remarks
                //// - The app instance starts a main loop when the session to the server has
                ////   been established.
                //// - Custom client/session dependent code have to be implemented within the event
                ////   handler of the Started event.
                //var app = new OpcClientApplication("opc.tcp://localhost:4840/SampleServer");
                //app.Started += Program.HandleAppStarted;

                //app.Run();
            }
            #endregion
        }
示例#4
0
        public static void Main(string[] args)
        {
            //// If the server domain name does not match localhost just replace it
            //// e.g. with the IP address or name of the server machine.

            var client = new OpcClient("opc.tcp://localhost:4840/SampleServer");

            client.Connect();

            // The mapping of the UNECE codes to OPC UA (OpcEngineeringUnitInfo.UnitId) is available here:
            // http://www.opcfoundation.org/UA/EngineeringUnits/UNECE/UNECE_to_OPCUA.csv
            var temperatureNode = client.BrowseNode("ns=2;s=Machine_1/Temperature") as OpcAnalogItemNodeInfo;


            if (temperatureNode != null)
            {
                var temperatureUnit  = temperatureNode.EngineeringUnit;
                var temperatureRange = temperatureNode.EngineeringUnitRange;

                var temperature = client.ReadNode(temperatureNode.NodeId);

                Console.WriteLine(
                    "Temperature: {0} {1}, Range: {3} {1} to {4} {1} ({2})",
                    temperature.Value,
                    temperatureUnit.DisplayName,
                    temperatureUnit.Description,
                    temperatureRange.Low,
                    temperatureRange.High);
            }

            var pressureNode = client.BrowseNode("ns=2;s=Machine_1/Pressure") as OpcAnalogItemNodeInfo;

            if (pressureNode != null)
            {
                var pressureUnit            = pressureNode.EngineeringUnit;
                var pressureInstrumentRange = pressureNode.InstrumentRange;

                var pressure = client.ReadNode(pressureNode.NodeId);

                Console.WriteLine(
                    "Pressure: {0} {1}, Range: {3} {1} to {4} {1} ({2})",
                    pressure.Value,
                    pressureUnit.DisplayName,
                    pressureUnit.Description,
                    pressureInstrumentRange.Low,
                    pressureInstrumentRange.High);
            }

            client.Disconnect();
            Console.ReadKey(true);
        }
示例#5
0
        static void Main(string[] args)
        {
            var client = new OpcClient("opc.tcp://opcuaserver.com:48010");

            client.Connected    += new EventHandler(ConnectedEvent);
            client.Disconnected += new EventHandler(DisconnectedEvent);

            client.Connect();

            var node = client.BrowseNode(OpcObjectTypes.ObjectsFolder);

            Browse(node);

            Thread.Sleep(6000);
            client.Disconnect();
        }
        static void Main(string[] args)
        {
            var client = new OpcClient("opc.tcp://127.0.0.1:49320");

            client.Security.UserIdentity   = new OpcClientIdentity("Tim", "1qaz2wsx3edc4rfv");
            client.Security.EndpointPolicy = new OpcSecurityPolicy(OpcSecurityMode.SignAndEncrypt, OpcSecurityAlgorithm.Basic256);
            client.Connect();


            // 一次寫取多個Tag
            OpcWriteNode[] wCommands = new OpcWriteNode[] {
                new OpcWriteNode("ns=2;s=Channel2.Device1.Tag1", false),     // 寫 boolean
                new OpcWriteNode("ns=2;s=Channel2.Device1.Tag2", "Test"),    // 寫 sting
                new OpcWriteNode("ns=2;s=Channel2.Device1.Tag3", 8.7),       // 寫 float
                new OpcWriteNode("ns=2;s=Channel2.Device1.Tag3", (ushort)88) // 寫 word
            };
            OpcStatusCollection results = client.WriteNodes(wCommands);

            // 一次讀取多個Tag
            OpcReadNode[] rCommands = new OpcReadNode[] {
                new OpcReadNode("ns=2;s=Channel2.Device1.Tag1"),
                new OpcReadNode("ns=2;s=Channel2.Device1.Tag2"),
                new OpcReadNode("ns=2;s=Channel2.Device1.Tag3"),
                new OpcReadNode("ns=2;s=Channel2.Device1.Tag4")
            };
            IEnumerable <OpcValue> job = client.ReadNodes(rCommands);
            int i = 0;

            foreach (OpcValue value in job)
            {
                Console.WriteLine("ReadNode: {0},\t = {1}", rCommands[i].NodeId, value);
                i++;
            }


            // 訂閱Tag5
            OpcSubscription subscription = client.SubscribeDataChange("ns=2;s=Channel2.Device1.Tag5", HandleDataChanged);

            subscription.PublishingInterval = 1000;
            subscription.ApplyChanges();


            Console.ReadLine();

            client.Disconnect();
        }
示例#7
0
        public static void Main(string[] args)
        {
            //// To simple use the configuration stored within the XML configuration file
            //// beside the client application you just need to load the configuration file as the
            //// following code does demonstrate.
            //// By default it is not necessary to explicitly configure an OPC UA client. But in case
            //// of advanced and productive scenarios you will have to.

            // There are different ways to load the client configuration.
            OpcApplicationConfiguration configuration = null;

            // 1st Way: Load client config using a file path.
            configuration = OpcApplicationConfiguration.LoadClientConfigFile(
                Path.Combine(Environment.CurrentDirectory, "ClientConfig.xml"));

            // 2nd Way: Load client config specified in a specific section of your App.config.
            configuration = OpcApplicationConfiguration.LoadClientConfig("Opc.UaFx.Client");

            // If the client uris domain name does not match localhost just replace it
            // e.g. with the IP address or name of the client machine.
            var client = new OpcClient("opc.tcp://localhost:4840/SampleClient");

            // To take use of the loaded client configuration, just set it on the client instance.
            client.Configuration = configuration;

            client.Connect();
            client.Disconnect();

            // In case you are using the OpcClientApplication class, you can explicitly trigger
            // loading a configuration file using the App.config as the following code does
            // demonstrate.
            var app = new OpcClientApplication("opc.tcp://localhost:4840/SampleClient");

            app.LoadConfiguration();

            // Alternatively you can assign the manually loaded client configuration on the client
            // instance used by the application instance, as the following code does demonstrate.
            app.Client.Configuration = configuration;

            app.Run();
        }
        public static void Main(string[] args)
        {
            //// If the server domain name does not match localhost just replace it
            //// e.g. with the IP address or name of the server machine.

            var client = new OpcClient("opc.tcp://localhost:4840/SampleServer");

            client.Connect();

            //
            // The data types used in following lines were generated using the OPC Watch.
            // https://docs.traeger.de/en/software/sdk/opc-ua/net/client.development.guide#generate-data-types
            //

            var job = client.ReadNode("ns=2;s=Machines/Machine_1/Job").As <MachineJob>();

            Console.WriteLine("Machine 1 - Job");
            PrintJob(job);

            var order = client.ReadNode("ns=2;s=Machines/Machine_2/Order").As <ManufacturingOrder>();

            Console.WriteLine();
            Console.WriteLine("Machine 2 - Order");
            Console.WriteLine(".Order = {0}", order.Order);
            Console.WriteLine(".Article = {0}", order.Article);

            Console.WriteLine();
            Console.WriteLine("Machine 2 - Order, Jobs");

            foreach (var orderJob in order.Jobs)
            {
                PrintJob(orderJob);
                Console.WriteLine('-');
            }

            client.Disconnect();
            Console.ReadKey(true);
        }
示例#9
0
        public static void Main(string[] args)
        {
            //// If the server domain name does not match localhost just replace it
            //// e.g. with the IP address or name of the server machine.

            var client = new OpcClient("opc.tcp://localhost:4840/SampleServer");

            client.Connect();

            var methodsNode = client.BrowseNode("ns=2;s=Methods");
            var methods     = BrowseMethods(methodsNode).ToList();

            do
            {
                Console.WriteLine("Enter index of method to call or 'exit':");

                for (int index = 0; index < methods.Count; index++)
                {
                    Console.WriteLine("{0}. {1}", index, methods[index].Node.DisplayName.Value);
                }

                var line = Console.ReadLine();

                if (line == "exit")
                {
                    break;
                }

                if (int.TryParse(line, out var methodIndex))
                {
                    var method = methods[methodIndex];

                    Console.WriteLine();
                    Console.WriteLine("Calling method '{0}' ...", method.Node.DisplayName.Value);

                    var inputs = method.Node.GetInputArguments();

                    foreach (var input in inputs)
                    {
                        Console.WriteLine(
                            "\t[IN] {0} : {1} // {2}",
                            input.Name,
                            OpcDataTypes.GetDataType(input.DataTypeId),
                            input.Description);
                    }

                    var outputs = method.Node.GetOutputArguments();

                    foreach (var output in outputs)
                    {
                        Console.WriteLine(
                            "\t[OUT] {0} : {1} // {2}",
                            string.IsNullOrEmpty(output.Name) ? "ret" : output.Name,
                            OpcDataTypes.GetDataType(output.DataTypeId),
                            output.Description);
                    }

                    var inputArguments = new List <object>();

                    if (inputs.Length > 0)
                    {
                        Console.WriteLine();

                        foreach (var input in inputs)
                        {
                            Console.Write(
                                "Enter '{0}' value of '{1}': ",
                                OpcDataTypes.GetDataType(input.DataTypeId),
                                input.Name);

                            var value = Console.ReadLine();

                            if (input.DataTypeId == OpcDataTypes.String)
                            {
                                inputArguments.Add(value);
                            }
                            else if (input.DataTypeId == OpcDataTypes.Int32)
                            {
                                inputArguments.Add(int.Parse(value));
                            }
                        }
                    }

                    try {
                        var outputArguments = client.CallMethod(method.ParentId, method.Node.NodeId, inputArguments);
                        Console.WriteLine("Call succeeded!");

                        for (int index = 0; index < outputs.Length; index++)
                        {
                            var output = outputs[index];

                            Console.WriteLine(
                                "'{0}' value of '{1}': {2}",
                                OpcDataTypes.GetDataType(output.DataTypeId),
                                string.IsNullOrEmpty(output.Name) ? "ret" : output.Name,
                                outputArguments[index]);
                        }
                    }
                    catch (OpcException ex) {
                        Console.WriteLine("Call failed: {0}", ex.Message);
                    }

                    Console.WriteLine();
                }
            } while (true);

            client.Disconnect();
        }
示例#10
0
        public static void Main(string[] args)
        {
            //// If the server domain name does not match localhost just replace it
            //// e.g. with the IP address or name of the server machine.

            var client = new OpcClient("opc.tcp://localhost:4840/SampleServer");

            client.Connect();

            var statusNode = client.BrowseNode("ns=2;s=Machine_1/Status") as OpcVariableNodeInfo;

            if (statusNode != null)
            {
                var statusValues = statusNode.DataType.GetEnumMembers();

                var currentStatus      = client.ReadNode(statusNode.NodeId);
                var currentStatusValue = null as OpcEnumMember;

                foreach (var statusValue in statusValues)
                {
                    if (statusValue.Value == currentStatus.As <int>())
                    {
                        currentStatusValue = statusValue;
                        break;
                    }
                }

                Console.WriteLine(
                    "Status: {0} ({1})",
                    currentStatusValue.Value,
                    currentStatusValue.Name);

                Console.WriteLine("-> " + currentStatusValue.Description);

                Console.WriteLine();
                Console.WriteLine("Possible status values...");

                foreach (var statusValue in statusValues)
                {
                    Console.WriteLine("{0} = {1}", statusValue.Value, statusValue.Name);
                }

                Console.Write("Enter new status: ");
                var value = Console.ReadLine();

                var newStatus = 0;

                if (int.TryParse(value, out newStatus))
                {
                    client.WriteNode(statusNode.NodeId, newStatus);
                }

                currentStatus = client.ReadNode(statusNode.NodeId);

                foreach (var statusValue in statusValues)
                {
                    if (statusValue.Value == currentStatus.As <int>())
                    {
                        currentStatusValue = statusValue;
                        break;
                    }
                }

                Console.WriteLine();
                Console.WriteLine(
                    "New Status: {0} ({1})",
                    currentStatusValue.Value,
                    currentStatusValue.Name);

                Console.WriteLine("-> " + currentStatusValue.Description);
            }

            client.Disconnect();
            Console.ReadKey(true);
        }
示例#11
0
        private void BtnConnect_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;

            if (btn.Content.ToString() == "连接")
            {
                if (_SelectedEndpointDes == null)
                {
                    Msg("请选择要连接的终结点");
                    return;
                }

                if (sender == BtnConnect)
                {
                    if (_OpcClient.Connect(_OpcServer))
                    {
                        Msg("连接成功!");
                        btn.Content = "断开连接";
                    }
                    else
                    {
                        Msg("连接失败!");
                    }
                }
                else
                {
                    OpcUaServer uaServer = _OpcServer as OpcUaServer;
                    if (RbNoneLogin.IsChecked == true)
                    {
                        //匿名登录

                        uaServer.UserAuth = false;
                    }
                    else
                    {
                        //使用用户名密码登录
                        uaServer.UserAuth = true;
                        uaServer.UserName = TbUser.Text.Trim();
                        uaServer.Password = TbPass.Password;
                    }

                    if (_OpcClient.Connect(uaServer))
                    {
                        btn.Content = "断开连接";
                        Msg("连接成功!");
                    }
                    else
                    {
                        Msg("连接失败!");
                    }
                }
            }

            else if (btn.Content.ToString() == "断开连接")
            {
                _OpcClient.Disconnect();
                btn.Content = "连接";
                ClearUi();
            }
            else
            {
                Msg("未知情况");
            }
        }
示例#12
0
        public static void Main(string[] args)
        {
            //// If the server domain name does not match localhost just replace it
            //// e.g. with the IP address or name of the server machine.

            var client = new OpcClient("opc.tcp://localhost:4840/SampleServer");

            client.Connect();

            var positionNode    = nodes.Add(client, machineId, "Position");
            var temperatureNode = nodes.Add(client, machineId, "Temperature");
            var statusNode      = nodes.Add(client, machineId, "Status");

            var severity   = new OpcSimpleAttributeOperand(OpcEventTypes.Event, "Severity");
            var sourceName = new OpcSimpleAttributeOperand(OpcEventTypes.Event, "SourceName");

            var filter = OpcFilter.Using(client)
                         // Construct the filter to use for event subscriptions...
                         .FromEvents(
                // ... define the types of events to include in the filter
                // this will automatically add all properties defined by
                // the types of events specified ...
                OpcEventTypes.AlarmCondition,
                OpcEventTypes.ExclusiveLimitAlarm,
                OpcEventTypes.DialogCondition)
                         .Where(
                // ... restrict the event information received from the server
                // by specifying the types of events and ...
                OpcFilterOperand.OfType(OpcEventTypes.AlarmCondition)
                | OpcFilterOperand.OfType(OpcEventTypes.ExclusiveLimitAlarm)
                | OpcFilterOperand.OfType(OpcEventTypes.DialogCondition))
                                    // ... maybe additional conditions to fulfill, like the required severity
                                    // using the severity operand defined above like follows:
                                    //// severity > OpcEventSeverity.Medium
                                    // ... these conditions can then enhanced logical operators like follows:
                                    //// & sourceName.Like("Limit")
                         .Select(); // ... finally using Select() will query all the necessary event

            // information required and will create the event filter setup with the
            // givent event types, constraints and additional selection fields.

            // All in one Subscription
            {
                // Subscribe to data changes (value changes committed using ApplyChanges(...)
                // calls) on the status, position and temperature node. Also subscribe to all
                // events reported through notifiers assigned to the machine node. Each of
                // these subscribe tasks represent a single monitored item instance which is used
                // to define the reporting characteristics to use. The so defined monitored items
                // are then maintained by one single subscription.
                var subscription = client.SubscribeNodes(
                    new OpcSubscribeDataChange(statusNode.Id, HandleDataChanges),
                    new OpcSubscribeDataChange(positionNode.Id, HandleDataChanges),
                    new OpcSubscribeDataChange(temperatureNode.Id, HandleDataChanges),
                    new OpcSubscribeEvent(machineId, filter, HandleDataEvents));

                // In case there the client is interested in the current event information (which
                // is not explicitly re-published through the server when a subscription is
                // created) the client have to query a "ConditionRefresh" to query the latest
                // event information known by the server. In general the server does not need to
                // hold something like a history of events.
                subscription.RefreshConditions();
            }

            // Everyone in its own Subscription
            ////{
            ////    var eventsSubscription = client.SubscribeEvent(machineId, filter, HandleDataEvents);
            ////    eventsSubscription.RefreshConditions();

            ////    // In case there only following events need to be known, the "ConditionRefresh" can
            ////    // be omitted and the subscription variable can be removed:
            ////    //// client.SubscribeEvent(machineId, filter, HandleDataEvents);

            ////    // The following created subscription do not need to trigger a "ConditionRefresh",
            ////    // because in general only event information may be important and the current
            ////    // value can be just read, too.
            ////    client.SubscribeDataChange(statusNode.Id, HandleDataChanges);
            ////    client.SubscribeDataChange(positionNode.Id, HandleDataChanges);
            ////    client.SubscribeDataChange(positionNode.Id, HandleDataChanges);
            ////    client.SubscribeDataChange(temperatureNode.Id, HandleDataChanges);
            ////}

            // Handle global (server-wide) events
            {
                var conditionName = new OpcSimpleAttributeOperand(OpcEventTypes.Condition, "ConditionName");

                var globalFilter = OpcFilter.Using(client)
                                   .FromEvents(OpcEventTypes.AlarmCondition)
                                   .Where(severity > OpcEventSeverity.Medium & conditionName.Like("Temperature"))
                                   .Select();

                client.SubscribeEvent(OpcObjectTypes.Server, globalFilter, HandleGlobalEvents);
            }

            Console.CancelKeyPress += (sender, e) => cancelSemaphore.Release();

            do
            {
                UpdateConsole(client);
            }while (!cancelSemaphore.Wait(1000));

            client.Disconnect();
        }
示例#13
0
    public static void Main()
    {
        string             stringEntered = "";
        bool               exitSession   = false;
        List <OpcNodeInfo> listOfNodes;

        using (var client = new OpcClient("opc.tcp://localhost:4840"))
        {
            client.Connect();

            while (true)//(!exitSession)
            {
                Console.WriteLine("Available commands: 'view' 'edit' 'disconnect'");
                Console.Write("Enter a command from the above list: ");
                stringEntered = Convert.ToString(Console.ReadLine());

                switch (stringEntered)
                {
                case "view":
                {
                    Console.WriteLine("Enter the name(s) of the node(s) separated by whitespace(s):");
                    string             fullString   = Console.ReadLine();
                    List <OpcNodeInfo> nodeInfoList = AddNodesToList(fullString, client);
                    Console.WriteLine("****************************");
                    foreach (OpcNodeInfo infoElement in nodeInfoList)
                    {
                        //Start here!
                    }
                    Console.WriteLine("****************************");

                    DisplayNodeInfo(nodeInfoList);
                    break;
                }

                case "editValue":
                {
                    //EditNodeValue();
                    break;
                }

                case "disconnect":
                {
                    client.Disconnect();
                    Console.WriteLine("Session is exiting...");
                    exitSession = true;
                    break;
                }

                default:
                {
                    Console.WriteLine(stringEntered + " is not an accepted command");
                    break;
                }
                }
                string[] splittedString = stringEntered.Split(" ");
                listOfNodes = new List <OpcNodeInfo>(); //or initialize it when declared and clear the list here?
                OpcNodeInfo machineNode;
                foreach (string substring in splittedString)
                {
                    machineNode = client.BrowseNode($"ns=2;");
                    // if(!machineNode.Name.IsNull)
                    // {
                    OpcNodeInfo jobnode = machineNode.Child("Job");
                    listOfNodes.Add(machineNode);
                    //}
                }
                OpcBrowseNode             test           = new OpcBrowseNode("s=Message");
                IEnumerable <OpcNodeInfo> infoAboutNodes = client.BrowseNodes(test);
                foreach (string element in splittedString)
                {
                    List <OpcReadNode> liste = new List <OpcReadNode>();
                    liste.Add(new OpcReadNode("s=Message"));
                    //OpcNodeInfo info = client.BrowseNode($"ns=2;s=Message");
                    List <OpcBrowseNode> liste2 = new List <OpcBrowseNode>();
                    //OpcBrowseNode test = new OpcBrowseNode("s=Message");
                    IEnumerable <OpcNodeInfo> info = client.BrowseNodes(test);
                    Console.WriteLine("\n**********************************");
                    Console.WriteLine("Writing the infoElements...");
                    Console.WriteLine("**********************************\n");

                    foreach (OpcNodeInfo infoElement in info)
                    {
                        Console.WriteLine("NodeID: " + infoElement.NodeId);
                        Console.WriteLine("InfoElement:: " + infoElement.ToString() + "\n");
                    }
                    var nodeOfInterest = client.ReadNode($"ns=2;s={stringEntered}");
                    if (nodeOfInterest.Value != null)
                    {
                        Console.Write($"The value of the node is: {nodeOfInterest.Value}\t");
                        Console.WriteLine($"The ID of the node is: {nodeOfInterest.DataTypeId}\n");
                    }
                }

                if (client.State == OpcClientState.Connected)
                {
                    var temperature = client.ReadNode("ns=2;s=Temperature");
                    var message     = client.ReadNode("ns=2;s=Message");
                    var level       = client.ReadNode("ns=2;s=Level");
                    Console.WriteLine($"Current Temperature is {temperature} °C");
                    Console.WriteLine($"Current message is {message}");
                    Console.WriteLine($"Level: {level}");
                }

                Thread.Sleep(1000);
            }
        }
    }
        private static async Task onDesiredPropertiesUpdate(TwinCollection desiredProperties, object userContext)
        {
            if (desiredProperties.Count == 0)
            {
                Console.WriteLine("Empty desired properties ignored.");

                return;
            }

            try
            {
                Console.WriteLine("Desired property change:");
                Console.WriteLine(JsonConvert.SerializeObject(desiredProperties));

                var client = userContext as ModuleClient;

                if (client == null)
                {
                    throw new InvalidOperationException($"UserContext doesn't contain expected ModuleClient");
                }

                var reportedProperties = new TwinCollection();

                if (desiredProperties.Contains("address"))
                {
                    if (desiredProperties["address"] != null)
                    {
                        Address = desiredProperties["address"];
                    }
                    else
                    {
                        Address = DefaultAddress;
                    }

                    Console.WriteLine($"Address changed to {Address}");

                    reportedProperties["address"] = Address;
                }

                if (desiredProperties.Contains("nodePotentio1"))
                {
                    if (desiredProperties["nodePotentio1"] != null)
                    {
                        NodePotentio1 = desiredProperties["nodePotentio1"];
                    }
                    else
                    {
                        NodePotentio1 = DefaultNodePotentio1;
                    }

                    Console.WriteLine($"NodePotentio1 changed to {NodePotentio1}");

                    reportedProperties["nodePotentio1"] = NodePotentio1;
                }

                if (desiredProperties.Contains("nodePotentio2"))
                {
                    if (desiredProperties["nodePotentio2"] != null)
                    {
                        NodePotentio2 = desiredProperties["nodePotentio2"];
                    }
                    else
                    {
                        NodePotentio2 = DefaultNodePotentio2;
                    }

                    Console.WriteLine($"NodePotentio2 changed to {NodePotentio2}");

                    reportedProperties["nodePotentio2"] = NodePotentio2;
                }

                if (desiredProperties.Contains("nodeSwitch1"))
                {
                    if (desiredProperties["nodeSwitch1"] != null)
                    {
                        NodeSwitch1 = desiredProperties["nodeSwitch1"];
                    }
                    else
                    {
                        NodeSwitch1 = DefaultNodeSwitch1;
                    }

                    Console.WriteLine($"NodeSwitch1 changed to {NodeSwitch1}");

                    reportedProperties["nodeSwitch1"] = NodeSwitch1;
                }

                if (desiredProperties.Contains("nodeSwitch2"))
                {
                    if (desiredProperties["nodeSwitch2"] != null)
                    {
                        NodeSwitch2 = desiredProperties["nodeSwitch2"];
                    }
                    else
                    {
                        NodeSwitch2 = DefaultNodeSwitch2;
                    }

                    Console.WriteLine($"NodeSwitch2 changed to {NodeSwitch2}");

                    reportedProperties["nodeSwitch2"] = NodeSwitch2;
                }

                if (desiredProperties.Contains("nodeRelay1"))
                {
                    if (desiredProperties["nodeRelay1"] != null)
                    {
                        NodeRelay1 = desiredProperties["nodeRelay1"];
                    }
                    else
                    {
                        NodeRelay1 = DefaultNodeRelay1;
                    }

                    Console.WriteLine($"NodeRelay1 changed to {NodeRelay1}");

                    reportedProperties["nodeRelay1"] = NodeRelay1;
                }

                if (desiredProperties.Contains("nodeRelay2"))
                {
                    if (desiredProperties["nodeRelay2"] != null)
                    {
                        NodeRelay2 = desiredProperties["nodeRelay2"];
                    }
                    else
                    {
                        NodeRelay2 = DefaultNodeRelay2;
                    }

                    Console.WriteLine($"NodeRelay2 changed to {NodeRelay2}");

                    reportedProperties["nodeRelay2"] = NodeRelay2;
                }

                if (desiredProperties.Contains("licenseKey"))
                {
                    if (desiredProperties["licenseKey"] != null)
                    {
                        LicenseKey = desiredProperties["licenseKey"];
                    }
                    else
                    {
                        LicenseKey = DefaultLicenseKey;
                    }

                    Console.WriteLine($"LicenseKey changed to {LicenseKey}");

                    reportedProperties["licenseKey"] = LicenseKey;
                }

                if (desiredProperties.Contains("minimalLogLevel"))
                {
                    if (desiredProperties["minimalLogLevel"] != null)
                    {
                        var minimalLogLevel = desiredProperties["minimalLogLevel"];

                        // casting from int to enum needed
                        var minimalLogLevelInteger = Convert.ToInt32(minimalLogLevel);

                        MinimalLogLevel = (LogLevelMessage.LogLevel)minimalLogLevelInteger;
                    }
                    else
                    {
                        MinimalLogLevel = DefaultMinimalLogLevel;
                    }

                    Console.WriteLine($"MinimalLogLevel changed to '{MinimalLogLevel}'");

                    reportedProperties["minimalLogLevel"] = MinimalLogLevel;
                }
                else
                {
                    Console.WriteLine($"MinimalLogLevel ignored");
                }

                if (reportedProperties.Count > 0)
                {
                    await client.UpdateReportedPropertiesAsync(reportedProperties);

                    if (opcClient != null)
                    {
                        opcClient.Disconnect();

                        if (LicenseKey != string.Empty)
                        {
                            Opc.UaFx.Licenser.LicenseKey = LicenseKey;
                        }
                        else
                        {
                            Console.WriteLine("No license key available.");

                            Opc.UaFx.Licenser.LicenseKey = string.Empty;
                        }

                        opcClient.ServerAddress = new Uri(Address);
                        opcClient.Connect();

                        var commands = new List <OpcSubscribeDataChange>();

                        if (!string.IsNullOrEmpty(NodePotentio1))
                        {
                            commands.Add(new OpcSubscribeDataChange(NodePotentio1, OpcDataChangeTrigger.StatusValue, HandleDataChangedMachineLineNode));
                        }
                        else
                        {
                            System.Console.WriteLine("Ignored empty NodePotentio1");
                        }

                        if (!string.IsNullOrEmpty(NodePotentio2))
                        {
                            commands.Add(new OpcSubscribeDataChange(NodePotentio2, OpcDataChangeTrigger.StatusValue, HandleDataChangedMachineLineNode));
                        }
                        else
                        {
                            System.Console.WriteLine("Ignored empty NodePotentio2");
                        }

                        if (!string.IsNullOrEmpty(NodeSwitch1))
                        {
                            commands.Add(new OpcSubscribeDataChange(NodeSwitch1, OpcDataChangeTrigger.StatusValue, HandleDataChangedMachineLineNode));
                        }
                        else
                        {
                            System.Console.WriteLine("Ignored empty NodeSwitch1");
                        }

                        if (!string.IsNullOrEmpty(NodeSwitch2))
                        {
                            commands.Add(new OpcSubscribeDataChange(NodeSwitch2, OpcDataChangeTrigger.StatusValue, HandleDataChangedMachineLineNode));
                        }
                        else
                        {
                            System.Console.WriteLine("Ignored empty NodeSwitch2");
                        }

                        if (!string.IsNullOrEmpty(NodeRelay1))
                        {
                            commands.Add(new OpcSubscribeDataChange(NodeRelay1, OpcDataChangeTrigger.StatusValue, HandleDataChangedMachineLineNode));
                        }
                        else
                        {
                            System.Console.WriteLine("Ignored empty NodeRelay1");
                        }

                        if (!string.IsNullOrEmpty(NodeRelay2))
                        {
                            commands.Add(new OpcSubscribeDataChange(NodeRelay2, OpcDataChangeTrigger.StatusValue, HandleDataChangedMachineLineNode));
                        }
                        else
                        {
                            System.Console.WriteLine("Ignored empty NodeRelay2");
                        }

                        OpcSubscription subscription = opcClient.SubscribeNodes(commands);

                        Console.WriteLine($"Client started... (listening to '{NodePotentio1},{NodePotentio2},{NodeSwitch1},{NodeSwitch2},{NodeRelay1},{NodeRelay2}' at '{Address}')");
                    }
                    else
                    {
                        Console.WriteLine("Client construction postponed.");
                    }

                    Console.WriteLine("Changes to desired properties can be enforced by restarting the module.");
                }
            }
            catch (AggregateException ex)
            {
                Console.WriteLine($"Desired properties change error: {ex.Message}");

                var logLevelMessage = new LogLevelMessage {
                    logLevel = LogLevelMessage.LogLevel.Error, code = "98", message = $"Desired properties change error: {ex.Message}"
                };

                await SendLogLevelMessage(logLevelMessage);

                foreach (Exception exception in ex.InnerExceptions)
                {
                    Console.WriteLine($"Error when receiving desired properties: {exception}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error when receiving desired properties: {ex.Message}");

                var logLevelMessage = new LogLevelMessage {
                    logLevel = LogLevelMessage.LogLevel.Error, code = "99", message = $"Error when receiving desired properties: {ex.Message}"
                };

                await SendLogLevelMessage(logLevelMessage);
            }
        }
示例#15
0
        public static void Main(string[] args)
        {
            //// If the server domain name does not match localhost just replace it
            //// e.g. with the IP address or name of the server machine.

            var client = new OpcClient("opc.tcp://localhost:4840/SampleServer");

            client.Connect();

            {
                // Read the historical 'Raw' data.
                // - for one specific node.
                // - the whole history in one request.
                var rawHistory = client.ReadNodeHistory(
                    DateTime.UtcNow.Date.AddHours(6),
                    DateTime.UtcNow.Date.AddHours(6).AddSeconds(10),
                    "ns=2;s=Machine_1/Position");

                Console.WriteLine("Read the historical 'Raw' data...");

                foreach (var item in rawHistory)
                {
                    Console.WriteLine("{0} - {1}", item.Timestamp, item.Value);
                }
            }

            {
                // Read the historical 'Raw' data page wise.
                // - for one specific node.
                // - the whole history partitioned into multiple requests.
                var rawHistoryNavigator = client.ReadNodeHistory(
                    DateTime.UtcNow.Date.AddHours(6),
                    DateTime.UtcNow.Date.AddHours(6).AddSeconds(10),
                    2,
                    "ns=2;s=Machine_1/Position");

                Console.WriteLine("Read the historical 'Raw' data page wise...");

                do
                {
                    foreach (var item in rawHistoryNavigator)
                    {
                        Console.WriteLine("{0} - {1}", item.Timestamp, item.Value);
                    }

                    Console.Write("Press any key to read the next page...");
                    Console.ReadKey();
                    Console.WriteLine();
                }while (rawHistoryNavigator.MoveNextPage());
            }

            {
                // Read the historical 'ModifiedRaw' data.
                // - for one specific node.
                // - the whole history in one request.
                var modifiedRawHistory = client.ReadNodeHistoryModified(
                    DateTime.UtcNow.Date.AddHours(6),
                    DateTime.UtcNow.Date.AddHours(6).AddSeconds(300),
                    "ns=2;s=Machine_1/Position");

                Console.WriteLine("Read the historical 'ModifiedRaw' data...");

                foreach (var item in modifiedRawHistory)
                {
                    Console.WriteLine("{0} - {1}", item.Timestamp, item.Value);
                    Console.WriteLine("\t[{0}] by {1}", item.ModificationType, item.ModificationUserName);
                }
            }

            {
                // Read the historical 'ModifiedRaw' data page wise.
                // - for one specific node.
                // - the whole history partitioned into multiple requests.
                var modifiedRawHistoryNavigator = client.ReadNodeHistoryModified(
                    DateTime.UtcNow.Date.AddHours(6),
                    DateTime.UtcNow.Date.AddHours(6).AddSeconds(300),
                    2,
                    "ns=2;s=Machine_1/Position");

                Console.WriteLine("Read the historical 'ModifiedRaw' data page wise...");

                do
                {
                    foreach (var item in modifiedRawHistoryNavigator)
                    {
                        Console.WriteLine("{0} - {1}", item.Timestamp, item.Value);
                        Console.WriteLine("\t[{0}] by {1}", item.ModificationType, item.ModificationUserName);
                    }

                    Console.Write("Press any key to read the next page...");
                    Console.ReadKey();
                    Console.WriteLine();
                }while (modifiedRawHistoryNavigator.MoveNextPage());
            }

            {
                // Read the historical data 'at time'.
                // - for one specific node.
                // - the whole history for each time specified.
                var atTimeHistory = client.ReadNodeHistoryAtTime(
                    new DateTime[]
                {
                    DateTime.UtcNow.Date.AddHours(6),
                    DateTime.UtcNow.Date.AddHours(6).AddSeconds(10),
                    DateTime.UtcNow.Date.AddHours(6).AddSeconds(20),
                    DateTime.UtcNow.Date.AddHours(6).AddSeconds(30),
                    DateTime.UtcNow.Date.AddHours(6).AddSeconds(40),
                    DateTime.UtcNow.Date.AddHours(6).AddSeconds(50),
                },
                    "ns=2;s=Machine_1/Position");

                Console.WriteLine("Read the historical data 'at time'...");

                foreach (var item in atTimeHistory)
                {
                    Console.WriteLine("{0} - {1}", item.Timestamp, item.Value);
                }
            }

            {
                // Read the historical data 'processed'.
                // - for one specific node.
                // - the whole history is processed on the server side.
                var processedHistory = client.ReadNodeHistoryProcessed(
                    DateTime.UtcNow.Date.AddHours(6),
                    DateTime.UtcNow.Date.AddHours(6).AddMinutes(30),
                    OpcAggregateType.Maximum,
                    "ns=2;s=Machine_1/Position");

                Console.WriteLine("Read the historical data 'processed'...");

                foreach (var item in processedHistory)
                {
                    Console.WriteLine("{0} - {1}", item.Timestamp, item.Value);
                }
            }

            client.Disconnect();
            Console.ReadKey(true);
        }
示例#16
0
        public static void Main(string[] args)
        {
            //// To simple use the in code configuration you just need to configure your client
            //// instance using the Configuration property of it.
            //// By default it is not necessary to explicitly configure an OPC UA client. But in case
            //// of advanced and productive scenarios you will have to.

            // If the server domain name does not match localhost just replace it
            // e.g. with the IP address or name of the server machine.
            var client = new OpcClient("opc.tcp://*****:*****@"%LocalApplicationData%\My Application\App Certificates";
            securityConfiguration.RejectedCertificateStore.StorePath
                = @"%LocalApplicationData%\My Application\Rejected Certificates";
            securityConfiguration.TrustedIssuerCertificates.StorePath
                = @"%LocalApplicationData%\My Application\Trusted Issuer Certificates";
            securityConfiguration.TrustedPeerCertificates.StorePath
                = @"%LocalApplicationData%\My Application\Trusted Peer Certificates";

            //// It is not necessary that all certificate stores have to point to the same root
            //// directory as above. Each store can also point to a totally different directory.

            client.Configuration = configuration;

            // 3rd Way: Directly change the default configuration of the client instance using the
            //         Configuration property.
            client.Configuration.ClientConfiguration.DefaultSessionTimeout = 300000; // 5 Minutes

            client.Connect();
            client.Disconnect();

            // In case you are using the OpcClientApplication class, you can directly configure
            // your client/application using the Configuration property of the application instance
            // as the following code does demonstrate.
            var app = new OpcClientApplication("opc.tcp://localhost:4840/SampleServer");

            app.Configuration.ClientConfiguration.DefaultSessionTimeout = 300000; // 5 Minutes

            app.Run();
        }
示例#17
0
 public void Disconnect()
 {
     _client?.Disconnect();
     Connected = false;
 }
示例#18
0
 public void Dispose()
 {
     Client.Disconnect();
 }
示例#19
0
        public static void Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                Console.WriteLine("Enter ip address of the server (or localhost)");
                return;
            }
            string serverIP = args[0];

            //// If the server domain name does not match localhost just replace it
            //// e.g. with the IP address or name of the server machine.

            //string serverURL = "https://192.168.0.102:4840/SampleServer";
            //string serverURL = "opc.tcp://localhost:4840/SampleServer";
            string serverURL = $"opc.tcp://{serverIP}:4840/SampleServer";

            #region 1st Way: Use the OpcClient class.
            {
                // The OpcClient class interacts with one OPC UA server. While this class
                // provides session based access to the different OPC UA services of the
                // server, it does not implement a main loop.
                //var client = new OpcClient("opc.tcp://localhost:4840/SampleServer");

                try
                {
                    var client = new OpcClient(serverURL);
                    Console.WriteLine($"Connected on {serverURL}");
                    client.Connect();
                    var node = client.BrowseNode(OpcObjectTypes.ObjectsFolder);
                    Browse(node);

                    while (true)
                    {
                        Program.CommunicateWithServer(client);
                        Thread.Sleep(1000);
                    }

                    client.Disconnect();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            #endregion

            #region 2nd Way: Use the OpcClientApplication class.
            {
                //// The OpcClientApplication class uses a single OpcClient instance which is
                //// wrapped within a main loop.
                ////
                //// Remarks
                //// - The app instance starts a main loop when the session to the server has
                ////   been established.
                //// - Custom client/session dependent code have to be implemented within the event
                ////   handler of the Started event.
                //var app = new OpcClientApplication("opc.tcp://localhost:4840/SampleServer");
                //app.Started += Program.HandleAppStarted;

                //app.Run();
            }
            #endregion
        }