Ejemplo n.º 1
0
        private void sinkEnergyFound(ICDEThing sender, object incoming)
        {
            if (!(incoming is TSM pMessage))
            {
                return;
            }

            if (pMessage.TXT.Equals("NEWENERGYREADING"))
            {
                int pos = pMessage.PLS.IndexOf("\"Watts\":");
                if (pos >= 0)
                {
                    string t    = pMessage.PLS.Substring(pos);
                    int    pos2 = t.IndexOf(",");
                    if (pos2 < 0)
                    {
                        pos2 = t.IndexOf("}");
                    }
                    if (pos2 >= 0)
                    {
                        t = t.Substring("\"Watts\":".Length, pos2 - "\"Watts\":".Length);
                        LastStationWatts = TheCommonUtils.CDbl(t);
                    }
                }
            }
        }
Ejemplo n.º 2
0
 Measurement GetMeasurement(string propertyName, DateTimeOffset propTime, object propValue)
 {
     var m = new Measurement
     {
         ts = propTime,
     };
     m.series.Add(propertyName, new List<double> { TheCommonUtils.CDbl(propValue) });
     m.series.Add("$_time", new List<double> { 0 });
     return m;
 }
Ejemplo n.º 3
0
 private void parseRequest(TheRequestData pReqData)
 {
     firstRequestLine = streamReadLine(mRequestStream);
     string[] tokens = firstRequestLine.Split(' ');
     if (tokens.Length != 3)
     {
         throw new Exception("HttpMidiServer: invalid http request head-line");
     }
     pReqData.HttpMethod     = tokens[0].ToUpper();
     pReqData.RequestUri     = tokens[1].StartsWith("http", StringComparison.OrdinalIgnoreCase) ? TheCommonUtils.CUri(tokens[1], false) : TheCommonUtils.CUri(TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false) + tokens[1], false);
     pReqData.HttpVersionStr = tokens[2];
     pReqData.HttpVersion    = TheCommonUtils.CDbl(pReqData.HttpVersionStr.Split('/')[1]);
 }
Ejemplo n.º 4
0
        public void Write(TheNMILiveTag pTag, string pEventLabel, string pComment)
        {
            TheNMITagLogEntry tEntry = new TheNMITagLogEntry
            {
                ID         = pTag.GetBaseThing().ID,
                Value      = TheCommonUtils.CDbl(pTag.GetBaseThing().Value),
                EngineName = pTag.GetBaseThing().EngineName,
                EventLabel = pEventLabel,
                Comment    = pComment
            };

            MyTagLog.AddAnItem(tEntry);
        }
Ejemplo n.º 5
0
 private double GetMetricValue(object value)
 {
     if (value is DateTimeOffset)
     {
         return(((DateTimeOffset)value).ToUnixTimeSeconds());
     }
     else if (value is DateTime)
     {
         return((new DateTimeOffset((DateTime)value)).ToUnixTimeSeconds());
     }
     else
     {
         return(TheCommonUtils.CDbl(value));
     }
 }
Ejemplo n.º 6
0
        public TheSensorMeta GetSensorMeta()
        {
            var sensorMetaProp = this.GetProperty(strSensor);
            var rangeMinProp   = sensorMetaProp?.GetProperty(nameof(TheSensorMeta.RangeMin));
            var rangeMaxProp   = sensorMetaProp?.GetProperty(nameof(TheSensorMeta.RangeMax));
            var sensorMeta     = new TheSensorMeta
            {
                SourceType    = TheCommonUtils.CStrNullable(sensorMetaProp?.GetProperty(nameof(TheSensorMeta.SourceType))),
                Units         = TheCommonUtils.CStrNullable(sensorMetaProp?.GetProperty(nameof(TheSensorMeta.Units))),
                SourceUnits   = TheCommonUtils.CStrNullable(sensorMetaProp?.GetProperty(nameof(TheSensorMeta.SourceUnits))),
                RangeMin      = rangeMinProp != null ? (double?)TheCommonUtils.CDbl(rangeMinProp) : null,
                RangeMax      = rangeMaxProp != null ? (double?)TheCommonUtils.CDbl(rangeMaxProp) : null,
                Description   = TheCommonUtils.CStrNullable(sensorMetaProp?.GetProperty(nameof(TheSensorMeta.Description))),
                FriendlyName  = TheCommonUtils.CStrNullable(sensorMetaProp?.GetProperty(nameof(TheSensorMeta.FriendlyName))),
                SemanticTypes = TheCommonUtils.CStrNullable(sensorMetaProp?.GetProperty(nameof(TheSensorMeta.SemanticTypes))),
                ExtensionData = ReadDictionaryFromProperties(sensorMetaProp, TheSensorMeta.KnownProperties),
            };

            return(sensorMeta);
        }
