private static void HandleClientConnected(object sender, EventArgs e) { Console.Clear(); Subscription?.Unsubscribe(); Subscription = ((OpcClient)sender).SubscribeNodes( new OpcSubscribeDataChange("nsu=http://sampleserver/cameras;s=Cameras/Var9700", HandleDataChange), new OpcSubscribeDataChange("nsu=http://sampleserver/conveyors;s=Conveyors/Var11100", HandleDataChange), new OpcSubscribeDataChange("nsu=http://sampleserver/doors;s=Doors/Var11400", HandleDataChange), new OpcSubscribeDataChange("nsu=http://sampleserver/files;s=Files/Var10800", HandleDataChange), new OpcSubscribeDataChange("nsu=http://sampleserver/motors;s=Motors/Var11400", HandleDataChange)); foreach (var monitoredItem in Subscription.MonitoredItems) { Data[monitoredItem.NodeId.ValueAsString] = null; if (monitoredItem.Status.IsCreated) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("{0} - active!", monitoredItem.NodeId.Value); } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("{0} - inactive!", monitoredItem.NodeId.Value); } Console.ResetColor(); } Console.WriteLine(new string('-', 30)); }
public void RegisterSubscribe() { OpcSubscribeDataChange[] commands = new OpcSubscribeDataChange[] { new OpcSubscribeDataChange(OPCUAWorkerPaths.MainPressure_path, HandleAnalogDataChange), new OpcSubscribeDataChange(OPCUAWorkerPaths.CrioPressure_path, HandleAnalogDataChange) }; var client = opcobjects.get_OpcClietn(); OpcSubscription subscription = opcobjects.get_OpcClietn().SubscribeNodes(commands); }
private static void ConsumeDataChanges(object state) { var client = (OpcClient)state; var subscription = dataChangeSubscription = client.SubscribeNodes(); subscription.AddMonitoredItem(CreateMonitoredItems(client, "ns=2;s=Data")); subscription.ReceivedDataChangeCallback = HandleDataChange; // Enforce the fastest supported publishing interval. subscription.PublishingInterval = 0; // Disable monitored item related cache und data change events. subscription.UseMonitoredItemDataCache = false; // Commit recent changes to the subscription. subscription.ApplyChanges(); while (!consumerControl.IsCancellationRequested) { try { var values = dataChanges.Take(consumerControl.Token); for (int index = 0; index < values.Length; index++) { var value = values[index]; if (value.Value is DateTime timestamp) { Console.WriteLine( "{0} BULK: Completed (Duration = {1} ms)", DateTime.Now, DateTime.UtcNow.Subtract(timestamp).TotalMilliseconds); } else { Console.WriteLine( "{0} BULK: New Data: {1}", DateTime.Now, value); } } } catch (OperationCanceledException) { break; } } }
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(); }
public OpcSubscription Subscribe(Common.DataSubscription subscriptionDef) { string[] nodes = subscriptionDef.monitored_items.Split("$"); string[] nodeparts; int ns; string path; List <OpcSubscribeNode> nodesList = new List <OpcSubscribeNode>(); OpcDataChangeFilter filter; if (subscriptionDef.report_on_timestamp_change) { filter = new OpcDataChangeFilter(OpcDataChangeTrigger.StatusValueTimestamp); } else { filter = new OpcDataChangeFilter(OpcDataChangeTrigger.StatusValue); } switch (subscriptionDef.deadband_type.ToLower()) { case "percent": filter.DeadbandType = OpcDeadbandType.Percent; break; case "absolute": filter.DeadbandType = OpcDeadbandType.Absolute; break; default: filter.DeadbandType = OpcDeadbandType.None; break; } filter.DeadbandValue = subscriptionDef.deadband; // create an empty subscription OpcSubscription sub = _client.SubscribeNodes(); // create a monitoredItem for each tag to be monitored and add it to the subscription OpcMonitoredItem thisItem; foreach (string node in nodes) { nodeparts = node.Split(":"); ns = int.Parse(nodeparts[0]); path = nodeparts[1]; thisItem = new OpcMonitoredItem(new OpcNodeId(path, ns), OpcAttribute.Value); thisItem.DataChangeReceived += DataChangeReceived; thisItem.Tag = Guid.Parse(nodeparts[2]); thisItem.Filter = filter; sub.AddMonitoredItem(thisItem); } //set the interval (milliseconds, 0 = whenever the value changes) sub.PublishingInterval = subscriptionDef.interval; sub.PublishingIsEnabled = true; // make the server aware of the changes to the subscription sub.ApplyChanges(); // set the Tag property of the subscription to the DataSubscription object that came from the database for later reference sub.Tag = subscriptionDef; // set the subscription-enabled status if (subscriptionDef.enabled) { sub.ChangeMonitoringMode(OpcMonitoringMode.Reporting); } else { sub.ChangeMonitoringMode(OpcMonitoringMode.Disabled); } sub.StartPublishing(); return(sub); }
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); } }
private static void ThreadBody() { try { if (LicenseKey != string.Empty) { Opc.UaFx.Licenser.LicenseKey = LicenseKey; } else { Console.WriteLine("No license key available."); Opc.UaFx.Licenser.LicenseKey = string.Empty; } opcClient = new OpcClient(Address); opcClient.Connecting += OpcClient_Connecting; opcClient.Connected += OpcClient_Connected; opcClient.BreakDetected += OpcClient_BreakDetected; opcClient.Disconnected += OpcClient_Disconnected; opcClient.Disconnecting += OpcClient_Disconnecting; opcClient.Reconnected += OpcClient_Reconnected; opcClient.Reconnecting += OpcClient_Reconnecting; 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}')"); while (true) { // keep thread alive Thread.Sleep(1000); } } catch (System.Exception ex) { // TODO: Test for Timeout towards OPC-UA Server connection Console.WriteLine($"Fatal ThreadBody exception: {ex.Message}"); var logLevelMessage = new LogLevelMessage { logLevel = LogLevelMessage.LogLevel.Critical, code = "00", message = $"ThreadBody exception: {ex.Message}" }; SendLogLevelMessage(logLevelMessage).Wait(); Console.WriteLine("Halted..."); } }