internal static OpcDaItemValue[] Create(OpcDaGroup opcDaGroup, OPCITEMSTATE[] ppItemValues,
     HRESULT[] ppErrors)
 {
     try
     {
         var result = new OpcDaItemValue[ppItemValues.Length];
         for (var i = 0; i < result.Length; i++)
         {
             result[i] = new OpcDaItemValue
             {
                 Timestamp = FileTimeConverter.FromFileTime(ppItemValues[i].ftTimeStamp),
                 Value = ppItemValues[i].vDataValue,
                 Quality = ppItemValues[i].wQuality,
                 Error = ppErrors[i],
                 Item = opcDaGroup.GetItem(ppItemValues[i].hClient)
             };
         }
         return result;
     }
     catch (Exception ex)
     {
         Log.Error("Cannot create OpcDaItemValue object.", ex);
         return new OpcDaItemValue[0];
     }
 }
        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);
            }
        }
Exemplo n.º 3
0
        //Создание групп для чтения данных из OPC-сервера
        protected void InitDataGroup(string[] itemDescription, string groupName, out OpcDaGroup dataGroup)
        {
            dataGroup          = opcReader._opcServer.AddGroup(groupName);              //Группа переменных для чтения (записи) из OPC-сервера
            dataGroup.IsActive = true;

            List <OpcDaItemDefinition> itemDefinitions = new List <OpcDaItemDefinition>(); //Definitions для добавления в группу чтения в OPC-сервер

            foreach (var item in opcTagNamesCollection)
            {
                for (int i = 0; i < itemDescription.Length; i++)
                {
                    itemDefinitions.Add(new OpcDaItemDefinition
                    {
                        ItemId   = item + "." + itemDescription[i],
                        IsActive = true
                    });
                }
            }

            OpcDaItemResult[] results = dataGroup.AddItems(itemDefinitions);    //Добавление переменных в группу

            foreach (OpcDaItemResult result in results)
            {
                if (result.Error.Failed)
                {
                    Console.WriteLine("Error adding items: {0}", result.Error);
                }
            }
        }
Exemplo n.º 4
0
        public void WriteValues(string host, string serviceProgId, string groupKey, Dictionary <string, object> itemValuePairs)
        {
            OpcDaService server = GetOpcDaService(host, serviceProgId);

            if (server == null)
            {
                return;
            }

            if (server.OpcDaGroupS.ContainsKey(groupKey) == true)
            {
                OpcDaGroup       group    = server.OpcDaGroupS[groupKey];
                var              keyList  = itemValuePairs.Keys.ToList();
                List <OpcDaItem> itemList = new List <OpcDaItem>();
                keyList.ForEach(ids =>
                {
                    var daItem = group.Items
                                 .Where(a => a.ItemId == ids)
                                 .FirstOrDefault();
                    itemList.Add(daItem);
                });

                object[]  dd  = itemValuePairs.Values.ToArray();
                HRESULT[] res = group.Write(itemList, dd);

                LogHelper.Log("Write HRESULT " + res.ToString());
            }
        }
        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 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
                // ...
            }
        }
Exemplo n.º 7
0
 public void setItemsCount(string groupKey, OpcDaGroup group)
 {
     try
     {
         OpcDaItemValue[] values = group.Read(group.Items, OpcDaDataSource.Device);
         if (values.Length == group.Items.Count)
         {
             for (int i = 0; i < values.Length; ++i)
             {
                 if (values[i].Value != null)
                 {
                     if (itemscountCollection.ContainsKey(groupKey) == false)
                     {
                         itemscountCollection.Add(groupKey, 1);
                         itemstotalCollection.Add(groupKey, 1);
                     }
                     else
                     {
                         itemscountCollection[groupKey] = itemscountCollection[groupKey] + 1;
                         itemstotalCollection[groupKey] = itemstotalCollection[groupKey] + 1;
                     }
                 }
             }
         }
     }
     catch (Exception e)
     {
         LogHelper.Log("Exception: " + e.ToString());
     }
 }
 internal static OpcDaItemValue[] Create(OpcDaGroup opcDaGroup, int dwCount, int[] phClientItems,
     object[] pvValues,
     short[] pwQualities, FILETIME[] pftTimeStamps, HRESULT[] pErrors)
 {
     try
     {
         var values = new OpcDaItemValue[dwCount];
         for (var i = 0; i < values.Length; i++)
         {
             values[i] = new OpcDaItemValue
             {
                 Value = pvValues[i],
                 Item = opcDaGroup.GetItem(phClientItems[i]),
                 Quality = pwQualities[i],
                 Timestamp = FileTimeConverter.FromFileTime(pftTimeStamps[i]),
                 Error = pErrors[i]
             };
         }
         return values;
     }
     catch (Exception ex)
     {
         Log.Error("Cannot create OpcDaItemValue object.", ex);
         return new OpcDaItemValue[0];
     }
 }