Ejemplo n.º 7
0
        void sinkPrePro(cdeP pProp)
        {
            if (TheThing.GetSafePropertyString(MyBaseThing, "StateSensorType") != "analog")
            {
                SetProperty("Value", pProp.Value);
                return;
            }
            int    prepro     = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(MyBaseThing, "PrePro"));
            int    preprotime = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(MyBaseThing, "PreProTime"));
            double valScale   = TheCommonUtils.CDbl(TheThing.GetSafePropertyNumber(MyBaseThing, "StateSensorScaleFactor"));


            var pPropString = TheCommonUtils.CStr(pProp);

            if (!string.IsNullOrEmpty(ValueFilterPattern))
            {
                try
                {
                    if (ValueFilterPattern != filterPattern || filterRegex == null)
                    {
#if !CDE_NET4
                        filterRegex = new Regex(ValueFilterPattern, RegexOptions.Compiled | RegexOptions.CultureInvariant, new TimeSpan(0, 0, 5));
#else
                        filterRegex = new Regex(ValueFilterPattern, RegexOptions.Compiled | RegexOptions.CultureInvariant);
#endif
                        filterPattern = ValueFilterPattern;
                    }
                    pPropString = filterRegex.Match(pPropString).Value;
                }
                catch (Exception e)
                {
                    LastMessage = $"Error applying filter pattern: {e.Message}";
                    return; // CODE REVIEW: Or ist it better to treat this as 0, so other time processing doesn not get confused?
                }
            }

            double pValue;

            if (!string.IsNullOrEmpty(ValueMatchPattern))
            {
                try
                {
                    if (ValueMatchPattern != matchPattern || matchRegex == null)
                    {
#if !CDE_NET4
                        matchRegex = new Regex(ValueMatchPattern, RegexOptions.Compiled | RegexOptions.CultureInvariant, new TimeSpan(0, 0, 5));
#else
                        matchRegex = new Regex(ValueMatchPattern, RegexOptions.Compiled | RegexOptions.CultureInvariant);
#endif
                        matchPattern = ValueMatchPattern;
                    }
                    if (matchRegex.IsMatch(pProp.ToString()))
                    {
                        pValue = 1;
                    }
                    else
                    {
                        pValue = 0;
                    }
                }
                catch (Exception e)
                {
                    LastMessage = $"Error applying match pattern: {e.Message}";
                    return; // CODE REVIEW: Or ist it better to treat this as 0, so other time processing doesn not get confused?
                }
            }
            else
            {
                pValue = TheCommonUtils.CDbl(pPropString);
            }
            if (valScale != 0)
            {
                pValue /= valScale;
            }
            if (pValue < 0 && TheThing.GetSafePropertyBool(MyBaseThing, "StateSensorIsAbs"))
            {
                pValue = Math.Abs(pValue);
            }
            if (preprotime > 0 && prepro > 0)
            {
                if (pValue < min)
                {
                    min = pValue;
                }
                if (pValue > max)
                {
                    max = pValue;
                }
                ave += pValue;
                aveCnt++;
                if (DateTimeOffset.Now.Subtract(lastWrite).TotalSeconds < preprotime)
                {
                    return;
                }
                lastWrite = DateTimeOffset.Now;
                switch (prepro)
                {
                case 1:
                    if (min == double.MaxValue)
                    {
                        return;
                    }
                    pValue = min;
                    min    = double.MaxValue;
                    break;

                case 2:
                    if (max == double.MinValue)
                    {
                        return;
                    }
                    pValue = max;
                    min    = double.MinValue;
                    break;

                case 3:
                    if (aveCnt == 0)
                    {
                        return;
                    }
                    pValue = ave / aveCnt;
                    ave    = 0;
                    aveCnt = 0;
                    break;
                }
            }
            if (GetProperty("StateSensorDigits", false) != null)
            {
                int tDigits = (int)TheThing.GetSafePropertyNumber(MyBaseThing, "StateSensorDigits");
                SetProperty("Value", decimal.Round((decimal)pValue, tDigits, MidpointRounding.AwayFromZero));
            }
            else
            {
                SetProperty("Value", pValue);
            }
        }
Ejemplo n.º 8
0
        private void CreateConfigurationSection(int writeEnableFlag, TheFormInfo tMyForm, int pStartFld, int pParentFld)
        {
            UseTree = TheCommonUtils.CBool(TheBaseAssets.MySettings.GetSetting("UseTreeView"));

            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.CollapsibleGroup, pStartFld, 2, 0xc0, "Tag Management...", null, ThePropertyBag.Create(new nmiCtrlCollapsibleGroup()
            {
                DoClose = !UseTree, IsSmall = true, ParentFld = pParentFld, TileWidth = UseTree ? 18 : 6
            }));

            if (!UseTree)
            {
                TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.SingleEnded, pStartFld + 1, writeEnableFlag, 0xC0, "Browse Branch", "BrowseBranch", new nmiCtrlSingleEnded()
                {
                    ParentFld = pStartFld
                });
            }
#if USE_WEBIX
            else
            {
                var stringCols = TheCommonUtils.SerializeObjectToJSONString(new List <TheWXColumn> {
                    { new TheWXColumn()
                      {
                          TileWidth = 6, Header = "Node Name", ID = "DisplayName", FilterType = "textFilter", Template = "{common.treetable()}{common.treecheckbox()}&nbsp;<strong>#DisplayName#</strong>"
                      } },
                    //{ new TheWXColumn() { TileWidth = 2, Header = "Host Property", ID = "HostPropertyNameOverride", SortType = "string", Flags=2 } },
                    { new TheWXColumn()
                      {
                          TileWidth = 1, Header = "Sample-Rate", ID = "SampleRate", SortType = "int", Flags = 2
                      } },
                    { new TheWXColumn()
                      {
                          TileWidth = 1, Header = "Deadband-Filter", ID = "DeadbandFilterValue", SortType = "int", Flags = 2
                      } },
                    { new TheWXColumn()
                      {
                          TileWidth = 1, Header = "Trigger", ID = "ChangeTrigger", SortType = "int", Flags = 2
                      } },
                    { new TheWXColumn()
                      {
                          TileWidth = 6, Header = "Node ID", ID = "NodeIdName", FilterType = "textFilter", SortType = "int"
                      } }
                });

                OpcTagTree = TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.UserControl, pStartFld + 6, 2, 0, "Sample Tree", "SelectedIs", new nmiCtrlWXTreeTable()
                {
                    ParentFld       = pStartFld,
                    TileWidth       = 12,
                    TileHeight      = 12,
                    NoTE            = true,
                    RootNode        = "Objects",
                    TreeNode        = "Parent",
                    NameNode        = "DisplayName",
                    SelectNode      = "HasActiveHostThing",
                    LeftSplit       = 1,
                    OpenAllBranches = false,
                    SplitCharacter  = ".",
                    Columns         = stringCols
                });
                OpcTagTree.RegisterEvent2("NMI_FIELD_EVENT", (pMSG, para) => {
                    var tUpdate = TheCommonUtils.DeserializeJSONStringToObject <TheWXFieldEvent>(pMSG.Message.PLS);
                    if (tUpdate != null)
                    {
                        var MyTag = MyTags.MyMirrorCache.GetEntryByID(tUpdate.cdeMID);
                        if (MyTag != null)
                        {
                            switch (tUpdate.Name)
                            {
                            case "SampleRate":
                                MyTag.SampleRate = TheCommonUtils.CInt(tUpdate.Value);
                                break;

                            case "DeadbandFilterValue":
                                MyTag.DeadbandFilterValue = TheCommonUtils.CDbl(tUpdate.Value);
                                break;

                            case "ChangeTrigger":
                                MyTag.ChangeTrigger = TheCommonUtils.CInt(tUpdate.Value);
                                break;
                            }
                        }
                    }
                });
            }
