Exemplo n.º 1
0
 public Trend(Opc.Hda.Server server)
 {
     this.m_server           = null;
     this.m_name             = null;
     this.m_aggregateID      = 0;
     this.m_startTime        = null;
     this.m_endTime          = null;
     this.m_maxValues        = 0;
     this.m_includeBounds    = false;
     this.m_resampleInterval = 0M;
     this.m_timestamps       = new ItemTimeCollection();
     this.m_items            = new ItemCollection();
     this.m_updateInterval   = 0M;
     this.m_playbackInterval = 0M;
     this.m_playbackDuration = 0M;
     this.m_subscription     = null;
     this.m_playback         = null;
     if (server == null)
     {
         throw new ArgumentNullException("server");
     }
     this.m_server = server;
     do
     {
         this.Name = string.Format("Trend{0,2:00}", ++m_count);
     }while (this.m_server.Trends[this.Name] != null);
 }
Exemplo n.º 2
0
        public static Opc.Hda.Server ServerHdaConnect()
        {
            var tagsList = new Tags();

            //Задаем расположение серверов
            foreach (var tag in tagsList.GetMassurm())
            {
                switch (tag.Name)
                {
                case "MasterIpHda":
                    MasterIpHda = tag.Value;
                    break;

                case "SlaveIpHda":
                    SlaveIpHda = tag.Value;
                    break;

                case "OpcHdaId":
                    OpcHdaId = tag.Value;
                    break;
                }
            }
            //const string masterIpHda = "localhost";
            //const string slaveIpHda = "localhost";
            //const string opcHdaId = "Infinity.OPCHDAServer";
            //Соединение с сервером
            var url       = new Opc.URL("opchda://" + MasterIpHda + "/" + OpcHdaId);
            var serverHda = new Opc.Hda.Server(new OpcCom.Factory(), url);

            try
            {
                serverHda.Connect();
            }
            catch
            {
                url       = new Opc.URL("opchda://" + SlaveIpHda + "/" + OpcHdaId);
                serverHda = new Opc.Hda.Server(new OpcCom.Factory(), url);
                try
                {
                    serverHda.Connect();
                }
                catch (Exception)
                {
                    MessageBox.Show(@"Отсутствует лицензия или проверьте подключения к серверу C:\Tag.ini", @"Ошибка подключения сервера", MessageBoxButton.OK, MessageBoxImage.Error);

                    Environment.Exit(0);
                }
            }
            // System.Threading.Thread.Sleep(1500);
            return(serverHda);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Initializes the object with the specified server.
        /// </summary>
        public Trend(Opc.Hda.Server server)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }

            // save a reference to a server.
            m_server = server;

            // create a default name.
            do
            {
                Name = String.Format("Trend{0,2:00}", ++m_count);
            }while (m_server.Trends[Name] != null);
        }