Exemplo n.º 9
0
        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()}");
                    }
                }
            }
        }
Exemplo n.º 10
0
        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);*/
            }
        }
Exemplo n.º 11
0
        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
            }
        }
Exemplo n.º 12
0
 //Method writes data to "VAL_CALC" field of Capacity (Density) object and than - to OPC server
 internal void WriteMultiplyItems(OpcDaGroup dataGroup, object[] values)
 {
     OpcDaItem[] items = dataGroup.Items.ToArray();
     try
     {
         HRESULT[] resultsWrite = dataGroup.Write(items, values);
     }
     catch (Exception)
     {
     }
 }
Exemplo n.º 13
0
        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);
        }
Exemplo n.º 14
0
        public void AddGroup(OpcDaService server, string groupKey, TreeNode groupNode, int interval, int count)
        {
            if (server.Service == null)
            {
                return;
            }

            foreach (TreeNode tmpNode in groupNode.Nodes)
            {
                if (tmpNode.Checked)
                {
                    string     md5Str = groupKey + tmpNode.Text;
                    OpcDaGroup group  = null;
                    if (server.OpcDaGroupS.ContainsKey(md5Str) == false)
                    {
                        group = server.Service.AddGroup(md5Str);  // maybe cost lot of time
                        server.OpcDaGroupS.Add(md5Str, group);
                        group.IsActive = true;
                        group.UserData = groupNode;

                        List <OpcDaItemDefinition> itemDefList = new List <OpcDaItemDefinition>();

                        var def = new OpcDaItemDefinition
                        {
                            ItemId   = tmpNode.Text,
                            UserData = groupKey,
                            IsActive = true
                        };
                        itemDefList.Add(def);

                        group.AddItems(itemDefList);

                        GroupEntity groupEntity = new GroupEntity()
                        {
                            Host   = server.Host,
                            ProgId = server.ServiceId
                        };
                        groupCollection.Add(md5Str, groupEntity);
                        group.UpdateRate = TimeSpan.FromMilliseconds(interval); // 1000毫秒触发一次
                    }
                    else
                    {
                        group = server.OpcDaGroupS[md5Str];
                    }
                    groupKeys.Add(md5Str);
                    group.ValuesChanged += MonitorValuesChanged;
                    SetGroupFlag(groupKey, count);
                    // LogHelper.Log("GroupFlag " + GetGroupFlag(groupKey).ToString(), (int)LogHelper.Level.INFO);
                }
                // GetUnits(group);
                // LogHelper.Log("aaa: " + GetUnits(group), (int)LogHelper.Level.INFO);
            }
        }
        public void startReadingGroup(string[] _tagName)
        {
            Console.WriteLine("Adicionando {0} itens ao grupo de leitura", _tagName.Length);

            //remove grupo para uma nova leitura
            if (readingGroup != null)
            {
                try{ this.server.RemoveGroup(readingGroup); } catch (Exception e) { Console.WriteLine(e); }
            }

            readingGroup = this.server.AddGroup("readingGroup");

            readingGroup.IsActive = true;

            List <OpcDaItemDefinition> def = new List <OpcDaItemDefinition>();

            foreach (string t in _tagName)
            {
                Console.WriteLine("Tag ItemID");
                Console.WriteLine(t);
                def.Add(new OpcDaItemDefinition
                {
                    ItemId   = t,
                    IsActive = true
                });
            }

            //cria array com as definicoes
            OpcDaItemDefinition[] definitions = def.ToArray();

            //readingGroup.Items.RemoveAll();

            //readingGroup.RemoveItems(definitions.GetValue());      //remove itens para adicionar eles
            OpcDaItemResult[] results = readingGroup.AddItems(definitions);

            // Handle adding results.
            foreach (OpcDaItemResult result in results)
            {
                if (result.Item != null)
                {
                    Console.WriteLine("Status of item: {0}", result.Item.ItemId);
                }

                if (result.Error.Failed)
                {
                    Console.WriteLine("Error adding items: {0}", result.Error);
                }
                else
                {
                    Console.WriteLine("Success adding items: ");
                }
            }
        }