#endif

            // BROWSE Button
            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.TileButton, pStartFld + 2, writeEnableFlag, 0xC0, "Browse", null, new nmiCtrlTileButton()
            {
                ParentFld = pStartFld, ClassName = "cdeGoodActionButton", TileWidth = 3, NoTE = true
            })
            .RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "BROWSE", (pThing, pObj) =>
            {
                TheProcessMessage pMsg = pObj as TheProcessMessage;
                if (pMsg == null || pMsg.Message == null)
                {
                    return;
                }
                if (ConnectionState != ConnectionStateEnum.Connected)
                {
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Server not connected - please connect first"));
                }
                else
                {
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Browsing..."));
                    LastMessage   = "Browsing Started at " + DateTimeOffset.Now.ToString();
                    BrowsedTagCnt = 0;
                    Browser(currentRoot, currentRoot.ToString(), true, false, null);


                    var dataModelJson = TheCommonUtils.SerializeObjectToJSONString(
                        MyTags.MyMirrorCache.TheValues
                        .Where(t => t.HostPropertyNameOverride?.Contains("].[") != true)     // Filter out any DataValue sub-properties (i.e. engineering units), as the tree view doesn't seem to handle nodes under leaf-nodes (or inner nodes with data) yet
                        .ToList());
                    OpcTagTree?.SetUXProperty(pMsg.Message.GetOriginator(), $"DataModel={dataModelJson}", true);
                    LastMessage += " - Browsing done at " + DateTimeOffset.Now.ToString();
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", LastMessage));
                }
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.Number, pStartFld + 3, 0, 0x0, "Browsed Tags:", "BrowsedTagCnt", new nmiCtrlNumber()
            {
                ParentFld = pStartFld, TileWidth = 3
            });


            ///Browsed TAGS Form
            {
                var tDataSource = "TheOPCTags";
                if (MyTags != null)
                {
                    tDataSource = MyTags.StoreMID.ToString();
                }
                var tOPCTagForm = new TheFormInfo(TheThing.GetSafeThingGuid(MyBaseThing, "TAGLIST_ID"), eEngineName.NMIService, "OPC-UA Server Tags", $"{tDataSource};:;1000")
                {
                    IsNotAutoLoading = true, AddButtonText = "Add new Tag", PropertyBag = new nmiCtrlTableView {
                        ShowFilterField = true
                    }
                };
                TheNMIEngine.AddFormToThingUX(MyBaseThing, tOPCTagForm, "CMyTable", "Tag List", 1, 3, 0xF0, null, null, new ThePropertyBag()
                {
                    "Visibility=false"
                });
                TheNMIEngine.AddFields(tOPCTagForm, new List <TheFieldInfo> {
                    // 1: Thing subscription
                    { new TheFieldInfo()
                      {
                          FldOrder = 3, DataItem = "IsSubscribedAsThing", Flags = 0, Type = eFieldType.SingleCheck, Header = "Has Tag Thing", FldWidth = 1
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 11, DataItem = "Parent", Flags = 0, Type = eFieldType.SingleEnded, Header = "Parent", FldWidth = 4
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 12, DataItem = "DisplayName", Flags = 0, Type = eFieldType.SingleEnded, Header = "Name", FldWidth = 3
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 13, DataItem = nameof(TheOPCTag.HostPropertyNameOverride), Flags = writeEnableFlag, Type = eFieldType.SingleEnded, Header = "Host Property Name", FldWidth = 3
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 14, DataItem = "HostThingMID", Flags = writeEnableFlag, Type = eFieldType.ThingPicker, Header = "Host Thing", FldWidth = 3
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 15, DataItem = nameof(TheOPCTag.ChangeTrigger), Flags = writeEnableFlag, Type = eFieldType.ComboBox, Header = "Change Trigger", FldWidth = 1, PropertyBag = new nmiCtrlComboBox {
                              Options = "Status:0;Value:1;Value & Timestamp:2"
                          }
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 16, DataItem = nameof(TheOPCTag.SampleRate), Flags = writeEnableFlag, Type = eFieldType.Number, Header = "Sample Rate (ms)", FldWidth = 1
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 17, DataItem = nameof(TheOPCTag.DeadbandFilterValue), Flags = writeEnableFlag, Type = eFieldType.Number, Header = "Deadband", FldWidth = 1
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 18, DataItem = "NodeIdName", Flags = 2, Type = eFieldType.SingleEnded, Header = "NodeId", FldWidth = 6
                      } },
                    // 30: Property subscription
                    { new TheFieldInfo()
                      {
                          FldOrder = 19, DataItem = nameof(TheOPCTag.HistoryStartTime), Flags = writeEnableFlag, Type = eFieldType.SingleEnded, Header = "History Start", FldWidth = 3
                      } },
                    //{  new TheFieldInfo() { FldOrder=13,DataItem="PropAttr.7.Value.Value",Flags=0,Type=eFieldType.SingleEnded,Header="Value",FldWidth=5 }},
                    //{  new TheFieldInfo() { FldOrder=14,DataItem="PropAttr.7.DataType",Flags=0,Type=eFieldType.SingleEnded,Header="Type",FldWidth=5 }},
                });
                TheNMIEngine.AddTableButtons(tOPCTagForm, false, 100, 0);

                // Button Subscribe as Thing
                TheNMIEngine.AddSmartControl(MyBaseThing, tOPCTagForm, eFieldType.TileButton, 1, writeEnableFlag, 0xC0, "Create Tag Thing", null, new nmiCtrlTileButton()
                {
                    ClassName = "cdeGoodActionButton", TileHeight = 1
                })
                .RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "SUBSCRIBE", (tThing, pMsg) => SubscribeAsThing(tThing, pMsg, MyTags));

                // Button: Subscribe property into host thing
                TheNMIEngine.AddSmartControl(MyBaseThing, tOPCTagForm, eFieldType.TileButton, 5, writeEnableFlag, 0xC0, "Monitor as Property", null, new nmiCtrlTileButton()
                {
                    ClassName = "cdeGoodActionButton", TileHeight = 1
                })
                .RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "SUBSCRIBEPROP", (tThing, pMsg) => SubscribeAsProperty(tThing, pMsg, MyTags));

                TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.TileButton, pStartFld + 4, writeEnableFlag, 0xF0, "Show Tag List", null, new nmiCtrlTileButton()
                {
                    OnClick = $"TTS:{tOPCTagForm.cdeMID}", ParentFld = pStartFld, ClassName = "cdeTransitButton", TileWidth = 3, NoTE = true
                });
            }

            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.Number, pStartFld + 5, writeEnableFlag, 0xC0, "Default Sample Rate", nameof(DefSampleRate), new nmiCtrlNumber()
            {
                ParentFld = pStartFld, TileWidth = 3
            });


            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.ThingPicker, pStartFld + 6, writeEnableFlag, 0xC0, "Thing for Property Subs", "TagHostThingForSubscribeAll", new nmiCtrlThingPicker()
            {
                NoTE = true, ParentFld = pStartFld, TileWidth = 4
            });

            // SUBSCRIBE all tags as Properties
            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.TileButton, pStartFld + 7, writeEnableFlag, 0xC0, $"Subscribe {(UseTree ? "selected" : "all")} in properties", null, new nmiCtrlTileButton()
            {
                ParentFld = pStartFld, ClassName = "cdeGoodActionButton", TileWidth = 2, NoTE = true
            })
            .RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "ALLTAGS", (pThing, pObj) =>
            {
                TheProcessMessage pMsg = pObj as TheProcessMessage;
                if (pMsg == null || pMsg.Message == null)
                {
                    return;
                }
                if (ConnectionState != ConnectionStateEnum.Connected)
                {
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Server not connected - please connect first"));
                }
                else
                {
                    var tHostThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(this.TagHostThingForSubscribeAll));
                    if (tHostThing == null)
                    {
                        TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Host Thing not specified or invalid"));
                        return;
                    }
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Subscribing..."));

                    if (MyTags.MyMirrorCache.Count == 0 && !UseTree)
                    {
                        // Clear all previous subscription in either MyTags (tag as thing) oder HostThing (tag as property)
                        MyTags.MyMirrorCache.Reset();

                        // TODO Figure out how to clean up subscribed things in properties.
                        // - Can't just delete as a customer may have hand picked certain properties via browse paths etc.
                        // - Allow customer to use multiple host things?
                        //var tThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(TagHostThing));
                        //if (tThing != null)
                        //{
                        //    foreach (var prop in tThing.GetPropertiesMetaStartingWith("OPCUA:"))
                        //    {
                        //        tThing.RemoveProperty(prop.Name);
                        //    }
                        //}

                        LastMessage = "Subscribing started at " + DateTimeOffset.Now.ToString();

                        BrowsedTagCnt = 0;

                        Browser(currentRoot, currentRoot.ToString(), true, true, tHostThing, CreateIDFilter());

                        LastMessage += " - Subscribing done at " + DateTimeOffset.Now.ToString();
                        TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", LastMessage));
                    }
                    else
                    {
                        // Previously browsed: use those tags to do the subscriptions
                        LastMessage = "Subscribing started at " + DateTimeOffset.Now.ToString();

                        var subscription = GetOrCreateSubscription(0);
                        var pFilterIDs   = CreateIDFilter();
                        int count        = 0;
                        //var results = new List<Opc.Ua.Client.MonitoredItem>();//CM: removed as Nothing is done with "results"

                        foreach (var tag in MyTags.TheValues)
                        {
                            string tagNameForFilter;
                            if (tag.DisplayName == "EngineeringUnits" || tag.DisplayName == "EURange")
                            {
                                tagNameForFilter = tag.Parent;
                            }
                            else
                            {
                                tagNameForFilter = $"{tag.Parent}.{tag.DisplayName}";
                            }

                            if (pFilterIDs != null && pFilterIDs.Contains(tagNameForFilter))
                            {
                                tag.HostThingMID = TheCommonUtils.cdeGuidToString(tHostThing.cdeMID);
                                var childTags    = tag.GetChildTags();
                                if (childTags?.Any() == true)
                                {
                                    foreach (var childTag in childTags)
                                    {
                                        childTag.HostThingMID = tag.HostThingMID;
                                    }
                                }
                                if (!RegisterAndMonitorTagInHostThing(subscription, tag, out string error, false, true, false) || !string.IsNullOrEmpty(error))
                                {
                                    // error
                                }
Ejemplo n.º 9
0
        private void GetISMHealthData()
        {
            if (TheCommonUtils.cdeIsLocked(GetHealthLock) || !AreCounterInit)
            {
                return;
            }
            lock (GetHealthLock)
            {
                MyHealthData.StationWatts     = LastStationWatts;
                MyHealthData.QSenders         = TheCDEKPIs.QSenders;
                MyHealthData.QSReceivedTSM    = TheCDEKPIs.QSReceivedTSM;
                MyHealthData.QSSendErrors     = TheCDEKPIs.QSSendErrors;
                MyHealthData.QSInserted       = TheCDEKPIs.QSInserted;
                MyHealthData.QSQueued         = TheCDEKPIs.QSQueued;
                MyHealthData.QSRejected       = TheCDEKPIs.QSRejected;
                MyHealthData.QSSent           = TheCDEKPIs.QSSent;
                MyHealthData.QKBSent          = Math.Floor(TheCDEKPIs.QKBSent > 0 ? TheCDEKPIs.QKBSent / 1024 : 0);
                MyHealthData.QKBReceived      = Math.Floor(TheCDEKPIs.QKBReceived > 0 ? TheCDEKPIs.QKBReceived / 1024 : 0);
                MyHealthData.QSLocalProcessed = TheCDEKPIs.QSLocalProcessed;

                MyHealthData.CCTSMsRelayed      = TheCDEKPIs.CCTSMsRelayed;
                MyHealthData.CCTSMsReceived     = TheCDEKPIs.CCTSMsReceived;
                MyHealthData.CCTSMsEvaluated    = TheCDEKPIs.CCTSMsEvaluated;
                MyHealthData.EventTimeouts      = TheCDEKPIs.EventTimeouts;
                MyHealthData.TotalEventTimeouts = TheCDEKPIs.TotalEventTimeouts;
                MyHealthData.KPI1        = TheCDEKPIs.KPI1;
                MyHealthData.KPI2        = TheCDEKPIs.KPI2;
                MyHealthData.KPI3        = TheCDEKPIs.KPI3;
                MyHealthData.KPI4        = TheCDEKPIs.KPI4;
                MyHealthData.KPI5        = TheCDEKPIs.KPI5;
                MyHealthData.KPI6        = TheCDEKPIs.KPI6;
                MyHealthData.KPI7        = TheCDEKPIs.KPI7;
                MyHealthData.KPI8        = TheCDEKPIs.KPI8;
                MyHealthData.KPI9        = TheCDEKPIs.KPI9;
                MyHealthData.KPI10       = TheCDEKPIs.KPI10;
                MyHealthData.HTCallbacks = TheCDEKPIs.HTCallbacks;
                TheCDEKPIs.Reset();

                MyHealthData.HostAddress  = System.Environment.MachineName;
                MyHealthData.FriendlyName = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false);
                MyHealthData.HostVersion  = TheBaseAssets.MyServiceHostInfo.Version;
                MyHealthData.LastUpdate   = DateTimeOffset.Now;
                DiskInfo di = GetDiskInfo();
                MyHealthData.DiskSpaceFree = di.TotalFreeSpace;
                if (di.TotalSize > 0 && di.TotalFreeSpace <= di.TotalSize)
                {
                    MyHealthData.DiskSpaceUsage = ((di.TotalSize - di.TotalFreeSpace) / di.TotalSize) * 100;
                }
                else
                {
                    MyHealthData.DiskSpaceUsage = 0;
                }

                try
                {
                    if (wmiObjectWin32 != null)
                    {
                        var tRed         = wmiObjectWin32.Get().Cast <ManagementObject>();
                        var memoryValues = tRed.Select(mo => new
                        {
                            FreePhysicalMemory     = TheCommonUtils.CDbl(mo["FreePhysicalMemory"].ToString()),
                            TotalVisibleMemorySize = TheCommonUtils.CDbl(mo["TotalVisibleMemorySize"].ToString())
                        }).FirstOrDefault();

                        if (memoryValues != null)
                        {
                            MyHealthData.RAMAvailable = memoryValues.FreePhysicalMemory;
                            //var percent = ((memoryValues.TotalVisibleMemorySize - memoryValues.FreePhysicalMemory) / memoryValues.TotalVisibleMemorySize) * 100;
                        }
                    }
                }
                catch (Exception e)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(8007, new TSM("jcHealth", "wmiObject-Warning (Not Supported on XP)", eMsgLevel.l2_Warning, e.ToString()));
                }

                try
                {
                    MeasureProcessCPU();
                    MyHealthData.cdeLoad = cpuUsageSinceLastMeasure; // Can also use cpuUsageSinceStart, depending on purpose of metric
                }
                catch (Exception e)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(8007, new TSM("jcHealth", "Could not get CPU usage for process", eMsgLevel.l2_Warning, e.ToString()));
                }

                try
                {
                    if (MyCPULoadCounter != null)
                    {
                        MyHealthData.CPULoad = TheCommonUtils.CDbl(MyCPULoadCounter.NextValue()).cdeTruncate(2);
                    }
                }
                catch (Exception e)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(8007, new TSM("jcHealth", "PerfCounter-Warning (Not Supported on XP)", eMsgLevel.l2_Warning, e.ToString()));
                    MyCPULoadCounter = new PerformanceCounter
                    {
                        CategoryName = "Processor Information",
                        CounterName  = "% Processor Time",
                        InstanceName = "_Total"
                    };
                }
                try
                {
                    //if (MyHealthData != null && MyCDELoadCounter != null)
                    //    MyHealthData.cdeLoad = MyCDELoadCounter.NextValue().cdeTruncate(2);
                }
                catch (Exception e)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(8007, new TSM("jcHealth", "PerfCounter-Warning (Not Supported on XP)", eMsgLevel.l2_Warning, e.ToString()));
                    MyCDELoadCounter = new PerformanceCounter
                    {
                        CategoryName = "Process",
                        CounterName  = "% Processor Time",
                        InstanceName = Process.GetCurrentProcess().ProcessName
                    };
                }

                if (UseNicState)
                {
                    UpdateNetworkInterface();
                }
                else
                {
                    if (MyCounter?.Count > 0)
                    {
                        foreach (var t in MyCounter)
                        {
                            try
                            {
                                MyHealthData.SetProperty(t.PropertyName, t.PerfCounter.NextValue());
                            }
                            catch (Exception)
                            {
                                TheBaseAssets.MySYSLOG.WriteToLog(8007, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("jcHealth", $"PerfCounter: {t.PropertyName} could not be read", eMsgLevel.l2_Warning));
                            }
                        }
                    }
                }

                try
                {
                    MyHealthData.cdeCTIM    = DateTimeOffset.Now;
                    MyHealthData.LastUpdate = DateTimeOffset.Now;
                    using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select CreationDate from Win32_Process where Name='System'"))
                    {
                        foreach (ManagementObject share in searcher.Get())
                        {
                            foreach (PropertyData pData in share.Properties)
                            {
                                if (pData.Name.Equals("CreationDate"))
                                {
                                    DateTime dc = ManagementDateTimeConverter.ToDateTime(TheCommonUtils.CStr(pData.Value));
                                    //dc = dc.AddTicks(-TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Ticks).ToLocalTime();
                                    TimeSpan ts = DateTime.Now.Subtract(dc);
                                    MyHealthData.PCUptime = ts.TotalMinutes;
                                }
                            }
                        }
                    }


                    /// cde Process Specific Information
                    int nProcessID = Process.GetCurrentProcess().Id;
                    using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select CreationDate,WorkingSetSize,HandleCount,ThreadCount from Win32_Process where ProcessID='" + nProcessID + "'"))
                    {
                        foreach (ManagementObject share in searcher.Get())
                        {
                            foreach (PropertyData PC in share.Properties)
                            {
                                string objName  = PC.Name;
                                string objValue = "";
                                if (PC.Value != null && PC.Value.ToString() != "")
                                {
                                    switch (PC.Value.GetType().ToString())
                                    {
                                    case "System.String[]":
                                        string[] str = (string[])PC.Value;
                                        foreach (string st in str)
                                        {
                                            objValue += st + " ";
                                        }
                                        break;

                                    case "System.UInt16[]":
                                        ushort[] shortData = (ushort[])PC.Value;
                                        foreach (ushort st in shortData)
                                        {
                                            objValue += st.ToString() + " ";
                                        }
                                        break;

                                    default:
                                        objValue = PC.Value.ToString();
                                        break;
                                    }
                                }
                                switch (objName)
                                {
                                case "CreationDate":
                                    DateTime dc = ManagementDateTimeConverter.ToDateTime(PC.Value.ToString());
                                    //dc=dc.AddTicks(-TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Ticks).ToLocalTime();
                                    TimeSpan ts = DateTime.Now.Subtract(dc);
                                    MyHealthData.cdeUptime = ts.TotalMinutes;
                                    break;

                                case "WorkingSetSize":
                                    MyHealthData.cdeWorkingSetSize = TheCommonUtils.CLng(objValue) / 1024;
                                    break;

                                case "HandleCount":
                                    MyHealthData.cdeHandles = TheCommonUtils.CInt(objValue);
                                    break;

                                case "ThreadCount":
                                    MyHealthData.cdeThreadCount = TheCommonUtils.CInt(objValue);
                                    break;
                                }
                            }
                            break;
                        }
                    }
                    //if (!WasRunBefore)
                    UpdateDiagInfo(MyHealthData);
                }
                catch (Exception e)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(8008, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("jcHealth", "Ring0-Warning", eMsgLevel.l2_Warning, e.ToString()));
                }
            }
        }