Exemplo n.º 4
0
 protected Trend(SerializationInfo info, StreamingContext context)
 {
     this.m_server           = null;
     this.m_name             = null;
     this.m_aggregateID      = 0;
     this.m_startTime        = null;
     this.m_endTime          = null;
     this.m_maxValues        = 0;
     this.m_includeBounds    = false;
     this.m_resampleInterval = 0M;
     this.m_timestamps       = new ItemTimeCollection();
     this.m_items            = new ItemCollection();
     this.m_updateInterval   = 0M;
     this.m_playbackInterval = 0M;
     this.m_playbackDuration = 0M;
     this.m_subscription     = null;
     this.m_playback         = null;
     this.m_name             = (string)info.GetValue("Name", typeof(string));
     this.m_aggregateID      = (int)info.GetValue("AggregateID", typeof(int));
     this.m_startTime        = (Time)info.GetValue("StartTime", typeof(Time));
     this.m_endTime          = (Time)info.GetValue("EndTime", typeof(Time));
     this.m_maxValues        = (int)info.GetValue("MaxValues", typeof(int));
     this.m_includeBounds    = (bool)info.GetValue("IncludeBounds", typeof(bool));
     this.m_resampleInterval = (decimal)info.GetValue("ResampleInterval", typeof(decimal));
     this.m_updateInterval   = (decimal)info.GetValue("UpdateInterval", typeof(decimal));
     this.m_playbackInterval = (decimal)info.GetValue("PlaybackInterval", typeof(decimal));
     this.m_playbackDuration = (decimal)info.GetValue("PlaybackDuration", typeof(decimal));
     DateTime[] timeArray = (DateTime[])info.GetValue("Timestamps", typeof(DateTime[]));
     if (timeArray != null)
     {
         foreach (DateTime time in timeArray)
         {
             this.m_timestamps.Add(time);
         }
     }
     Item[] itemArray = (Item[])info.GetValue("Items", typeof(Item[]));
     if (itemArray != null)
     {
         foreach (Item item in itemArray)
         {
             this.m_items.Add(item);
         }
     }
 }
        /// <summary>
        /// Returns a list of servers that support the specified specification on the specified host.
        /// </summary>
        public Opc.Server[] GetAvailableServers(Specification specification, string host, ConnectData connectData)
        {
            lock (this)
            {
                NetworkCredential credentials = (connectData != null)?connectData.GetCredential(null, null):null;

                // connect to the server.
                m_server = (IOPCServerList2)OpcCom.Interop.CreateInstance(CLSID, host, credentials);
                m_host   = host;

                try
                {
                    ArrayList servers = new ArrayList();

                    // convert the interface version to a guid.
                    Guid catid = new Guid(specification.ID);

                    // get list of servers in the specified specification.
                    IOPCEnumGUID enumerator = null;

                    m_server.EnumClassesOfCategories(
                        1,
                        new Guid[] { catid },
                        0,
                        null,
                        out enumerator);

                    // read clsids.
                    Guid[] clsids = ReadClasses(enumerator);

                    // release enumerator object.
                    OpcCom.Interop.ReleaseServer(enumerator);
                    enumerator = null;

                    // fetch class descriptions.
                    foreach (Guid clsid in clsids)
                    {
                        Factory factory = new OpcCom.Factory();

                        try
                        {
                            URL url = CreateUrl(specification, clsid);

                            Opc.Server server = null;

                            if (specification == Specification.COM_DA_30)
                            {
                                server = new Opc.Da.Server(factory, url);
                            }

                            else if (specification == Specification.COM_DA_20)
                            {
                                server = new Opc.Da.Server(factory, url);
                            }

                            else if (specification == Specification.COM_AE_10)
                            {
                                server = new Opc.Ae.Server(factory, url);
                            }

                            else if (specification == Specification.COM_HDA_10)
                            {
                                server = new Opc.Hda.Server(factory, url);
                            }

                            else if (specification == Specification.COM_DX_10)
                            {
                                server = new Opc.Dx.Server(factory, url);
                            }

                            servers.Add(server);
                        }
                        catch (Exception)
                        {
                            // ignore bad clsids.
                        }
                    }

                    return((Opc.Server[])servers.ToArray(typeof(Opc.Server)));
                }
                finally
                {
                    // free the server.
                    OpcCom.Interop.ReleaseServer(m_server);
                    m_server = null;
                }
            }
        }
Exemplo n.º 6
0
        // Connect to OPC HDA server
        public bool Connect(string HostName, string ServerName)
        {
            var url = new Opc.URL();

            url.Scheme   = Opc.UrlScheme.HDA;
            url.HostName = HostName;
            url.Path     = ServerName;

            try {
                var fact = new OpcCom.Factory();
                if ((_OPCServer != null) && (!_OPCServer.IsConnected))
                {
                    _trace.TraceEvent(TraceEventType.Verbose, 0, "_OPCServer is disconnected, disposing object");
                    //Unfortunately, in case of lost connection simply calling .Connect() doesn't work :(
                    //Let's try to recreate the object from scratch
                    _OPCServer.Dispose();
                    _OPCServer = null;
                }

                if (_OPCServer == null)
                {
                    _trace.TraceEvent(TraceEventType.Verbose, 0, "_OPCServer is null, creating new object");
                    _OPCServer = new Opc.Hda.Server(fact, null);
                }

                if (!_OPCServer.IsConnected)
                {
                    _trace.TraceEvent(TraceEventType.Verbose, 0, "OPC server is disconnected, trying to connect");
                    _OPCServer.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential(), null));
                    if (!_OPCServer.IsConnected)
                    {
                        _trace.TraceEvent(TraceEventType.Error, 0, "Connection failed without exception: {0}", url.ToString());
                        return(false);
                    }
                    _trace.TraceEvent(TraceEventType.Verbose, 0, "Succesfully connected to {0}, obj: {1}", url.ToString(), _OPCServer.GetHashCode().ToString());
                }
                try {
                    Status = _OPCServer.GetStatus();
                    _trace.TraceEvent(TraceEventType.Verbose, 0, "OPC server status:\n" +
                                      "\tCurrentTime:     {0}\n" +
                                      "\tMaxReturnValues: {1}\n" +
                                      "\tProductVersion:  {2}\n" +
                                      "\tServerState:     {3}\n" +
                                      "\tStartTime:       {4}\n" +
                                      "\tStatusInfo:      {5}\n" +
                                      "\tVendorInfo:      {6}\n",
                                      Status.CurrentTime,
                                      Status.MaxReturnValues,
                                      Status.ProductVersion,
                                      Status.ServerState,
                                      Status.StartTime,
                                      Status.StatusInfo,
                                      Status.VendorInfo);
                } catch (Exception e) {
                    _trace.TraceEvent(TraceEventType.Warning, 0, "Can't get server status: {0}, {1}", url.ToString(), e.Message);
                }

                try {
                    _trace.TraceEvent(TraceEventType.Verbose, 0, "SupportedAggregates:");
                    SupportedAggregates = _OPCServer.GetAggregates();
                    foreach (Opc.Hda.Aggregate agg in SupportedAggregates)
                    {
                        _trace.TraceEvent(TraceEventType.Verbose, 0, "{0}\t{1}\t{2}", agg.ID, agg.Name, agg.Description);
                    }
                } catch (Exception e) {
                    _trace.TraceEvent(TraceEventType.Warning, 0, "Can't get server supported aggregates: {0}, {1}", url.ToString(), e.Message);
                }
            } catch (Exception e) {
                _trace.TraceEvent(TraceEventType.Error, 0, "Connection failed: {0}, {1}", url.ToString(), e.Message);
                return(false);
            }

            return(true);
        }