Exemplo n.º 16
0
 internal OpcDaItem(OpcDaItemDefinition itemDefinition, OPCITEMRESULT itemResult, OpcDaGroup @group)
 {
     Group = @group;
     ClientHandle = 0;
     ServerHandle = itemResult.hServer;
     ItemId = itemDefinition.ItemId;
     RequestedDataType = itemDefinition.RequestedDataType;
     CanonicalDataType = TypeConverter.FromVarEnum((VarEnum) itemResult.vtCanonicalDataType);
     Blob = itemResult.pBlob;
     AccessPath = itemDefinition.AccessPath;
     IsActive = itemDefinition.IsActive;
     AccessRights = (OpcDaAccessRights) itemResult.dwAccessRights;
 }
Exemplo n.º 17
0
        public void StartMonitor(string groupKey, List <string> items, string serverID, string host = "127.0.0.1")
        {
            JsonArray properties = new JsonArray();

            OpcDaService server = GetOpcDaService(host, serverID);

            if (server == null)
            {
                return;
            }
            foreach (string item in items)
            {
                string md5Str = groupKey + item;
                if (server.OpcDaGroupS.ContainsKey(md5Str) == false)
                {
                    OpcDaGroup group = server.Service.AddGroup(md5Str);  // maybe cost lot of time
                    group.IsActive = true;
                    server.OpcDaGroupS.Add(md5Str, group);
                    List <OpcDaItemDefinition> itemDefList = new List <OpcDaItemDefinition>();
                    var def = new OpcDaItemDefinition
                    {
                        ItemId   = item,
                        UserData = groupKey,
                        IsActive = true
                    };
                    itemDefList.Add(def);

                    group.AddItems(itemDefList);
                    groupKeys.Add(md5Str);
                    SetGroupFlag(groupKey, 0);
                    LogHelper.Log("StartMonitoring  is groupId " + md5Str + " interval " + "1000  ms", (int)LogHelper.Level.INFO);
                    setItemsCount(groupKey, group);
                    group.UpdateRate     = TimeSpan.FromMilliseconds(1000); // 1000毫秒触发一次
                    group.ValuesChanged += MonitorValuesChanged;
                    if (!groupCollection.ContainsKey(md5Str))
                    {
                        GroupEntity groupEntity = new GroupEntity()
                        {
                            Host   = server.Host,
                            ProgId = server.ServiceId
                        };
                        groupCollection.Add(md5Str, groupEntity);
                    }
                    LogHelper.Log("groupKeygroupKeygroupKey: " + groupKey);
                    // LogHelper.Log("aaaa: " + GetUnits(group), (int)LogHelper.Level.INFO);
                }
            }
        }
Exemplo n.º 18
0
 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 AsyncRequestManager(OpcDaGroup opcDaGroup)
        {
            var opcDataCallback = new OpcDataCallback
            {
                CancelComplete = OnCancelComplete,
                DataChange = OnDataChange,
                ReadComplete = OnReadComplete,
                WriteComplete = OnWriteComplete
            };

            _connectionPoint = new ConnectionPoint<IOPCDataCallback>(opcDataCallback);

            _slots = new Slots<IAsyncRequest>(OpcConfiguration.MaxSimultaneousRequests);
            _opcDaGroup = opcDaGroup;

            TryConnect(opcDaGroup.ComObject);
        }
Exemplo n.º 20
0
 internal OpcDaItem(OPCITEMATTRIBUTES opcItemDefinition, OpcDaGroup @group)
 {
     Group = @group;
     ClientHandle = opcItemDefinition.hClient;
     ServerHandle = opcItemDefinition.hServer;
     ItemId = opcItemDefinition.szItemID;
     RequestedDataType = TypeConverter.FromVarEnum((VarEnum) opcItemDefinition.vtRequestedDataType);
     CanonicalDataType = TypeConverter.FromVarEnum((VarEnum) opcItemDefinition.vtCanonicalDataType);
     AccessPath = opcItemDefinition.szAccessPath;
     IsActive = opcItemDefinition.bActive;
     AccessRights = (OpcDaAccessRights) opcItemDefinition.dwAccessRights;
     if (opcItemDefinition.pBlob != IntPtr.Zero)
     {
         Blob = new byte[opcItemDefinition.dwBlobSize];
         Marshal.Copy(opcItemDefinition.pBlob, Blob, 0, Blob.Length);
     }
 }