Ejemplo n.º 10
0
        internal void RuleTrigger(string tVal, bool bForce = false)
        {
            MyBaseThing.Value = tVal;
            switch (TriggerCondition)
            {
            case eRuleTrigger.Not:
                if (!TriggerValue.Equals(tVal, StringComparison.OrdinalIgnoreCase))
                {
                    FireAction(bForce);
                }
                break;

            case eRuleTrigger.Larger:
                if (TheCommonUtils.CDbl(TriggerValue) < TheCommonUtils.CDbl(tVal) && TheCommonUtils.CDbl(TriggerValue) >= TheCommonUtils.CDbl(TriggerOldValue))
                {
                    FireAction(bForce);
                }
                break;

            case eRuleTrigger.Smaller:
                if (TheCommonUtils.CDbl(TriggerValue) > TheCommonUtils.CDbl(tVal) && TheCommonUtils.CDbl(TriggerValue) <= TheCommonUtils.CDbl(TriggerOldValue))
                {
                    FireAction(bForce);
                }
                break;

            case eRuleTrigger.Contains:
                if (tVal.ToLower().Contains(TriggerValue.ToLower()))
                {
                    FireAction(bForce);
                }
                break;

            case eRuleTrigger.StartsWith:
                if (tVal.StartsWith(TriggerValue, StringComparison.OrdinalIgnoreCase))
                {
                    FireAction(bForce);
                }
                break;

            case eRuleTrigger.EndsWith:
                if (tVal.EndsWith(TriggerValue, StringComparison.OrdinalIgnoreCase))
                {
                    FireAction(bForce);
                }
                break;

            case eRuleTrigger.Set:
                if (!string.IsNullOrEmpty(TriggerValue))
                {
                    string expression = tVal + TriggerValue;
                    ActionValue = Evaluate(expression).ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    ActionValue = tVal;
                }
                FireAction(bForce);
                break;

            case eRuleTrigger.Equals:
                if (TriggerValue.Equals(tVal, StringComparison.OrdinalIgnoreCase))
                {
                    FireAction(bForce);
                }
                break;

            case eRuleTrigger.Fire:
                FireAction(bForce);
                break;

            case eRuleTrigger.Flank:
                if (TheCommonUtils.IsNullOrWhiteSpace(TriggerValue))
                {
                    if (!TriggerOldValue.Equals(tVal, StringComparison.OrdinalIgnoreCase))
                    {
                        FireAction(bForce);
                    }
                    break;
                }
                string[] tTrigs = TriggerValue.Split(',');
                if (tTrigs.Length == 1)
                {
                    if (Math.Abs(TheCommonUtils.CDbl(TriggerValue) - TheCommonUtils.CDbl(tVal)) < double.Epsilon && Math.Abs(TheCommonUtils.CDbl(TriggerOldValue) - TheCommonUtils.CDbl(tVal)) > double.Epsilon)
                    {
                        FireAction(false);
                    }
                }
                else
                {
                    if (Math.Abs(TheCommonUtils.CDbl(tVal) - TheCommonUtils.CDbl(TriggerOldValue)) > Double.Epsilon &&
                        Math.Abs(TheCommonUtils.CDbl(TriggerOldValue) - TheCommonUtils.CDbl(tTrigs[0])) < double.Epsilon &&
                        Math.Abs(TheCommonUtils.CDbl(tVal) - TheCommonUtils.CDbl(tTrigs[1])) < Double.Epsilon)
                    {
                        FireAction(bForce);
                    }
                }
                break;

            case eRuleTrigger.State:
                if (TriggerOldValue.Equals(tVal, StringComparison.OrdinalIgnoreCase))
                {
                    FireAction(bForce);
                }
                break;
            }
            TriggerOldValue = tVal;
        }
