public bool GetResponse(Uri requestUri, Stream stream)
        {
            var query = new RequestQuery(requestUri);

            if (query.IsValid)
            {
                try
                {
                    List <ComponentDefinition> components = null;
                    List <DataItemDefinition>  dataItems  = null;

                    // Get Current Agent
                    var agent = Database.ReadAgent(query.DeviceId);
                    if (agent != null)
                    {
                        var e = GetEvent("Program Status", agent.Version);
                        if (e != null)
                        {
                            // Get Components
                            components = Database.ReadComponents(query.DeviceId, agent.InstanceId);

                            // Get Data Items
                            dataItems = Database.ReadDataItems(query.DeviceId, agent.InstanceId);

                            if (!dataItems.IsNullOrEmpty())
                            {
                                var ids = GetEventIds(e, dataItems, components);
                                if (!ids.IsNullOrEmpty())
                                {
                                    // Program Name DataItem
                                    var programNameItem = dataItems.Find(o => o.Type == "PROGRAM");
                                    if (programNameItem != null)
                                    {
                                        if (!ids.Exists(o => o == programNameItem.Id))
                                        {
                                            ids.Add(programNameItem.Id);
                                        }
                                    }

                                    // Execution DataItem
                                    var executionItem = dataItems.Find(o => o.Type == "EXECUTION");
                                    if (executionItem != null)
                                    {
                                        if (!ids.Exists(o => o == executionItem.Id))
                                        {
                                            ids.Add(executionItem.Id);
                                        }
                                    }

                                    // Get Samples
                                    var samples = Database.ReadSamples(ids.ToArray(), query.DeviceId, query.From, query.To, DateTime.MinValue, 500000);
                                    if (!samples.IsNullOrEmpty())
                                    {
                                        // Get the initial timestamp
                                        //DateTime timestamp = samples.Select(o => o.Timestamp).OrderBy(o => o).First();
                                        DateTime timestamp;
                                        if (query.From > DateTime.MinValue)
                                        {
                                            timestamp = query.From;
                                        }
                                        else
                                        {
                                            timestamp = samples.Select(o => o.Timestamp).OrderByDescending(o => o).First();
                                        }

                                        // Create a list of DataItemInfos (DataItems with Parent Component info)
                                        var dataItemInfos = DataItemInfo.CreateList(dataItems, components);

                                        // Get Path Components
                                        var paths = components.FindAll(o => o.Type == "Path");

                                        var currentSamples = samples.FindAll(o => o.Timestamp <= timestamp);

                                        if (programNameItem != null && executionItem != null)
                                        {
                                            // Previous variables
                                            DateTime previousTime        = DateTime.MinValue;
                                            string   previousValue       = null;
                                            string   previousProgramName = null;

                                            // Stored variables
                                            var  parts = new List <Part>();
                                            Part part  = null;

                                            // Get distinct timestamps
                                            var timestamps = samples.FindAll(o => o.Timestamp >= timestamp).OrderBy(o => o.Timestamp).Select(o => o.Timestamp).Distinct().ToList();
                                            for (int i = 0; i < timestamps.Count; i++)
                                            {
                                                var time = timestamps[i];

                                                // Update CurrentSamples
                                                foreach (var sample in samples.FindAll(o => o.Timestamp == time))
                                                {
                                                    int j = currentSamples.FindIndex(o => o.Id == sample.Id);
                                                    if (j >= 0)
                                                    {
                                                        currentSamples[j] = sample;
                                                    }
                                                    else
                                                    {
                                                        currentSamples.Add(sample);
                                                    }
                                                }


                                                // Program Name
                                                string programName = null;
                                                if (currentSamples.Exists(o => o.Id == programNameItem.Id))
                                                {
                                                    programName = currentSamples.Find(o => o.Id == programNameItem.Id).CDATA;
                                                }

                                                // Execution
                                                string execution = null;
                                                if (currentSamples.Exists(o => o.Id == executionItem.Id))
                                                {
                                                    execution = currentSamples.Find(o => o.Id == executionItem.Id).CDATA;
                                                }

                                                // Create a list of SampleInfo objects with DataItem information contained
                                                var infos = SampleInfo.Create(dataItemInfos, currentSamples);

                                                // Evaluate the Event and get the Response
                                                var response = e.Evaluate(infos);
                                                if (response != null)
                                                {
                                                    if (part != null)
                                                    {
                                                        // Update the program stop time
                                                        part.Stop = time;

                                                        // Check if program changed
                                                        if (part != null && programName != previousProgramName)
                                                        {
                                                            part          = null;
                                                            previousValue = null;
                                                        }
                                                    }


                                                    if (part == null && !string.IsNullOrEmpty(programName) && programName != "UNAVAILABLE" &&
                                                        response.Value != "Stopped" && response.Value != "Completed")
                                                    {
                                                        // Create a new Part object
                                                        part             = new Part();
                                                        part.ProgramName = programName;
                                                        part.Start       = time;
                                                    }


                                                    if (part != null)
                                                    {
                                                        if (response.Value != previousValue)
                                                        {
                                                            if (response.Value == "Stopped" || response.Value == "Completed")
                                                            {
                                                                parts.Add(part);
                                                                part = null;
                                                            }
                                                        }
                                                    }

                                                    previousValue = response.Value;
                                                    previousTime  = time;
                                                }

                                                previousProgramName = programName;
                                            }

                                            var toTime = query.To > DateTime.MinValue ? query.To : DateTime.UtcNow;

                                            if (part != null)
                                            {
                                                part.Stop = toTime;
                                                parts.Add(part);
                                            }

                                            if (!parts.IsNullOrEmpty())
                                            {
                                                var partIds = parts.Select(o => o.Id).ToArray();

                                                // Get Rejected Parts
                                                var rejectedParts = Database.ReadRejectedParts(query.DeviceId, partIds, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue);
                                                if (!rejectedParts.IsNullOrEmpty())
                                                {
                                                    foreach (var matchedPart in parts)
                                                    {
                                                        var rejectedPart = rejectedParts.Find(o => o.PartId == matchedPart.Id);
                                                        if (rejectedPart != null)
                                                        {
                                                            var rejection = new Rejection(rejectedPart.Message, rejectedPart.Timestamp);
                                                            matchedPart.Rejection = rejection;
                                                        }
                                                    }
                                                }

                                                // Get Verified Parts
                                                var verifiedParts = Database.ReadVerifiedParts(query.DeviceId, partIds, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue);
                                                if (!verifiedParts.IsNullOrEmpty())
                                                {
                                                    foreach (var matchedPart in parts)
                                                    {
                                                        var verifiedPart = verifiedParts.Find(o => o.PartId == matchedPart.Id);
                                                        if (verifiedPart != null)
                                                        {
                                                            var verification = new Verification(verifiedPart.Message, verifiedPart.Timestamp);
                                                            matchedPart.Verification = verification;
                                                        }
                                                    }
                                                }

                                                // Write JSON to stream
                                                string json  = TrakHound.Api.v2.Json.Convert.ToJson(parts, true);
                                                var    bytes = Encoding.UTF8.GetBytes(json);
                                                stream.Write(bytes, 0, bytes.Length);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Info("Parts Stream Closed");
                    log.Trace(ex);
                }

                return(true);
            }

            return(false);
        }
Example #2
0
        public List <Oee> Run()
        {
            // Set timestamps
            from = RequestQuery.From;
            to   = RequestQuery.To;
            if (RequestQuery.To == DateTime.MinValue)
            {
                to = DateTime.UtcNow;
            }

            // Set the Next timestamp (for Incremental processing)
            next = to;
            if (RequestQuery.Increment > 0)
            {
                next = from.AddSeconds(RequestQuery.Increment);
            }
            if (next > to)
            {
                next = to;
            }

            // Create a list of DataItemInfos (DataItems with Parent Component info)
            dataItemInfos = DataItemInfo.CreateList(DataItems, Components);

            var samples = GetSamples();

            if (!samples.IsNullOrEmpty())
            {
                // Get a list of distinct ids retrieved from Database
                var sampleIds = samples.Select(o => o.Id).Distinct().ToList();

                var instanceSamples = new List <Sample>();
                var oees            = new List <Oee>();

                int i = 0;

                do
                {
                    i++;

                    // Update Instance Samples
                    UpdateInstanceSamples(sampleIds, samples);

                    // Create and Add a new OEE object to list
                    oees.Add(CreateOee(samples));

                    // Increment time
                    if (next == to)
                    {
                        break;
                    }
                    from = next;
                    next = next.AddSeconds(RequestQuery.Increment);
                    if (next > to)
                    {
                        next = to;
                    }
                } while (next <= to);

                // Get list of Part IDs
                var partIds = new List <string>();
                foreach (var oee in oees)
                {
                    partIds.AddRange(oee.Parts.Select(o => o.Id));
                }
                var verifiedParts = Database.ReadVerifiedParts(RequestQuery.DeviceId, partIds.ToArray(), DateTime.MinValue, DateTime.MinValue, DateTime.MinValue);

                // Add Quality Component
                foreach (var oee in oees)
                {
                    if (!oee.Parts.IsNullOrEmpty())
                    {
                        int goodParts = 0;

                        if (!verifiedParts.IsNullOrEmpty())
                        {
                            foreach (var part in verifiedParts)
                            {
                                if (oee.Parts.Exists(o => o.Id == part.PartId))
                                {
                                    goodParts++;
                                }
                            }
                        }

                        oee.Quality = new Quality(goodParts, oee.Parts.Count);
                    }
                }

                return(oees);
            }

            return(null);
        }
        public bool GetResponse(Uri requestUri, Stream stream)
        {
            var query = new RequestQuery(requestUri);

            if (query.IsValid)
            {
                try
                {
                    var previousEvents = new List <EventItem>();

                    List <ComponentDefinition> components = null;
                    List <DataItemDefinition>  dataItems  = null;
                    List <Sample> samples = null;

                    // Get Current Agent
                    var agent = Database.ReadAgent(query.DeviceId);
                    if (agent != null)
                    {
                        // Get Components
                        components = Database.ReadComponents(query.DeviceId, agent.InstanceId);

                        // Get Data Items
                        dataItems = Database.ReadDataItems(query.DeviceId, agent.InstanceId);
                    }

                    if (!dataItems.IsNullOrEmpty())
                    {
                        DateTime from = query.From;

                        while (stream != null)
                        {
                            var activityItem = new ActivityItem();
                            var pathItems    = new List <PathItem>();

                            // Get Samples
                            samples = Database.ReadSamples(null, query.DeviceId, from, query.To, query.At, query.Count);

                            if (!samples.IsNullOrEmpty())
                            {
                                var events = GetEvents(agent.Version);
                                if (events != null)
                                {
                                    // Get the initial timestamp
                                    DateTime timestamp;
                                    if (query.From > DateTime.MinValue)
                                    {
                                        timestamp = query.From;
                                    }
                                    else if (query.At > DateTime.MinValue)
                                    {
                                        timestamp = query.At;
                                    }
                                    else
                                    {
                                        timestamp = samples.Select(o => o.Timestamp).OrderByDescending(o => o).First();
                                    }

                                    // Create a list of DataItemInfos (DataItems with Parent Component info)
                                    var dataItemInfos = DataItemInfo.CreateList(dataItems, components);

                                    // Get Path Components
                                    var paths = components.FindAll(o => o.Type == "Path");

                                    foreach (var e in events)
                                    {
                                        // Check if Event relies on Path and there are multiple paths
                                        if (ContainsPath(e, components, dataItems) && paths.Count > 1)
                                        {
                                            foreach (var path in paths)
                                            {
                                                // Find all DataItemInfo descendants of this Path
                                                var pathInfos = dataItemInfos.FindAll(o => !o.Parents.Exists(x => x.Type == "Path") || o.ParentId == path.Id);

                                                var pathItem = pathItems.Find(o => o.Id == path.Id);
                                                if (pathItem == null)
                                                {
                                                    // Create new PathItem
                                                    pathItem      = new PathItem();
                                                    pathItem.Id   = path.Id;
                                                    pathItem.Name = path.Name;
                                                    pathItems.Add(pathItem);
                                                }

                                                // Get a list of EventItems for the Path
                                                pathItem.Events.AddRange(GetEvents(e, pathInfos, samples, timestamp));
                                            }
                                        }
                                        else
                                        {
                                            activityItem.Add(GetEvents(e, dataItemInfos, samples, timestamp));
                                        }
                                    }

                                    activityItem.Add(pathItems);

                                    bool send = false;

                                    // Filter out old events (for streaming)
                                    foreach (var eventItem in activityItem.Events)
                                    {
                                        int i = previousEvents.FindIndex(o => o.Name == eventItem.Name);
                                        if (i < 0)
                                        {
                                            send = true;
                                            previousEvents.Add(eventItem);
                                        }
                                        else
                                        {
                                            if (previousEvents[i].Value != eventItem.Value)
                                            {
                                                //previousEvents[i] = eventItem;
                                                previousEvents.RemoveAt(i);
                                                previousEvents.Add(eventItem);
                                                send = true;
                                            }
                                        }
                                    }

                                    if (send)
                                    {
                                        // Write JSON to stream
                                        string json = TrakHound.Api.v2.Json.Convert.ToJson(activityItem, query.Interval == 0);
                                        if (query.Interval > 0)
                                        {
                                            json += "\r\n";
                                        }
                                        var bytes = Encoding.UTF8.GetBytes(json);
                                        stream.Write(bytes, 0, bytes.Length);
                                    }
                                    else
                                    {
                                        stream.WriteByte(32);
                                    }
                                }
                            }

                            if (from > DateTime.MinValue)
                            {
                                from = from.AddMilliseconds(query.Interval);
                            }

                            if (query.Interval <= 0)
                            {
                                break;
                            }
                            else
                            {
                                Thread.Sleep(query.Interval);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Info("Activity Stream Closed");
                    log.Trace(ex);
                }

                return(true);
            }

            return(false);
        }
Example #4
0
        public override void OnAddedToCommLine()
        {
            // загрузка конфигурации КП
            string errMsg;

            configLoaded = config.Load(Config.GetFileName(AppDirs.ConfigDir, Number), out errMsg);

            int             dataGroupCnt = config.DataGroups.Count;
            List <TagGroup> tagGroups    = new List <TagGroup>(dataGroupCnt);
            int             signal       = 1;

            if (configLoaded)
            {
                for (int i = 0; i < dataGroupCnt; i++) // browser folders
                {
                    Config.DataGroup dataGroup = config.DataGroups[i];

                    // определение количества тегов КП в группе чтения данных
                    int tagCntByGroup = 0;
                    foreach (Config.DataItem dataItem in dataGroup.DataItems)
                    {
                        tagCntByGroup += 1;
                    }

                    // создание группы тегов КП
                    if (tagCntByGroup > 0)
                    {
                        TagGroup tagGroup = new TagGroup(string.IsNullOrEmpty(dataGroup.Name) ?
                                                         (Localization.UseRussian ? "Безымянная группа" : "Unnamed group") : dataGroup.Name);
                        int dataItemCnt = dataGroup.DataItems.Count;

                        List <DataItemInfo> dataGroupInfo = new List <DataItemInfo>();
                        dataGroup.Tag = dataGroupInfo;

                        for (int j = 0; j < dataItemCnt; j++) // Browse Items in a folder
                        {
                            Config.DataItem dataItem      = dataGroup.DataItems[j];
                            string          dataItemName  = string.IsNullOrEmpty(dataItem.Name) ? "" : dataItem.Name;
                            string          tagNamePrefix = dataItemName == "" ?
                                                            (Localization.UseRussian ? "Безымянный тег" : "Unnamed tag") : dataItemName;
                            int tagCntByItem = 1;

                            DataItemInfo dataItemInfo = new DataItemInfo(dataItem.Name, dataItem.Id);
                            dataItemInfo.KPTags = new KPTag[tagCntByItem];

                            //for (int k = 0; k < tagCntByItem; k++)
                            {
                                string tagName = tagNamePrefix;
                                KPTag  kpTag   = new KPTag(signal++, tagName);
                                tagGroup.KPTags.Add(kpTag);
                                dataItemInfo.KPTags[0] = kpTag; //0->k
                            }

                            if (tagCntByItem > 0 && !kpTagsByName.ContainsKey(dataItemName))
                            {
                                kpTagsByName.Add(dataItemName, dataItemInfo.KPTags[0]);
                            }
                        }

                        tagGroups.Add(tagGroup);
                    }
                }
                InitKPTags(tagGroups);
            }

            // Logs

            /*
             * string m_UtilsLogFilePath;
             * bool m_deleteOnLoad = true;
             * int m_traceMasks = Opc.Ua.Utils.TraceMasks.Error | Opc.Ua.Utils.TraceMasks.Information;
             * m_UtilsLogFilePath = AppDomain.CurrentDomain.BaseDirectory + "Opc.Ua.Core.Logs.txt";
             * Opc.Ua.Utils.SetTraceLog(m_UtilsLogFilePath, m_deleteOnLoad);
             * Opc.Ua.Utils.SetTraceMask(m_traceMasks);
             * Opc.Ua.Utils.Trace(Opc.Ua.Utils.TraceMasks.Information, "Beginning of Opc.Ua.Core.Utils logs");
             */

            WriteToLog("Configuration started");

            Init().Wait();

            WriteToLog("Configuration finished");
        }