Exemplo n.º 21
0
        public AsyncRequestManager(OpcDaGroup opcDaGroup)
        {
            var opcDataCallback = new OpcDataCallback
            {
                CancelComplete = OnCancelComplete,
                DataChange     = OnDataChange,
                ReadComplete   = OnReadComplete,
                WriteComplete  = OnWriteComplete
            };

            _connectionPoint = new ConnectionPoint <IOPCDataCallback>(opcDataCallback);

            _slots      = new Slots <IAsyncRequest>(OpcConfiguration.MaxSimultaneousRequests);
            _opcDaGroup = opcDaGroup;

            TryConnect(opcDaGroup.ComObject);
        }
Exemplo n.º 22
0
 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);
         }
     }
 }
Exemplo n.º 23
0
        private static OpcNode[] GetNodesRecursive(OpcDaBrowserAuto browser, OpcDaGroup group, OpcNode parentNode)
        {
            OpcDaBrowseElement[] elements = browser.GetElements(parentNode?.FullPath); // fetches from root if null

            OpcNode[] results = elements.Select(x => new OpcNode
            {
                Name     = x.Name,
                FullPath = x.ItemId,
                ItemId   = x.IsItem ? x.ItemId : null
            }).ToArray();

            foreach (OpcNode node in results)
            {
                GetNodesRecursive(browser, group, node);
            }

            if (parentNode != null)
            {
                parentNode.Children = results;

                if (!string.IsNullOrEmpty(parentNode.ItemId)) // fetch data types for tags
                {
                    var def = new OpcDaItemDefinition
                    {
                        ItemId = parentNode.ItemId
                    };
                    OpcDaItemResult[] groupAddResults = group.AddItems(new OpcDaItemDefinition[] { def });

                    foreach (OpcDaItemResult addResult in groupAddResults)
                    {
                        if (addResult.Error.Failed)
                        {
                            throw new Exception($"Could not fetch type data for {parentNode.ItemId}");
                        }
                    }

                    OpcDaItem item = group.Items.FirstOrDefault(x => x.ItemId == parentNode.ItemId);
                    if (item != null)
                    {
                        parentNode.TypeName = item.CanonicalDataType.FullName;
                    }
                }
            }

            return(results);
        }
Exemplo n.º 24
0
        private static void AddItemIdsToGroup(OpcDaGroup group, string[] paths)
        {
            if (paths.Length == 0)
            {
                return;
            }
            OpcDaItemDefinition[] definitions = paths.Select(x => new OpcDaItemDefinition {
                ItemId = x, IsActive = true
            }).ToArray();
            OpcDaItemResult[] results = group.AddItems(definitions);

            foreach (OpcDaItemResult result in results)
            {
                if (result.Error.Failed)
                {
                    ; //todo, error handling?
                }
            }
        }
Exemplo n.º 25
0
        public void ValueChangedCallBack(OpcDaGroup group, OpcDaItemValue[] values)
        {
            JsonObject result = new JsonObject();

            result.Add("timestamp", DgiotHelper.Now());
            string groupKey = "";

            JsonObject  properties = new JsonObject();
            List <Item> collection = new List <Item>();

            values.ToList().ForEach(v =>
            {
                if (v.Item != null && v.Value != null)
                {
                    properties.Add(v.Item.ItemId, v.Value);
                    groupKey = v.Item.UserData as string;
                    OpcDa.setItems(groupKey, v.Item.ItemId, properties);
                }
            });
            int i = OpcDa.getItemsCount(groupKey);

            if (i <= 0)
            {
                properties = OpcDa.getItems(group, groupKey);
                string topic = "$dg/thing/" + productId + "/" + devAddr + "/properties/report";
                int    flag1 = OpcDa.GetGroupFlag(groupKey);
                if (flag1 > 0)
                {
                    properties.Add("dgiotcollectflag", 0);
                    LogHelper.Log(" topic: " + topic + " payload: " + properties);
                }
                else
                {
                    properties.Add("dgiotcollectflag", 1);
                }
                result.Add("properties", properties);
                MqttClientHelper.Publish(topic, Encoding.UTF8.GetBytes(properties.ToString()));
                // LogHelper.Log("properties: " + properties.ToString());
            }
        }
