public bool startClient() { try{ //Tenta Encerrar Cliente OPC if (this.server != null) { this.stopClient(); } // Define the cancellation token. this.readingCancelationTokenSource = new CancellationTokenSource(); this.readingCancelationToken = this.readingCancelationTokenSource.Token; Uri url = UrlBuilder.Build(this.name, this.host); this.server = new OpcDaServer(url); this.server.Connect(); Console.WriteLine("Servidor OPC Instanciado na url {0}", url); return(true); } catch (Exception e) { //Console.Write("Falha ao Iniciar Conexão do Opc"); Console.Write("Falha ao Iniciar Conexão do Opc -> "); //Console.Write(e.ToString()); Console.Write(e.ToString()); } return(false); }
//private static string server = String.Format("opcda:/{0}", DatabaseInteractor.GetServerName()); public static object ReadTag(string serverName, string opcTag = "") { Uri url = UrlBuilder.Build(serverName); object readString; using (var client = new OpcDaServer(url)) { client.Connect(); var g1 = client.AddGroup("g1"); g1.IsActive = true; var item = new[] { new OpcDaItemDefinition { ItemId = opcTag, IsActive = true } }; g1.AddItems(item); try { readString = g1.Read(g1.Items)[0].Value; return(readString); } catch (Exception e) { log.Error(String.Format("Error reading Tag {0}", opcTag)); log.Error(e); return(null); } } }
public void BrowsingAnOpcDaServerLocally() { Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1"); using (var server = new OpcDaServer(url)) { // Connect to the server first. server.Connect(); // Browse elements. var browser = new OpcDaBrowserAuto(server); BrowseChildren(browser); // The output should be like the following: // #MonitorACLFile (ItemId: #MonitorACLFile, IsHint: False, IsItem: True, HasChildren: False) // @Clients (ItemId: @Clients, IsHint: False, IsItem: True, HasChildren: False) // Configured Aliases (ItemId: Configured Aliases, IsHint: False, IsItem: False, HasChildren: True) // Simulation Items (ItemId: Simulation Items, IsHint: False, IsItem: False, HasChildren: True) // Bucket Brigade (ItemId: Bucket Brigade, IsHint: False, IsItem: False, HasChildren: True) // ArrayOfReal8 (ItemId: Bucket Brigade.ArrayOfReal8, IsHint: False, IsItem: True, HasChildren: False) // ArrayOfString (ItemId: Bucket Brigade.ArrayOfString, IsHint: False, IsItem: True, HasChildren: False) // Boolean (ItemId: Bucket Brigade.Boolean, IsHint: False, IsItem: True, HasChildren: False) // Int1 (ItemId: Bucket Brigade.Int1, IsHint: False, IsItem: True, HasChildren: False) // Int2 (ItemId: Bucket Brigade.Int2, IsHint: False, IsItem: True, HasChildren: False) // Int4 (ItemId: Bucket Brigade.Int4, IsHint: False, IsItem: True, HasChildren: False) // ... } }
private static OpcDaGroup CreateGroupWithItems(OpcDaServer server) { // Create a group with items. OpcDaGroup group = server.AddGroup("MyGroup"); group.IsActive = true; var definition1 = new OpcDaItemDefinition { ItemId = "Bucket Brigade.Int4", IsActive = true }; var definition2 = new OpcDaItemDefinition { ItemId = "Random.Int2", IsActive = true }; OpcDaItemDefinition[] definitions = { definition1, definition2 }; OpcDaItemResult[] results = group.AddItems(definitions); // Handle adding results. foreach (OpcDaItemResult result in results) { if (result.Error.Failed) { Console.WriteLine("Error adding items: {0}", result.Error); } } return(group); }
internal static void WriteTag(string serverName, string opcTag, object valueToWrite) { Uri url = UrlBuilder.Build(serverName); using (var client = new OpcDaServer(url)) { client.Connect(); var g1 = client.AddGroup("g1"); var item = new[] { new OpcDaItemDefinition { ItemId = opcTag, IsActive = true } }; g1.AddItems(item); object[] writeObject = { valueToWrite }; try { g1.Write(g1.Items, writeObject); } catch (Exception e) { log.Error(String.Format("Error writing Tag {opcTag}", opcTag)); log.Error(e); } } }
public async Task GetAValueOfAnItemBySubscription() { Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1"); using (var server = new OpcDaServer(url)) { // Connect to the server first. server.Connect(); // Create a group with items. OpcDaGroup group = CreateGroupWithItems(server); // Configure subscription. group.ValuesChanged += OnGroupValuesChanged; group.UpdateRate = TimeSpan.FromMilliseconds(100); // ValuesChanged won't be triggered if zero // Wait some time. await Task.Delay(1000); // The output should be like the following: // ItemId: Bucket Brigade.Int4; Value: 0; Quality: Good+Good+NotLimited; Timestamp: 04/19/2016 12:41:11 +03:00 // ItemId: Random.Int2; Value: 0; Quality: Bad+BadOutOfService+NotLimited; Timestamp: 04/19/2016 12:41:11 +03:00 // ItemId: Random.Int2; Value: 41; Quality: Good+Good+NotLimited; Timestamp: 04/19/2016 12:41:13 +03:00 // ItemId: Random.Int2; Value: 18467; Quality: Good+Good+NotLimited; Timestamp: 04/19/2016 12:41:13 +03:00 // ... } }
public async Task ReadValiesAsynchronously() { Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1"); using (var server = new OpcDaServer(url)) { // Connect to the server first. server.Connect(); // Create a group with items. OpcDaGroup group = CreateGroupWithItems(server); // Read values of items from device asynchronously. OpcDaItemValue[] values = await group.ReadAsync(group.Items); // Output values foreach (OpcDaItemValue value in values) { Console.WriteLine("ItemId: {0}; Value: {1}; Quality: {2}; Timestamp: {3}", value.Item.ItemId, value.Value, value.Quality, value.Timestamp); } // The output should be like the following: // ItemId: Bucket Brigade.Int4; Value: 0; Quality: Good+Good+NotLimited; Timestamp: 04/18/2016 13:40:57 +03:00 // ItemId: Random.Int2; Value: 26500; Quality: Good+Good+NotLimited; Timestamp: 04/18/2016 13:40:57 +03:00 values.Should().OnlyContain(v => v.Error.Succeeded); values.Should().OnlyContain(v => v.Quality.Master == OpcDaQualityMaster.Good); } }
public void BrowsingAnOpcDaServerLocally() { Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1"); using (var server = new OpcDaServer(url)) { // Connect to the server first. server.Connect(); // Browse elements. var browser = new OpcDaBrowserAuto(server); BrowseChildren(browser); // The output should be like the following: // #MonitorACLFile (ItemId: #MonitorACLFile, IsHint: False, IsItem: True, HasChildren: False) // @Clients (ItemId: @Clients, IsHint: False, IsItem: True, HasChildren: False) // Configured Aliases (ItemId: Configured Aliases, IsHint: False, IsItem: False, HasChildren: True) // Simulation Items (ItemId: Simulation Items, IsHint: False, IsItem: False, HasChildren: True) // Bucket Brigade (ItemId: Bucket Brigade, IsHint: False, IsItem: False, HasChildren: True) // ArrayOfReal8 (ItemId: Bucket Brigade.ArrayOfReal8, IsHint: False, IsItem: True, HasChildren: False) // ArrayOfString (ItemId: Bucket Brigade.ArrayOfString, IsHint: False, IsItem: True, HasChildren: False) // Boolean (ItemId: Bucket Brigade.Boolean, IsHint: False, IsItem: True, HasChildren: False) // Int1 (ItemId: Bucket Brigade.Int1, IsHint: False, IsItem: True, HasChildren: False) // Int2 (ItemId: Bucket Brigade.Int2, IsHint: False, IsItem: True, HasChildren: False) // Int4 (ItemId: Bucket Brigade.Int4, IsHint: False, IsItem: True, HasChildren: False) // ... } }
public void TestInitialize() { var uri = UrlBuilder.Build("Matrikon.OPC.Simulation.1"); _server = new OpcDaServer(uri); _server.Connect(); _opcBrowser = new OpcDaBrowser1(_server); }
private static OpcDaGroup CreateGroupWithItems(OpcDaServer server) { // Create a group with items. OpcDaGroup group = server.AddGroup("MyGroup"); group.IsActive = true; var definition1 = new OpcDaItemDefinition { ItemId = "Bucket Brigade.Int4", IsActive = true }; var definition2 = new OpcDaItemDefinition { ItemId = "Random.Int2", IsActive = true }; OpcDaItemDefinition[] definitions = {definition1, definition2}; OpcDaItemResult[] results = group.AddItems(definitions); // Handle adding results. foreach (OpcDaItemResult result in results) { if (result.Error.Failed) Console.WriteLine("Error adding items: {0}", result.Error); } return group; }
public static OpcDaGroup Subscribe(String groupname, OpcDaServer server, String[] tags) { var group = server.AddGroup(groupname); group.IsActive = true; group.UpdateRate = TimeSpan.FromMilliseconds(cfg.Period); group.ValuesChanged += Group_ValuesChanged; List <OpcDaItemDefinition> defs = new List <OpcDaItemDefinition>(); foreach (String tag in tags) { var tagdef = new OpcDaItemDefinition { ItemId = tag, IsActive = true }; defs.Add(tagdef); } var results = group.AddItems(defs.ToArray()); int idx = 0; foreach (OpcDaItemResult res in results) { if (res.Error.Failed) { Console.WriteLine("Error adding item {0}: {1}", defs[idx].ItemId, res.Error); } idx++; } return(group); }
public static void SetTagValues(string opcServerUrl, BaseTagValueWrapper valuesWrapper) { lock (GetLockObject(opcServerUrl)) { OpcDaServer server = GetOrCreateServer(opcServerUrl); OpcDaGroup group = server.Groups.FirstOrDefault(x => x.Name == "DecisionsWriteGroup"); if (group == null) { group = server.AddGroup("DecisionsWriteGroup"); } BaseTagValue[] values = valuesWrapper.Values; if (values == null || values.Length == 0) { return; } List <OpcDaItemDefinition> missing = new List <OpcDaItemDefinition>(); foreach (BaseTagValue value in values) { OpcDaItem item = group.Items.FirstOrDefault(x => x.ItemId == value.Path); if (item == null) { missing.Add(new OpcDaItemDefinition { ItemId = value.Path }); } } // ensure that tags are in group if (missing.Count > 0) { OpcDaItemResult[] addResults = group.AddItems(missing); foreach (OpcDaItemResult result in addResults) { if (result.Error.Failed) { throw new Exception($"Set tag value failed: could not add tag to group"); } } } List <OpcDaItem> items = new List <OpcDaItem>(); List <object> itemValues = new List <object>(); foreach (BaseTagValue value in values) { OpcDaItem item = group.Items.First(x => x.ItemId == value.Path); //throw if missing items.Add(item); itemValues.Add(OPCAgentUtils.GetObjectValueFromTag(value)); } HRESULT[] writeResults = group.Write(items, itemValues.ToArray()); foreach (HRESULT writeResult in writeResults) { if (writeResult.Failed) { throw new Exception($"Set tag value failed: Error while writing values: {writeResult.ToString()}"); } } } }
public void TestInitialize() { var uri = UrlBuilder.Build("Matrikon.OPC.Simulation.1"); _server = new OpcDaServer(uri); _server.Connect(); _opcBrowser = new OpcDaBrowser1(_server); }
public void Test_MemoryLeaks() { using (var server = new OpcDaServer(UrlBuilder.Build("Matrikon.OPC.Simulation.1"))) { for (var gi = 0; gi < 500; gi++) { var group = server.AddGroup("g" + gi); var itemDefs = Enumerable.Repeat( new[] { new OpcDaItemDefinition { ItemId = "Random.Int1" }, new OpcDaItemDefinition { ItemId = "Random.Int2", RequestedDataType = TypeConverter.FromVarEnum(VarEnum.VT_R4) } }, 1000).SelectMany(t => t).ToArray(); var cts = new CancellationTokenSource(); group.ValidateItems(itemDefs); group.AddItems(itemDefs); group.SetActiveItems(group.Items); group.SetDataTypes(group.Items, TypeConverter.FromVarEnum(VarEnum.VT_I4)); group.SyncItems(); group.IsActive = true; group.SyncState(); // sync read group.Read(group.Items); group.ReadMaxAge(group.Items, TimeSpan.Zero); // async read Task.WaitAll(group.ReadAsync(group.Items, cts.Token), group.ReadMaxAgeAsync(group.Items, TimeSpan.Zero, cts.Token), group.RefreshAsync(OpcDaDataSource.Cache, cts.Token) ); group.RemoveItems(group.Items.Take(group.Items.Count / 2).ToArray()); // sync read group.Read(group.Items); group.ReadMaxAge(group.Items, TimeSpan.Zero); // async read Task.WaitAll(group.ReadAsync(group.Items, cts.Token), group.ReadMaxAgeAsync(group.Items, TimeSpan.Zero, cts.Token), group.RefreshAsync(OpcDaDataSource.Cache, cts.Token) ); } } GC.Collect(); }
public void TestInitialize() { _matrikon = new OpcDaServer(UrlBuilder.Build("Matrikon.OPC.Simulation.1")); _matrikon.Connect(); _graybox = new OpcDaServer(UrlBuilder.Build("Graybox.Simulator.1")); _graybox.Connect(); _matrikonBrowser = new OpcDaBrowser3(_matrikon); _grayboxBrowser = new OpcDaBrowser3(_graybox); }
static void Main() { Bootstrap.Initialize(); Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1"); using (var server = new OpcDaServer(url)) { // Connect to the server first. server.Connect(); // Create a group with items. OpcDaGroup group = server.AddGroup("MyGroup"); group.IsActive = true; var definition1 = new OpcDaItemDefinition { ItemId = "Random.Boolean", IsActive = true }; var definition2 = new OpcDaItemDefinition { ItemId = "Random.Int1", IsActive = true }; var definition3 = new OpcDaItemDefinition { ItemId = "Random.Int2", IsActive = true }; OpcDaItemDefinition[] definitions = { definition1, definition2, definition3 }; OpcDaItemResult[] results = group.AddItems(definitions); // Handle adding results. foreach (OpcDaItemResult result in results) { if (result.Error.Failed) { Console.WriteLine("Error adding items: {0}", result.Error); } } while (true) { OpcDaItemValue[] values = group.Read(group.Items, OpcDaDataSource.Device); Console.WriteLine("Random.Boolean: {0} \n Random.Int1: {1} \n Random.Int2: {2}", values[0].Value, values[1].Value, values[2].Value); Thread.Sleep(1000); Console.Clear(); } /*int count = server.Groups.Count; * Console.WriteLine(count);*/ } }
public static void AddOrUpdateEventGroup(string opcServerUrl, OpcEventGroup eventGroup) { lock (GetLockObject(opcServerUrl)) { OpcDaServer server = GetServer(opcServerUrl); if (server == null) { return; } if (eventGroup?.Paths == null || eventGroup.Paths.Length == 0) { RemoveEventGroup(opcServerUrl, eventGroup.EventId); return; } // If server isn't connected or there is no ping thread running, then we aren't listening, and can't do anything here: PingThread pingThread; if (!ServerIsConnected(opcServerUrl) || !pingThreads.TryGetValue(opcServerUrl, out pingThread) || !pingThread.IsRunning) { return; } string groupName = "DecisionsGroup_" + eventGroup.EventId; OpcDaGroup group = server.Groups.FirstOrDefault(x => x.Name == groupName); if (group == null) { group = server.AddGroup(groupName); group.IsActive = true; AddItemIdsToGroup(group, eventGroup.Paths); OpcDaItemValue[] values = group.Read(group.Items, OpcDaDataSource.Device); Callback(opcServerUrl, eventGroup.EventId, ConvertToBaseTagValues(values)); // Send all current values in this group before subscribing to further changes group.ValuesChanged += (object sender, OpcDaItemValuesChangedEventArgs e) => { Callback(opcServerUrl, eventGroup.EventId, ConvertToBaseTagValues(e.Values)); }; } else { string[] addedPaths = eventGroup.Paths.Except(group.Items.Select(x => x.ItemId)).ToArray(); OpcDaItem[] removedItems = group.Items.Where(x => !eventGroup.Paths.Contains(x.ItemId)).ToArray(); AddItemIdsToGroup(group, addedPaths); if (removedItems.Length > 0) { group.RemoveItems(removedItems); // could check return value for errors here } } group.PercentDeadband = eventGroup.Deadband; group.UpdateRate = TimeSpan.FromMilliseconds(eventGroup.UpdateRate > 0 ? eventGroup.UpdateRate : 100); // ValuesChanged won't be triggered if zero } }
public static List <OpcDaGroup> BuildSubcribtion(OpcDaServer server, OPCAgentConfig cfg) { List <OpcDaGroup> groups = new List <OpcDaGroup>(); try { string objectFilePath = cfg.AssetFolder + "\\objects.txt"; string tagFilePath = cfg.AssetFolder + "\\tags.txt"; string objLine, tagLine; List <String> objs = new List <string>(); System.IO.StreamReader fileObj = new System.IO.StreamReader(objectFilePath); while ((objLine = fileObj.ReadLine()) != null) { objLine = objLine.Trim(); if (!objLine.StartsWith("//")) { objs.Add(objLine); } } fileObj.Close(); List <String> tags = new List <string>(); System.IO.StreamReader fileTag = new System.IO.StreamReader(tagFilePath); while ((tagLine = fileTag.ReadLine()) != null) { tagLine = tagLine.Trim(); if (!tagLine.StartsWith("//")) { tags.Add(tagLine); } } fileTag.Close(); foreach (String obj in objs) { List <string> objtags = new List <string>(); foreach (string tag in tags) { String objTag = String.Concat(obj, ".", tag); objtags.Add(objTag); } OpcDaGroup g = Subscribe(obj, server, objtags.ToArray()); Console.WriteLine("Subscribe for " + obj); } }catch (Exception exc) { Console.WriteLine("Error: " + exc.Message); } return(groups); }
public void Test_Connect_Disconnect() { var serv = new OpcDaServer(UrlBuilder.Build("Matrikon.OPC.Simulation.1")); serv.Connect(); serv.IsConnected.Should().BeTrue(); serv.Disconnect(); serv.IsConnected.Should().BeFalse(); serv.Connect(); serv.IsConnected.Should().BeTrue(); serv.Disconnect(); serv.IsConnected.Should().BeFalse(); }
public void Test_Connect_Disconnect() { var serv = new OpcDaServer(UrlBuilder.Build("Matrikon.OPC.Simulation.1")); serv.Connect(); serv.IsConnected.Should().BeTrue(); serv.Disconnect(); serv.IsConnected.Should().BeFalse(); serv.Connect(); serv.IsConnected.Should().BeTrue(); serv.Disconnect(); serv.IsConnected.Should().BeFalse(); }
public OpcDaService GetOpcDaService(string host, string serviceProgId) { var service = hostCollection.Where(a => a.ServiceIds.Contains(serviceProgId) && a.Host == host) .FirstOrDefault(); if (service == null) { return(null); } OpcDaService service1 = null; if (CheckServiceExisted(service, serviceProgId)) { service1 = opcDaServices.Find(item => { return(item.Host == service.Host && item.ServiceId == serviceProgId); }); } else { OpcDaServer daService = new OpcDaServer(serviceProgId, service.Host); service1 = new OpcDaService() { Host = service.Host, ServiceId = serviceProgId, Service = daService, OpcDaGroupS = new Dictionary <string, OpcDaGroup>() }; opcDaServices.Add(service1); } if (service1.Service.IsConnected == false) { try { service1.Service.ConnectionStateChanged += new EventHandler <OpcDaServerConnectionStateChangedEventArgs>(ConnectionStateChanged); service1.Service.Connect(); } catch (Exception e) { LogHelper.Log("Connect " + service1.Host + ", ServiceId " + service1.ServiceId + "error!!" + e.Message); } } return(service1); }
public static OpcInitialData GetInitialData(string opcServerUrl, bool valuesOnly) { lock (GetLockObject(opcServerUrl)) { OpcDaServer server = GetOrCreateServer(opcServerUrl); var browser = new OpcDaBrowserAuto(server); OpcDaGroup group = server.AddGroup("DecisionsDataTypeGroup"); OpcNode[] nodes = GetNodesRecursive(browser, group, null); //now that group has all tags, read all initial values at once: OpcDaItemValue[] values = group.Read(group.Items, OpcDaDataSource.Device); server.RemoveGroup(group); return(new OpcInitialData { Nodes = valuesOnly ? null : nodes, Values = ConvertToBaseTagValues(values) }); } }
public static void RemoveEventGroup(string opcServerUrl, string eventId) { lock (GetLockObject(opcServerUrl)) { OpcDaServer server = GetServer(opcServerUrl); if (server == null) { return; } string groupName = "DecisionsGroup_" + eventId; OpcDaGroup group = server.Groups.FirstOrDefault(x => x.Name == groupName); if (group != null) { server.RemoveGroup(group); } } }
static void Main(string[] args) { cfg = new OPCAgentConfig(); cfg.Host = ConfigurationManager.AppSettings["host"]; cfg.OPCName = ConfigurationManager.AppSettings["opcname"]; cfg.Period = Convert.ToInt32(ConfigurationManager.AppSettings["period"]); cfg.AssetFolder = ConfigurationManager.AppSettings["assetfolder"]; var server = new OpcDaServer(UrlBuilder.Build(cfg.OPCName, cfg.Host)); server.Connect(); BuildSubcribtion(server, cfg); System.Threading.Thread.Sleep(cfg.Period * 10); server.Disconnect(); Console.WriteLine("Press any key ...."); Console.ReadLine(); }
private static OpcDaServer GetOrCreateServer(string opcServerUrl) { if (string.IsNullOrEmpty(opcServerUrl)) { throw new Exception("URL is null or empty"); } OpcDaServer server; if (servers.TryGetValue(opcServerUrl, out server)) { return(server); } server = new OpcDaServer(UrlBuilder.Build(opcServerUrl)); server.Connect(); servers[opcServerUrl] = server; return(server); }
public void CreatingAGroupWithItemsInAnOpcDaServer() { Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1"); using (var server = new OpcDaServer(url)) { // Connect to the server first. server.Connect(); // Create a group with items. CreateGroupWithItems(server); server.Groups.Should().HaveCount(1); server.Groups[0].Name.Should().Be("MyGroup"); server.Groups[0].Items.Should().HaveCount(2); server.Groups[0].Items[0].ItemId.Should().Be("Bucket Brigade.Int4"); server.Groups[0].Items[1].ItemId.Should().Be("Random.Int2"); } }
public void CreatingAGroupWithItemsInAnOpcDaServer() { Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1"); using (var server = new OpcDaServer(url)) { // Connect to the server first. server.Connect(); // Create a group with items. CreateGroupWithItems(server); server.Groups.Should().HaveCount(1); server.Groups[0].Name.Should().Be("MyGroup"); server.Groups[0].Items.Should().HaveCount(2); server.Groups[0].Items[0].ItemId.Should().Be("Bucket Brigade.Int4"); server.Groups[0].Items[1].ItemId.Should().Be("Random.Int2"); } }
public void Test_PendingRequests() { using (var server = new OpcDaServer(UrlBuilder.Build("Matrikon.OPC.Simulation.1"))) { server.Connect(); var group = server.AddGroup("g"); var itemDefs = Enumerable.Repeat( new[] { new OpcDaItemDefinition { ItemId = "Random.Int1" }, new OpcDaItemDefinition { ItemId = "Random.Int2", RequestedDataType = TypeConverter.FromVarEnum(VarEnum.VT_R4) } }, 1000).SelectMany(t => t).ToArray(); group.AddItems(itemDefs); group.SetActiveItems(group.Items); group.IsActive = true; group.UpdateRate = TimeSpan.FromMilliseconds(10); group.IsSubscribed = true; CancellationTokenSource cts = new CancellationTokenSource(); List <Task> tasks = new List <Task>(); for (var i = 0; i < 100; i++) { tasks.Add(group.ReadAsync(group.Items, cts.Token)); tasks.Add(group.ReadMaxAgeAsync(group.Items, TimeSpan.Zero, cts.Token)); tasks.Add(group.RefreshAsync(OpcDaDataSource.Device, cts.Token)); tasks.Add(group.RefreshMaxAgeAsync(TimeSpan.Zero, cts.Token)); tasks.Add(group.WriteAsync(group.Items, Enumerable.Repeat((object)1, group.Items.Count).ToArray(), cts.Token)); tasks.Add(group.WriteVQTAsync(group.Items, Enumerable.Repeat(new OpcDaVQT(), group.Items.Count).ToArray(), cts.Token)); } Task.WaitAll(tasks.ToArray()); } GC.Collect(); }
public void Init() { cfg = new OPCAgentConfig(); cfg.Host = Common.GetConfig("host"); cfg.OPCName = Common.GetConfig("opcname"); cfg.Period = Convert.ToInt32(Common.GetConfig("period")); cfg.AssetFolder = Common.GetConfig("assetfolder"); ErrorTags = new List <string>(); if (!String.IsNullOrEmpty(cfg.Host)) { server = new OpcDaServer(UrlBuilder.Build(cfg.OPCName, cfg.Host)); server.Connect(); BuildSubcribtion(server, cfg); } else { Log.Write("Cannot find host address.", LogType.ERROR); } }
public CalcController(ControllerParameters controllerParameters) { this.controllerRole = controllerParameters.ControllerRole; timer = new Stopwatch(); Uri url = UrlBuilder.Build(controllerParameters.OpcServerName); opcServer = new OpcDaServer(url); opcClient = new OpcClient(opcServer, controllerParameters.OpcServerSubstring); SingleTagsNamesForRW = controllerParameters.SingleTagNamesForRW; this.controllerParameters = controllerParameters; //Определение creator'ов для переменных //0.0. Single Tag for reading/writing to OPC singleTagCreator = new SingleTagCreator(opcClient, SingleTagsNamesForRW); //1.0. TemperatureCreator temperatureCreator = new TemperatureCreator(opcClient); //2.0. PressureCreator pressureCreator = new PressureCreator(opcClient); // levelCreator = new LevelCreator(opcClient); //3.0. CapacityCreator capacityCreator = new CapacityCreator(opcClient, singleTagCreator); //4.0. DensityCreator densityCreator = new DensityCreator(opcClient, singleTagCreator); //5.0. ContentCreator contentCreator = new ContentCreator(opcClient, singleTagCreator); //6.0. ContentCreator levelTankCreator = new LevelTankCreator(opcClient, singleTagCreator); //parameterClaculatedSucceedEvent += (o, ea) => CheckForItemInPlcForWritingToPLC(o, (CustomEventArgs)ea); //Запускаем процесс проверки изменения тега в PLC для определения разрешения записи данному экземпляру программы в PLC //Процесс непрерывно раз в 3 периода поллинга проверяет активность тега PLC Task.Run(() => CheckForItemInPlcForWritingToPLC()); }
public void read_group(string opcserver, string group_name, List <string> items) { Uri url = UrlBuilder.Build(opcserver); using (var server = new OpcDaServer(url)) { // Connect to the server first. server.Connect(); // Create a group with items. OpcDaGroup group = server.AddGroup(group_name); IList <OpcDaItemDefinition> definitions = new List <OpcDaItemDefinition>(); int i = 0; foreach (string id in items) { LogHelper.Log("id: " + id); var definition = new OpcDaItemDefinition { ItemId = id, IsActive = true }; definitions.Insert(i++, definition); } group.IsActive = true; OpcDaItemResult[] results = group.AddItems(definitions); OpcDaItemValue[] itemValues = group.Read(group.Items, OpcDaDataSource.Device); // Handle adding results. JsonObject data = new JsonObject(); foreach (OpcDaItemValue item in itemValues) { if (item.Item != null && item.Value != null) { data.Add(item.Item.ItemId, item.Value); } } server.Disconnect(); } }
public async Task WriteValiesToAnItemOfAnOpcServerAsynchronously() { Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1"); using (var server = new OpcDaServer(url)) { // Connect to the server first. server.Connect(); // Create a group with items. OpcDaGroup group = CreateGroupWithItems(server); // Write value to the item. OpcDaItem item = group.Items.FirstOrDefault(i => i.ItemId == "Bucket Brigade.Int4"); OpcDaItem[] items = { item }; object[] values = { 123 }; HRESULT[] results = await group.WriteAsync(items, values); // Handle write result. if (results[0].Failed) { Console.WriteLine("Error writing value"); } // Read and output value. OpcDaItemValue value = group.Read(items, OpcDaDataSource.Device)[0]; Console.WriteLine("ItemId: {0}; Value: {1}; Quality: {2}; Timestamp: {3}", value.Item.ItemId, value.Value, value.Quality, value.Timestamp); // The output should be like the following: // ItemId: Bucket Brigade.Int4; Value: 123; Quality: Good+Good+NotLimited; Timestamp: 04/18/2016 14:04:11 +03:00 value.Value.Should().Be(123); value.Quality.Master.Should().Be(OpcDaQualityMaster.Good); } }
protected OpcDaGroup Subscribe(String groupname, OpcDaServer server, String[] tags) { var group = server.AddGroup(groupname); group.IsActive = true; group.UpdateRate = TimeSpan.FromMilliseconds(cfg.Period); group.ValuesChanged += Group_ValuesChanged; List <OpcDaItemDefinition> defs = new List <OpcDaItemDefinition>(); foreach (String tag in tags) { var tagdef = new OpcDaItemDefinition { ItemId = tag, IsActive = true }; defs.Add(tagdef); } var results = group.AddItems(defs.ToArray()); int idx = 0; foreach (OpcDaItemResult res in results) { if (res.Error.Failed) { if (!res.Error.ToString().Contains("The item ID is not defined in the server address space")) { string err = String.Format("Error adding item {0}: {1}", defs[idx].ItemId, res.Error); Log.Write(err, LogType.WARNING); } } idx++; } return(group); }
/// <summary> /// Initializes a new instance of the <see cref="OpcDaBrowserAuto"/> class. /// </summary> /// <param name="server">The OPC DA server for browsing.</param> public OpcDaBrowserAuto(OpcDaServer server = null) { OpcDaServer = server; }
/// <summary> /// Initializes a new instance of the <see cref="OpcDaBrowser1"/> class. /// </summary> /// <param name="opcDaServer">The OPC DA server for browsing.</param> public OpcDaBrowser1(OpcDaServer opcDaServer = null) : base(opcDaServer) { _currentPath = new string[0]; _itemIdToPath[String.Empty] = _currentPath; }
/// <summary> /// Initializes a new instance of the <see cref="OpcDaBrowser2"/> class. /// </summary> /// <param name="opcDaServer">The OPC DA server for browsing.</param> public OpcDaBrowser2(OpcDaServer opcDaServer = null) { OpcDaServer = opcDaServer; }
public void TestInitialize() { _server = new OpcDaServer(UrlBuilder.Build("Matrikon.OPC.Simulation.1")); _server.Connect(); }
public async Task GetAValueOfAnItemBySubscription() { Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1"); using (var server = new OpcDaServer(url)) { // Connect to the server first. server.Connect(); // Create a group with items. OpcDaGroup group = CreateGroupWithItems(server); // Configure subscription. group.ValuesChanged += OnGroupValuesChanged; group.UpdateRate = TimeSpan.FromMilliseconds(100); // ValuesChanged won't be triggered if zero // Wait some time. await Task.Delay(1000); // The output should be like the following: // ItemId: Bucket Brigade.Int4; Value: 0; Quality: Good+Good+NotLimited; Timestamp: 04/19/2016 12:41:11 +03:00 // ItemId: Random.Int2; Value: 0; Quality: Bad+BadOutOfService+NotLimited; Timestamp: 04/19/2016 12:41:11 +03:00 // ItemId: Random.Int2; Value: 41; Quality: Good+Good+NotLimited; Timestamp: 04/19/2016 12:41:13 +03:00 // ItemId: Random.Int2; Value: 18467; Quality: Good+Good+NotLimited; Timestamp: 04/19/2016 12:41:13 +03:00 // ... } }
public void Test_PendingRequests() { using (var server = new OpcDaServer(UrlBuilder.Build("Matrikon.OPC.Simulation.1"))) { server.Connect(); var group = server.AddGroup("g"); var itemDefs = Enumerable.Repeat( new[] { new OpcDaItemDefinition { ItemId = "Random.Int1" }, new OpcDaItemDefinition { ItemId = "Random.Int2", RequestedDataType = TypeConverter.FromVarEnum(VarEnum.VT_R4) } }, 1000).SelectMany(t => t).ToArray(); group.AddItems(itemDefs); group.SetActiveItems(group.Items); group.IsActive = true; group.UpdateRate = TimeSpan.FromMilliseconds(10); group.IsSubscribed = true; CancellationTokenSource cts = new CancellationTokenSource(); List<Task> tasks = new List<Task>(); for (var i = 0; i < 100; i++) { tasks.Add(group.ReadAsync(group.Items, cts.Token)); tasks.Add(group.ReadMaxAgeAsync(group.Items, TimeSpan.Zero, cts.Token)); tasks.Add(group.RefreshAsync(OpcDaDataSource.Device, cts.Token)); tasks.Add(group.RefreshMaxAgeAsync(TimeSpan.Zero, cts.Token)); tasks.Add(group.WriteAsync(group.Items, Enumerable.Repeat((object)1, group.Items.Count).ToArray(), cts.Token)); tasks.Add(group.WriteVQTAsync(group.Items, Enumerable.Repeat(new OpcDaVQT(), group.Items.Count).ToArray(), cts.Token)); } Task.WaitAll(tasks.ToArray()); } GC.Collect(); }
public async Task WriteValiesToAnItemOfAnOpcServerAsynchronously() { Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1"); using (var server = new OpcDaServer(url)) { // Connect to the server first. server.Connect(); // Create a group with items. OpcDaGroup group = CreateGroupWithItems(server); // Write value to the item. OpcDaItem item = group.Items.FirstOrDefault(i => i.ItemId == "Bucket Brigade.Int4"); OpcDaItem[] items = { item }; object[] values = { 123 }; HRESULT[] results = await group.WriteAsync(items, values); // Handle write result. if (results[0].Failed) { Console.WriteLine("Error writing value"); } // Read and output value. OpcDaItemValue value = group.Read(items, OpcDaDataSource.Device)[0]; Console.WriteLine("ItemId: {0}; Value: {1}; Quality: {2}; Timestamp: {3}", value.Item.ItemId, value.Value, value.Quality, value.Timestamp); // The output should be like the following: // ItemId: Bucket Brigade.Int4; Value: 123; Quality: Good+Good+NotLimited; Timestamp: 04/18/2016 14:04:11 +03:00 value.Value.Should().Be(123); value.Quality.Master.Should().Be(OpcDaQualityMaster.Good); } }
public void Test_MemoryLeaks() { using (var server = new OpcDaServer(UrlBuilder.Build("Matrikon.OPC.Simulation.1"))) { for (var gi = 0; gi < 500; gi++) { var group = server.AddGroup("g" + gi); var itemDefs = Enumerable.Repeat( new[] { new OpcDaItemDefinition { ItemId = "Random.Int1" }, new OpcDaItemDefinition { ItemId = "Random.Int2", RequestedDataType = TypeConverter.FromVarEnum(VarEnum.VT_R4) } }, 1000).SelectMany(t => t).ToArray(); var cts = new CancellationTokenSource(); group.ValidateItems(itemDefs); group.AddItems(itemDefs); group.SetActiveItems(group.Items); group.SetDataTypes(group.Items, TypeConverter.FromVarEnum(VarEnum.VT_I4)); group.SyncItems(); group.IsActive = true; group.SyncState(); // sync read group.Read(group.Items); group.ReadMaxAge(group.Items, TimeSpan.Zero); // async read Task.WaitAll(group.ReadAsync(group.Items, cts.Token), group.ReadMaxAgeAsync(group.Items, TimeSpan.Zero, cts.Token), group.RefreshAsync(OpcDaDataSource.Cache, cts.Token) ); group.RemoveItems(group.Items.Take(group.Items.Count/2).ToArray()); // sync read group.Read(group.Items); group.ReadMaxAge(group.Items, TimeSpan.Zero); // async read Task.WaitAll(group.ReadAsync(group.Items, cts.Token), group.ReadMaxAgeAsync(group.Items, TimeSpan.Zero, cts.Token), group.RefreshAsync(OpcDaDataSource.Cache, cts.Token) ); } } GC.Collect(); }
public async Task ReadValiesAsynchronously() { Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1"); using (var server = new OpcDaServer(url)) { // Connect to the server first. server.Connect(); // Create a group with items. OpcDaGroup group = CreateGroupWithItems(server); // Read values of items from device asynchronously. OpcDaItemValue[] values = await group.ReadAsync(group.Items); // Output values foreach (OpcDaItemValue value in values) { Console.WriteLine("ItemId: {0}; Value: {1}; Quality: {2}; Timestamp: {3}", value.Item.ItemId, value.Value, value.Quality, value.Timestamp); } // The output should be like the following: // ItemId: Bucket Brigade.Int4; Value: 0; Quality: Good+Good+NotLimited; Timestamp: 04/18/2016 13:40:57 +03:00 // ItemId: Random.Int2; Value: 26500; Quality: Good+Good+NotLimited; Timestamp: 04/18/2016 13:40:57 +03:00 values.Should().OnlyContain(v => v.Error.Succeeded); values.Should().OnlyContain(v => v.Quality.Master == OpcDaQualityMaster.Good); } }
public void TestInitialize() { _server = new OpcDaServer(UrlBuilder.Build("Matrikon.OPC.Simulation.1")); _server.Connect(); }
public OpcCommon(OpcDaServer opcDaServer, object userData) : this(opcDaServer.ComObject, userData) { }
public void TestInitialize() { _matrikon = new OpcDaServer(UrlBuilder.Build("Matrikon.OPC.Simulation.1")); _matrikon.Connect(); _graybox = new OpcDaServer(UrlBuilder.Build("Graybox.Simulator.1")); _graybox.Connect(); _matrikonBrowser = new OpcDaBrowser3(_matrikon); _grayboxBrowser = new OpcDaBrowser3(_graybox); }
/// <summary> /// Initializes a new instance of the <see cref="OpcDaBrowser3"/> class. /// </summary> /// <param name="opcDaServer">The OPC DA server for browsing.</param> public OpcDaBrowser3(OpcDaServer opcDaServer = null) { OpcDaServer = opcDaServer; }