Ejemplo n.º 11
0
        public override void OnNewEvent(TheProcessMessage timer, object unused)
        {
            TheEventLogEntry tEntry = timer?.Cookie as TheEventLogEntry;

            if (tEntry == null)
            {
                return;
            }
            if (!string.IsNullOrEmpty(MyBaseThing.Address) && tEntry?.Message?.TXT?.Contains(MyBaseThing.Address) == true) //Avoid recursive
            {
                return;
            }
            var t = new TheGELFLogEntry()
            {
                version = "1.1",
                host    = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false),
                level   = (int)tEntry.Message?.LVL,
#if CDE_NET45 || CDE_NET4 || CDE_NET35
                timestamp = TheCommonUtils.CDbl($"{(tEntry.Message.TIM.Subtract(new DateTime(1970, 1, 1))).TotalSeconds}.{tEntry.Message.TIM.Millisecond}"),
#else
                timestamp = TheCommonUtils.CDbl($"{tEntry.Message.TIM.ToUnixTimeSeconds()}.{tEntry.Message.TIM.Millisecond}"),
#endif
                full_message  = tEntry.Message?.PLS,
                short_message = tEntry.Message?.TXT,
                _log_id       = tEntry.EventID,
                _serial_no    = tEntry.Serial,
                _engine       = tEntry.Message.ENG,
                _device_id    = tEntry.Message.GetOriginator().ToString()
            };

            try
            {
                if (!string.IsNullOrEmpty(MyBaseThing.Address))
                {
                    var pData = new TheRequestData()
                    {
                        RequestUri       = new Uri($"{MyBaseThing.Address}/gelf"),
                        ResponseMimeType = "application/json",
                        PostData         = TheCommonUtils.CUTF8String2Array(TheCommonUtils.SerializeObjectToJSONString <TheGELFLogEntry>(t)),
                        DontCompress     = true
                    };

                    MyRest.PostRESTAsync(pData, (okData) =>
                    {
                        MyBaseThing.StatusLevel = 1;
                    }, (errData) =>
                    {
                        MyBaseThing.LastMessage = $"Post to Log Error: {errData.ErrorDescription}";
                        MyBaseThing.StatusLevel = 2;
                    });
                }
            }
            catch (Exception e)
            {
                MyBaseThing.LastMessage = $"Cannot Post to Log Error: {e.Message}";
                MyBaseThing.StatusLevel = 2;
            }

            if (TheThing.GetSafePropertyBool(MyBaseThing, "ToConsole"))
            {
                Console.WriteLine(TheCommonUtils.SerializeObjectToJSONString <TheGELFLogEntry>(t));
            }
        }