Exemplo n.º 26
0
        public List <Item> ReadItemsValues(string host, string serverID, string groupKey)
        {
            OpcDaService server = GetOpcDaService(host, serverID);

            if (server == null)
            {
                return(null);
            }

            if (server.OpcDaGroupS.ContainsKey(groupKey) == true)
            {
                OpcDaGroup       group  = server.OpcDaGroupS[groupKey];
                OpcDaItemValue[] values = group.Read(group.Items, OpcDaDataSource.Device);

                if (values.Length != group.Items.Count)
                {
                    LogHelper.Log($"values.Length(${values.Length}) != group.Items.Count(${group.Items.Count}) ");
                    return(null);
                }

                List <Item> itemValues = new List <Item>();
                for (int i = 0; i < values.Length; ++i)
                {
                    Item it = new Item();
                    it.ItemId = group.Items[i].ItemId;
                    it.Data   = values[i].Value;
                    if (values[i].Value != null)
                    {
                        it.Data = values[i].Value;
                        it.Type = values[i].Value.GetType().ToString();
                        itemValues.Add(it);
                    }
                }

                return(itemValues);
            }

            return(null);
        }
        public void writeTag(string _tagName, string _tagValue, bool _sync = false)
        {
            // Create a group with items.
            if (writingGroup == null)
            {
                writingGroup = this.server.AddGroup("writingGroup");
            }

            writingGroup.IsActive = true;

            OpcDaItemDefinition def = new OpcDaItemDefinition
            {
                ItemId   = _tagName,
                IsActive = true
            };

            OpcDaItemDefinition[] definitions = { def };
            OpcDaItemResult[]     results     = writingGroup.AddItems(definitions);

            // Handle adding results.
            foreach (OpcDaItemResult result in results)
            {
            }

            OpcDaItem[] items  = { writingGroup.Items[0] };
            object[]    values = { _tagValue };

            if (_sync)
            {
                // Write values to the items synchronously.
                HRESULT[] hresults = writingGroup.Write(items, values);
            }/*
              * else
              * {
              * // Write values to the items asynchronously.
              * HRESULT[] results = await group.WriteAsync(items, values);
              * }*/
        }
        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);
            }
        }
Exemplo n.º 29
0
        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();
            }
        }
Exemplo n.º 30
0
 public JsonObject getItems(OpcDaGroup group, string groupKey)
 {
     if (itemstotalCollection.ContainsKey(groupKey) == true)
     {
         if (itemscountCollection.ContainsKey(groupKey) == true)
         {
             itemscountCollection[groupKey] = itemstotalCollection[groupKey];
         }
         else
         {
             itemscountCollection.Add(groupKey, itemstotalCollection[groupKey]);
         }
     }
     if (itemsCollection.ContainsKey(groupKey) == false)
     {
         return(new JsonObject());
     }
     else
     {
         JsonObject json = itemsCollection[groupKey];
         itemsCollection[groupKey] = new JsonObject();
         return(json);
     }
 }
Exemplo n.º 31
0
        public void StopMonitoringItems(string md5Str)
        {
            if (groupCollection.ContainsKey(md5Str))
            {
                LogHelper.Log("StopMonitoringItems: " + md5Str);
                Thread.Sleep(100);
                string       host          = groupCollection[md5Str].Host;
                string       serviceProgId = groupCollection[md5Str].ProgId;
                OpcDaService server        = GetOpcDaService(host, serviceProgId);
                if (server == null)
                {
                    LogHelper.Log("StopMonitoringItems  is null");
                    return;
                }

                // OpcDaGroup group = server.OpcDaGroupS[groupKey];
                OpcDaGroup group = server.OpcDaGroupS[md5Str];
                group.ValuesChanged -= MonitorValuesChanged;
                // server.OpcDaGroupS.Remove(groupKey);
                // server.Service.RemoveGroup(group);
                // groupCollection.Remove(groupKey);
                // groupFlagCollection.Remove(groupKey);
            }
        }