Exemplo n.º 7
0
        private void CreateSignalDict(Opc.Hda.Server Hda, List <string> tagsLst, string[] propID = null, string dtBegin = null, string dtEnd = null, bool restrict = false)
        {
            Dictionary = new Dictionary <string, Signal>();
            DateTime dt1    = new DateTime();
            DateTime dt2    = new DateTime();
            var      memRec = new OpcRecord();

            if (dtBegin != null)
            {
                if (serverHda == null)
                {
                    serverHda = Hda;
                }
            }



            for (int i = 0; i < tagsLst.Count; i++)
            {
                var signal = new Signal(serverDa, tagsLst[i], propID);

                if (dtBegin != null)
                {
                    try
                    {
                        signal.ValueCollection = new List <OpcRecord>();
                        dt1 = System.Convert.ToDateTime(dtBegin);
                        dt2 = DateTime.Today;
                        DateTime lastdt = dt1;

                        if (dtEnd == null)
                        {
                            dtEnd = dt2.AddDays(1).ToString();
                        }
                        dt2 = System.Convert.ToDateTime(dtEnd);

                        signal.DtBegin = dt1;
                        signal.DtEnd   = dt2;

                        var identifiers = new ItemIdentifier[1];
                        identifiers[0] = new Opc.ItemIdentifier(tagsLst[i]);

                        Opc.IdentifiedResult[] items = serverHda.CreateItems(identifiers);
                        OpcRecord rec  = null;
                        bool      exit = false;
                        Opc.Hda.ItemValueCollection[] vForPrev = serverHda.ReadRaw(new Opc.Hda.Time(dt1),
                                                                                   new Opc.Hda.Time(dt1.AddSeconds(1)), 0, true, items);
                        signal.PrevValue = new OpcRecord();
                        if (vForPrev.Length > 0)
                        {
                            if (vForPrev[0].Count > 0)
                            {
                                signal.PrevValue.Value     = vForPrev[0][0].Value;
                                signal.PrevValue.Quality   = vForPrev[0][0].Quality.GetCode();
                                signal.PrevValue.Timestamp = vForPrev[0][0].Timestamp.ToString();
                            }
                        }
                        Opc.Hda.ItemValueCollection[] vForNext =
                            serverHda.ReadRaw(new Opc.Hda.Time(dt2.AddMilliseconds(-1)), new Opc.Hda.Time(dt2), 0, true,
                                              items);
                        signal.NextValue = new OpcRecord();
                        if (vForNext.Length > 0)
                        {
                            if (vForNext[0].Count > 0)
                            {
                                signal.NextValue.Value     = vForNext[0][vForNext[0].Count - 1].Value;
                                signal.NextValue.Quality   = vForNext[0][vForNext[0].Count - 1].Quality.GetCode();
                                signal.NextValue.Timestamp = vForNext[0][vForNext[0].Count - 1].Timestamp.ToString();
                            }
                        }

                        while (!exit)
                        {
                            Opc.Hda.ItemValueCollection[] values = serverHda.ReadRaw(new Opc.Hda.Time(lastdt),
                                                                                     new Opc.Hda.Time(dt2), 0, false, items);

                            for (int j = 0; j < values.Length; j++)
                            {
                                if (values[j].Count <= 1)
                                {
                                    exit = true;
                                }
                                for (int k = 0; k < values[j].Count; k++)
                                {
                                    rec = new OpcRecord();
                                    if (signal.ValueType == "long")
                                    {
                                        if (values[j][k].Value != null)
                                        {
                                            rec.Value = System.Convert.ToInt64(values[j][k].Value.ToString());
                                        }
                                        else
                                        {
                                            rec.Value = 0;
                                        }
                                    }
                                    if (signal.ValueType == "double")
                                    {
                                        if (values[j][k].Value != null)
                                        {
                                            rec.Value = System.Convert.ToDouble(values[j][k].Value.ToString());
                                        }
                                        else
                                        {
                                            rec.Value = 0.0;
                                        }
                                    }
                                    if (signal.ValueType == "string")
                                    {
                                        if (values[j][k].Value != null)
                                        {
                                            rec.Value = values[j][k].Value.ToString();
                                        }
                                        else
                                        {
                                            rec.Value = "";
                                        }
                                    }
                                    if (signal.ValueType == "bool")
                                    {
                                        if (values[j][k].Value != null)
                                        {
                                            rec.Value = values[j][k].Value.ToString().ToLower().Trim() == "true";
                                        }
                                        else
                                        {
                                            rec.Value = false;
                                        }
                                    }

                                    rec.Quality   = values[j][k].Quality.GetCode();
                                    rec.Timestamp = values[j][k].Timestamp.ToString();
                                    rec.Value     = values[j][k].Value;
                                    lastdt        = values[j][k].Timestamp;
                                    if (values[j].Count > 1)
                                    {
                                        if (k == values[j].Count - 1 &&
                                            values[j][k].Timestamp == values[j][k - 1].Timestamp)
                                        {
                                            lastdt = lastdt.AddMilliseconds(1);
                                        }
                                    }
                                    if (k != values[j].Count - 1)
                                    {
                                        if (restrict & signal.ValueCollection.Count > 0)
                                        {
                                            if (
                                                System.Convert.ToDateTime(
                                                    signal.ValueCollection[signal.ValueCollection.Count - 1].Timestamp)
                                                .ToString() ==
                                                System.Convert.ToDateTime(rec.Timestamp).ToString() &&
                                                rec.Quality >= 192)
                                            {
                                                signal.ValueCollection[signal.ValueCollection.Count - 1] = rec;
                                            }
                                            else
                                            {
                                                signal.ValueCollection.Add(rec);
                                            }
                                        }
                                        else
                                        {
                                            signal.ValueCollection.Add(rec);
                                        }
                                    }
                                }
                            }
                        }

                        if (restrict & signal.ValueCollection.Count > 0)
                        {
                            if (
                                System.Convert.ToDateTime(
                                    signal.ValueCollection[signal.ValueCollection.Count - 1].Timestamp).ToString() ==
                                System.Convert.ToDateTime(rec.Timestamp).ToString() && rec.Quality >= 192)
                            {
                                signal.ValueCollection[signal.ValueCollection.Count - 1] = rec;
                            }
                            else
                            {
                                signal.ValueCollection.Add(rec);
                            }
                        }
                        else
                        {
                            signal.ValueCollection.Add(rec);
                        }
                    }

                    catch (Exception)
                    {
                        MessageBox.Show(@"Отсутствует лицензия или проверьте подключения к серверу C:\Tag.ini", @"Ошибка подключения сервера", MessageBoxButton.OK, MessageBoxImage.Error);

                        Environment.Exit(0);
                    }
                }

                if (restrict)
                {
                    if (signal.ValueCollection.Count > 0)
                    {
                        if (signal.ValueCollection[0] == null)
                        {
                            signal.ValueCollection.Remove(signal.ValueCollection[0]);
                        }
                    }

                    var restrictLeft = new OpcRecord();
                    restrictLeft.Value     = signal.PrevValue.Value;
                    restrictLeft.Quality   = signal.PrevValue.Quality;
                    restrictLeft.Timestamp = dt1.ToString();
                    signal.ValueCollection.Insert(0, restrictLeft);

                    var restrictRight = new OpcRecord();
                    restrictRight.Value     = signal.ValueCollection[signal.ValueCollection.Count - 1].Value;
                    restrictRight.Quality   = signal.ValueCollection[signal.ValueCollection.Count - 1].Quality;
                    restrictRight.Timestamp = dt2.ToString();
                    signal.ValueCollection.Add(restrictRight);
                }
                Dictionary.Add(tagsLst[i], signal);
            }
        }
Exemplo n.º 8
0
 public SignalDict(Opc.Hda.Server Hda, List <string> tagsLst, string[] propID = null, string dtBegin = null, string dtEnd = null, bool restrict = false)
 {
     CreateSignalDict(Hda, tagsLst, propID, dtBegin, dtEnd, restrict);
 }
Exemplo n.º 9
0
 internal void SetServer(Opc.Hda.Server server)
 {
     this.m_server = server;
 }