Ejemplo n.º 12
0
        protected override void SensorCyclicCalc(long timer)
        {
            base.SensorCyclicCalc(timer);
            if ((timer % PingFreq) != 0)
            {
                return;
            }
            if (IsInCyclic)
            {
                return;
            }
            IsInCyclic = true;
            PingFreq   = (int)TheThing.GetSafePropertyNumber(MyBaseEngine.GetBaseThing(), "CalcAggregation");
            if (PingFreq == 0)
            {
                PingFreq = 30;
            }

            var tVals = MyHistorian?.GetValues();   //TODO: This returns null if the SensorHistorian is in the SQL Server. We need to think about what we do here!

            if (tVals?.Any() == true)
            {
                string tValues = TheThing.GetSafePropertyString(MyBaseThing, "HistoryFields");
                if (tValues.Contains("QValue_Ave"))
                {
                    TheThing.SetSafePropertyNumber(MyBaseThing, "QValue_Ave", tVals.Average(w => w.PB.ContainsKey("QValue") ? TheCommonUtils.CDbl(w.PB["QValue"]) : 0));
                }
                if (tValues.Contains("QValue_Min"))
                {
                    TheThing.SetSafePropertyNumber(MyBaseThing, "QValue_Min", tVals.Min(w => w.PB.ContainsKey("QValue") ? TheCommonUtils.CDbl(w.PB["QValue"]) : 0));
                }
                if (tValues.Contains("QValue_Max"))
                {
                    TheThing.SetSafePropertyNumber(MyBaseThing, "QValue_Max", tVals.Max(w => w.PB.ContainsKey("QValue") ? TheCommonUtils.CDbl(w.PB["QValue"]) : 0));
                }
            }
            IsInCyclic = false;
        }