Exemplo n.º 32
0
        public JsonObject GetUnits(OpcDaGroup group)
        {
            JsonObject units = new JsonObject();

            try
            {
                OpcDaItemValue[] values = group.Read(group.Items, OpcDaDataSource.Device);
                if (values.Length == group.Items.Count)
                {
                    for (int i = 0; i < values.Length; ++i)
                    {
                        if (values[i].Value != null)
                        {
                            units.Add(values[i].Item.ItemId, values[i].Value.GetType().ToString());
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

            return(units);
        }
Exemplo n.º 33
0
        //Создание группы для OPC -для одного тега. Нахера??? :)
        protected virtual void InitSingleItemDataGroup(string groupName, string valueName, out OpcDaGroup dataGroup)
        {
            var definition = new OpcDaItemDefinition
            {
                ItemId   = opcClient.ParentNodeDescriptor + valueName,
                IsActive = true
            };

            dataGroup          = opcClient.OpcServer.AddGroup(groupName);                                //Группа переменных для чтения (записи) из OPC-сервера
            dataGroup.IsActive = true;
            OpcDaItemResult[] results = dataGroup.AddItems(new OpcDaItemDefinition[] { definition });    //Добавление переменных в группу
        }
Exemplo n.º 34
0
        //Создание группы для OPC - с формированием списка пеерменных Characteristic (с фильтрацией на неправильные теги. Передается список opBrowseElements)
        protected virtual void InitDataGroup(string[] itemDescription, string groupName, IEnumerable <OpcDaBrowseElement> opBrowseElements, out OpcDaGroup dataGroup, out OpcDaItemResult[] results, out List <string> listOfValidItems)
        {
            List <OpcDaItemDefinition> itemDefinitions = new List <OpcDaItemDefinition>();

            if (opBrowseElements != null)
            {
                foreach (var item in opBrowseElements)
                {
                    for (int i = 0; i < itemDescription.Length; i++)
                    {
                        itemDefinitions.Add(new OpcDaItemDefinition
                        {
                            ItemId   = opcClient.ParentNodeDescriptor + item.Name + "." + itemDescription[i],
                            IsActive = true
                        });
                    }
                }
            }


            dataGroup          = opcClient.OpcServer.AddGroup(groupName);
            dataGroup.IsActive = true;
            results            = dataGroup.AddItems(itemDefinitions);
            opcClient.OpcGroupsCount++;

            //Создаем список переменных, на основании добавленных в OPC тегов
            string itemyName;

            listOfValidItems = new List <string>();
            //Формируем список пустых объектов Density
            foreach (var result in results)
            {
                if (result.Error.Succeeded)
                {
                    itemyName = result.Item.ItemId.Substring(result.Item.ItemId.LastIndexOf('!') + 1);
                    itemyName = itemyName.Substring(0, itemyName.LastIndexOf('.'));
                    if (!listOfValidItems.Any(s => s == itemyName))
                    {
                        listOfValidItems.Add(itemyName);
                    }
                }
            }
        }
Exemplo n.º 35
0
        //Создание группы для OPC - без формирования списка пеерменных Characteristic (без фильтрации на несуществующие теги. Передается список Characteristic)
        protected virtual void InitDataGroup(string[] itemDescription, string groupName, IEnumerable <Characteristic> characteristicList, out OpcDaGroup dataGroup)
        {
            List <OpcDaItemDefinition> itemDefinitions = new List <OpcDaItemDefinition>();

            foreach (var item in characteristicList)
            {
                for (int i = 0; i < itemDescription.Length; i++)
                {
                    itemDefinitions.Add(new OpcDaItemDefinition
                    {
                        ItemId   = opcClient.ParentNodeDescriptor + item.TagName + "." + itemDescription[i],
                        IsActive = true
                    });
                }
            }

            dataGroup          = opcClient.OpcServer.AddGroup(groupName);
            dataGroup.IsActive = true;
            OpcDaItemResult[] results = dataGroup.AddItems(itemDefinitions);
            opcClient.OpcGroupsCount++;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="OpcDaServerGroupsChangedEventArgs"/> class.
 /// </summary>
 /// <param name="added">The added groups.</param>
 /// <param name="removed">The removed groups.</param>
 public OpcDaServerGroupsChangedEventArgs(OpcDaGroup added, OpcDaGroup removed)
 {
     Added = added;
     Removed = removed;
 }