Ejemplo n.º 13
0
        public override bool Init()
        {
            if (mIsInitCalled)
            {
                return(false);
            }
            mIsInitCalled = true;

            MyBaseThing.StatusLevel = 4;
            string temp;

            TheBaseAssets.MyCmdArgs.TryGetValue("IsHealthCollectionOff", out temp);
            if (!string.IsNullOrEmpty(temp))
            {
                IsHealthCollectionOff = TheCommonUtils.CBool(temp);
            }
            if (HealthCollectionCycle == 0)
            {
                TheBaseAssets.MyCmdArgs.TryGetValue("HealthCollectionCycle", out temp);
                if (!string.IsNullOrEmpty(temp))
                {
                    HealthCollectionCycle = TheCommonUtils.CInt(temp);
                }
                if (HealthCollectionCycle == 0)
                {
                    HealthCollectionCycle = 15;
                }
            }

            if (SensorDelay == 0)
            {
                TheBaseAssets.MyCmdArgs.TryGetValue("SensorDelay", out temp);
                if (!string.IsNullOrEmpty(temp))
                {
                    SensorDelay = TheCommonUtils.CInt(temp);
                }
                if (SensorDelay == 0)
                {
                    SensorDelay = 500;
                }
            }

            if (SensorAccelDeadband < 1)
            {
                TheBaseAssets.MyCmdArgs.TryGetValue("SensorAccelDeadband", out temp);
                if (!string.IsNullOrEmpty(temp))
                {
                    SensorAccelDeadband = TheCommonUtils.CDbl(temp);
                }
                if (SensorAccelDeadband < 0.1)
                {
                    SensorAccelDeadband = 3.0;
                }
            }
            int tBS = (int)TheThing.GetSafePropertyNumber(MyBaseThing, "ChartValues");

            if (tBS < 10)
            {
                tBS = 1000;
                TheThing.SetSafePropertyNumber(MyBaseThing, "ChartValues", tBS);
            }
            tBS = (int)TheThing.GetSafePropertyNumber(MyBaseThing, "ChartSize");
            if (tBS < 6)
            {
                tBS = 18;
                TheThing.SetSafePropertyNumber(MyBaseThing, "ChartSize", tBS);
            }

            TheUserManager.RegisterNewRole(new TheUserRole(new Guid("{0A254170-D4D4-4B2D-9E05-D471729BE739}"), "ComputerManager", 1, new Guid("{3FB56264-9AA8-4AC9-9208-A01F1142B153}"), true, "Person allowed to view Computer Details"));
            MyBaseThing.RegisterEvent(eEngineEvents.IncomingMessage, HandleMessage);        //Event when C-DEngine has new Telegram for this service as a subscriber (Client Side)
            MyBaseThing.RegisterEvent("FileReceived", sinkFileReceived);
            MyBaseThing.RegisterEvent(eEngineEvents.ShutdownEvent, sinkEngineShutdown);
            StartEngineServices();
            if (MyBaseThing.StatusLevel == 4)
            {
                MyBaseThing.StatusLevel = 1;
            }
            mIsInitialized = true;
            return(true);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Checks if a property already matches a desired value.  Sets the property and
        /// notifies listeners only when necessary.
        /// </summary>
        /// <typeparam name="T">Type of the property.</typeparam>
        /// <param name="storage">Reference to a property with both getter and setter.</param>
        /// <param name="value">Desired value for the property.</param>
        /// <param name="cdeT">Type of this property - important for comparison with old value</param>
        /// <param name="cdeE">Extended Flags of the value</param>
        /// <param name="propertyName">Name of the property used to notify listeners.  This
        /// value is optional and can be provided automatically when invoked from compilers that
        /// support CallerMemberName.</param>
        /// <returns>True if the value was changed, false if the existing value matched the
        /// desired value.</returns>
        protected bool SetProperty <T>(ref T storage, T value, int cdeT, int cdeE, string propertyName = null)
        {
            if ((cdeE & 8) == 0)
            {
                if ((cdeE & 1) != 0)    //Required in case the property is encrypted.
                {
                    if (Equals(storage, value))
                    {
                        return(false);
                    }
                }
                else
                {
                    switch (cdeT)
                    {
                    case 1:
                        if (Math.Abs(TheCommonUtils.CDbl(storage) - TheCommonUtils.CDbl(value)) < Double.Epsilon &&
                            (storage == null && value == null || storage != null && value != null))        // 3.217: treat 0 and null as different
                        {
                            return(false);
                        }
                        break;

                    case 2:
                        if (TheCommonUtils.CBool(storage) == TheCommonUtils.CBool(value) &&
                            (storage == null && value == null || storage != null && value != null))        // 3.217: treat 0 and null as different
                        {
                            return(false);
                        }
                        value = (T)((object)TheCommonUtils.CBool(value));
                        break;

                    case 3:
                        if (storage != null && value != null && TheCommonUtils.CDate(storage) == TheCommonUtils.CDate(value))
                        {
                            return(false);
                        }
                        break;

                    case 4:     //Binary Comparison - TODO:CODEREVIEW Could be very expensive to do Byte[] comparison
                        if ((storage == null && value == null))
                        {
                            return(false);                                       // || ((storage as byte[]).GetHashCode() == (value as byte[]).GetHashCode())) return false;
                        }
                        break;

                    case 5:     //Function - Never Set it!
                        return(false);

                    case 6:
                        if (TheCommonUtils.CGuid(storage) == TheCommonUtils.CGuid(value))
                        {
                            return(false);
                        }
                        break;

                    default:
                        if (Equals(storage, value))
                        {
                            return(false);
                        }
                        break;
                    }
                }
            }
            storage = value; // CORE REVIEW Markus: SHould we clone the value here to prevent future modification?
            // CODE REVIEW: There is a race condition between setting mHasChanged and delivering the change notification. Should we raise the notification outside or is this mostly obsolete anyway (XAML only)?
            OnPropertyChanged(propertyName);
            return(true);
        }