예제 #1
0
        public override bool Init()
        {
            if (!mIsInitStarted)
            {
                mIsInitStarted = true;
                MyBaseEngine.RegisterEvent(eEngineEvents.ShutdownEvent, OnShutdown);
                TheThing.SetSafePropertyBool(MyBaseThing, "IsConnected", false);

                IBaseEngine tBase = TheThingRegistry.GetBaseEngine(TheThing.GetSafePropertyString(MyBaseThing, "ISOLaterName"), true);
                if (tBase != null)
                {
                    MyIsolator = tBase.GetISOLater() as Process;
                    if (MyIsolator == null)
                    {
                        MyBaseThing.LastMessage = "Engine not isolated";
                        MyBaseThing.StatusLevel = 3;
                        mIsInitCompleted        = true;
                        return(true);
                    }
                    MyBaseThing.LastMessage = "KPIs monitor ready";
                    MyBaseThing.StatusLevel = 1;
                    if (TheThing.GetSafePropertyBool(MyBaseThing, "AutoConnect"))
                    {
                        Connect();
                    }
                }
                else
                {
                    MyBaseThing.LastMessage = "Base Engine cloud not be located";
                    MyBaseThing.StatusLevel = 3;
                }
                mIsInitCompleted = true;
            }
            return(true);
        }
예제 #2
0
        public virtual bool Init()
        {
            if (mIsInitCalled)
            {
                return(false);
            }
            mIsInitCalled = true;

            if (string.IsNullOrEmpty(MyBaseThing.ID))
            {
                MyBaseThing.ID = Guid.NewGuid().ToString();
                this.Gen_Config_StatsUpdateInterval = 5000;
            }
            MyBaseThing.Value = "0";
            TheThing.SetSafePropertyBool(MyBaseThing, "IsActive", true);
            MyBaseThing.GetProperty(nameof(Gen_Config_PropertyUpdateInterval), true).RegisterEvent(eThingEvents.PropertyChanged, OnChangeTimer);
            MyBaseThing.GetProperty(nameof(Gen_Config_NumberOfActiveProperties), true).RegisterEvent(eThingEvents.PropertyChanged, OnChangeTimer);
            MyBaseThing.StatusLevel = 0;
            if (TheThing.GetSafePropertyBool(MyBaseThing, "AutoStart"))
            {
                OnChangeTimer(null);
            }
            mIsInitialized = true;
            return(true);
        }
예제 #3
0
 public virtual bool Init(bool declareInit)
 {
     if (mIsInitCalled)
     {
         return(false);
     }
     mIsInitCalled           = true;
     IsConnected             = false;
     MyBaseThing.StatusLevel = 0;
     MyBaseThing.LastMessage = "Service is ready";
     MyBaseThing.RegisterStatusChanged(sinkUpdateUX);
     MyBaseThing.RegisterEvent(eEngineEvents.IncomingMessage, HandleMessage);
     if (string.IsNullOrEmpty(MyBaseThing.ID))
     {
         MyBaseThing.ID = Guid.NewGuid().ToString();
         TheThing.SetSafePropertyBool(MyBaseThing, "IsStateSensor", true);
         TheThing.SetSafePropertyString(MyBaseThing, "StateSensorType", "analog");
         TheThing.SetSafePropertyString(MyBaseThing, "StateSensorUnit", "ms");
         TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorMaxValue", 100);
         TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorAverage", 50);
         TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorMinValue", 0);
         //TheThing.SetSafePropertyString(MyBaseThing, "StateSensorName", MyBaseThing.FriendlyName);
         TheRulesFactory.CreateOrUpdateRule(new TheThingRule(Guid.NewGuid(), "NetService:" + MyBaseThing.FriendlyName + " Failed", MyBaseThing, "StatusLevel", eRuleTrigger.Larger, "1", true, true));
     }
     if (declareInit)
     {
         mIsInitialized = true;
     }
     return(true);
 }
예제 #4
0
        private void SetCtrlType()
        {
            if (CountBar == null)
            {
                return;
            }
            string     tControl  = ThePropertyBag.PropBagGetValue(CountBar.PropertyBag, "ControlType", "=");
            eFieldType tCtrlType = eFieldType.SingleEnded;

            if (!string.IsNullOrEmpty(tControl) && TheCommonUtils.CInt(tControl) == 0 && tControl.Length > 0)
            {
                TheControlType tType = TheNMIEngine.GetControlTypeByType(tControl);
                if (tType != null)
                {
                    ThePropertyBag.PropBagUpdateValue(CountBar.PropertyBag, "EngineName", "=", tType.BaseEngineName);
                }
                tCtrlType = eFieldType.UserControl;
            }
            else
            {
                tCtrlType = (eFieldType)TheCommonUtils.CInt(tControl);
            }
            CountBar.Type        = tCtrlType;
            CountBar.Flags       = TheCommonUtils.CInt(ThePropertyBag.PropBagGetValue(CountBar.PropertyBag, "Flags", "="));
            CountBar.PropertyBag = new TheNMIBaseControl {
                ParentFld = 1
            };
            CountBar.UpdateUXProperties(Guid.Empty);
            CountBar.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "click", (sener, para) => {
                TheThing.SetSafePropertyBool(MyBaseThing, "ClickState", !TheThing.GetSafePropertyBool(MyBaseThing, "ClickState"));
            });
        }
예제 #5
0
        public override bool Init()
        {
            if (!mIsInitStarted)
            {
                mIsInitStarted          = true;
                MyBaseThing.StatusLevel = 4;
                MyBaseThing.LastMessage = "Logger Service has started";

                MyBaseThing.RegisterEvent(eEngineEvents.IncomingMessage, HandleMessage);
                MyBaseEngine.RegisterEvent(eEngineEvents.ThingDeleted, OnThingDeleted);

                cdeP tP = null;
                if (TheBaseAssets.MyServiceHostInfo.DisableConsole)
                {
                    TheThing.SetSafePropertyBool(MyBaseThing, "DisableStandardLog", TheBaseAssets.MyServiceHostInfo.DisableConsole);
                }
                else
                {
                    tP = GetProperty("DisableStandardLog", true);
                }
                tP.RegisterEvent(eThingEvents.PropertyChanged, sinkDisableChanged);
                if (TheCommonUtils.CBool(tP.ToString()))
                {
                    TheBaseAssets.MyServiceHostInfo.DisableConsole = true;
                }

                if (TheBaseAssets.MyServiceHostInfo.UseGELFLoggingFormat)
                {
                    tP = TheThing.SetSafePropertyBool(MyBaseThing, "UseGELF", TheBaseAssets.MyServiceHostInfo.UseGELFLoggingFormat);
                }
                else
                {
                    tP = GetProperty("UseGELF", true);
                }
                tP.RegisterEvent(eThingEvents.PropertyChanged, sinkGELF);
                if (TheCommonUtils.CBool(tP.ToString()))
                {
                    TheBaseAssets.MyServiceHostInfo.UseGELFLoggingFormat = true;
                }

                bool DoLogKPIs = TheCommonUtils.CBool(TheBaseAssets.MySettings.GetSetting("LogKPIs"));
                if (DoLogKPIs)
                {
                    TheThing.SetSafePropertyBool(MyBaseThing, "LogKPIs", true);
                }

                TheQueuedSenderRegistry.RegisterHealthTimer(sinkTimer);
                // If not lengthy initialized you can remove cdeRunasync and call this synchronously
                TheCommonUtils.cdeRunAsync(MyBaseEngine.GetEngineName() + " Init Services", true, (o) =>
                {
                    // Perform any long-running initialization (i.e. network access, file access) here
                    InitServices();
                    MyBaseEngine.ProcessInitialized(); //Set the status of the Base Engine according to the status of the Things it manages
                    mIsInitCompleted = true;
                });
            }
            return(false);
        }
예제 #6
0
 public TheBitmapImage(TheThing tBaseThing, ICDEPlugin pPluginBase)
 {
     MyBaseThing            = tBaseThing ?? new TheThing();
     MyBaseEngine           = pPluginBase.GetBaseEngine();
     MyBaseThing.EngineName = MyBaseEngine.GetEngineName();
     MyBaseThing.SetIThingObject(this);
     MyBaseThing.DeviceType = eImageTypes.Bitmap;
     TheThing.SetSafePropertyBool(MyBaseThing, "IsCamera", true);
 }
예제 #7
0
 /// <summary>
 /// Connect to the Thing
 /// </summary>
 public void Connect()
 {
     if (MyIsolator == null)
     {
         return;
     }
     readBytesSec = new PerformanceCounter("Process", "IO Other Bytes/sec", MyIsolator.ProcessName);
     TheThing.SetSafePropertyBool(MyBaseThing, "IsConnected", true);
     TheQueuedSenderRegistry.RegisterHealthTimer(sinkTimer);
 }
예제 #8
0
        public override bool DoInit()
        {
            base.DoInit();
            IsActive = false;
            TheThing.SetSafePropertyBool(MyBaseThing, "IsStateSensor", true);
            MyBaseThing.StatusLevel = 4;
            if (string.IsNullOrEmpty(MyBaseThing.ID))
            {
                MyBaseThing.ID = Guid.NewGuid().ToString();

                TheThing.SetSafePropertyString(MyBaseThing, "StateSensorType", "analog");
                TheThing.SetSafePropertyString(MyBaseThing, "StateSensorUnit", "units");
                TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorMaxValue", 100);
                TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorAverage", 50);
                TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorMinValue", 0);
                TheThing.SetSafePropertyNumber(MyBaseThing, "Interval", 500);
            }
            TheThing.SetSafePropertyString(MyBaseThing, "StateSensorIcon", "/P066/Images/iconVThingsRest.png");
            GetProperty("FriendlyName", true).RegisterEvent(eThingEvents.PropertyChanged, sinkNameChanged);
            cdeP tRW = GetProperty("RawValue", true);

            tRW.RegisterEvent(eThingEvents.PropertyChanged, sinkPrePro);
            cdeP.SetSafePropertyBool(tRW, "IsStateSensor", true);
            cdeP.SetSafePropertyString(tRW, "StateSensorType", "analog");
            cdeP.SetSafePropertyString(tRW, "StateSensorUnit", "&#176;F");
            cdeP.SetSafePropertyNumber(tRW, "StateSensorMaxValue", 100);
            cdeP.SetSafePropertyNumber(tRW, "StateSensorAverage", 50);
            cdeP.SetSafePropertyNumber(tRW, "StateSensorMinValue", 0);

            if (!string.IsNullOrEmpty(TheThing.GetSafePropertyString(MyBaseThing, "RealSensorThing")) && !string.IsNullOrEmpty(TheThing.GetSafePropertyString(MyBaseThing, "RealSensorProperty")))
            {
                EngageMapper();
            }

            GetProperty("IsGlobal", true).RegisterEvent(eThingEvents.PropertyChanged, (p) =>
            {
                if (TheCommonUtils.CBool(p.ToString()))
                {
                    TheThingRegistry.RegisterThingGlobally(MyBaseThing);
                }
                else
                {
                    TheThingRegistry.UnregisterThingGlobally(MyBaseThing);
                }
            });
            GetProperty("Interval", true).RegisterEvent(eThingEvents.PropertyChanged, (p) =>
            {
                changeInterval(TheCommonUtils.CInt(p.ToString()));
            });
            MyBaseThing.SetPublishThrottle((int)TheThing.GetSafePropertyNumber(MyBaseThing, "Interval"));

            //TheQueuedSenderRegistry.RegisterHealthTimer(checkMapperHealth);
            return(true);
        }
예제 #9
0
        private void sinkPropChanged(cdeP pPara)
        {
            cdeP tProp = pPara as cdeP;

            if (tProp != null && tProp.Name == nameof(IsConnected))
            {
                if (_bIsConnected != TheCommonUtils.CBool(tProp.Value))
                {
                    TheThing.SetSafePropertyBool(MyBaseThing, nameof(IsConnected), _bIsConnected);
                }
            }
        }
예제 #10
0
        public virtual bool Init()
        {
            if (mIsInitCalled)
            {
                return(false);
            }
            mIsInitCalled = true;

            if (string.IsNullOrEmpty(MyBaseThing.ID))
            {
                MyBaseThing.ID = Guid.NewGuid().ToString();
            }
            MyBaseThing.Value = "0";
            TheThing.SetSafePropertyBool(MyBaseThing, "IsActive", true);

            mIsInitialized = true;
            return(true);
        }
예제 #11
0
        public override bool Init()
        {
            if (mIsInitCalled)
            {
                return(false);
            }
            mIsInitCalled = true;

            MyBaseThing.RegisterStatusChanged(sinkStatChanged);
            MyBaseThing.StatusLevel = 4;
            MyBaseThing.Value       = "0";
            MyBaseThing.RegisterEvent(eEngineEvents.IncomingMessage, HandleMessage);
            MyBaseEngine.RegisterEvent(eEngineEvents.ThingDeleted, OnThingDeleted);
            MyBaseEngine.RegisterEvent(eEngineEvents.ThingRegistered, OnThingRegisterd);

            if (!TheBaseAssets.MyServiceHostInfo.IsCloudService && !TheThing.GetSafePropertyBool(MyBaseThing, "RanBefore"))
            {
                TheThing.SetSafePropertyBool(MyBaseThing, "RanBefore", true);
                string tAutoPing = TheBaseAssets.MySettings.GetSetting("AutoPing");
                if (!string.IsNullOrEmpty(tAutoPing))
                {
                    TheThing tThing = new TheThing();
                    tThing.EngineName   = MyBaseEngine.GetEngineName();
                    tThing.DeviceType   = eNetworkServiceTypes.PingService;
                    tThing.Address      = tAutoPing;
                    tThing.FriendlyName = tAutoPing;
                    TheThing.SetSafePropertyBool(tThing, "AllowRTT", true);
                    TheThing.SetSafePropertyBool(tThing, "AutoConnect", true);
                    TheThingRegistry.RegisterThing(tThing);
                }
            }

            if (MyBaseEngine.GetEngineState().IsService)
            {
                TheCommonUtils.cdeRunAsync("Init Networkers", true, (o) =>
                {
                    InitNetworkServices();
                    mIsInitialized = true;
                    FireEvent(eThingEvents.Initialized, this, true, true);
                    MyBaseEngine.ProcessInitialized();
                });
            }
            return(false);
        }
예제 #12
0
        public virtual bool Init()
        {
            if (mIsInitCalled)
            {
                return(mIsInitCalled);
            }
            mIsInitCalled = true;

            if (string.IsNullOrEmpty(MyBaseThing.ID))
            {
                MyBaseThing.ID = Guid.NewGuid().ToString();
            }
            MyBaseThing.Value = "0";
            TheThing.SetSafePropertyBool(MyBaseThing, "IsActive", true);

            MyBaseThing.StatusLevel = 1;
            MyBaseThing.LastMessage = "MemoryTag Ready";
            mIsInitialized          = true;
            return(true);
        }
예제 #13
0
        /// <summary>
        /// Initializes the Live Tag
        /// </summary>
        /// <returns></returns>
        public override bool Init()
        {
            if (mIsInitCalled)
            {
                return(false);
            }
            mIsInitCalled = true;

            TheThing.SetSafePropertyBool(MyBaseThing, "IsLiveTag", true);
            MyBaseThing.FireEvent("OnInitialized", this, new TSM(MyBaseThing.cdeMID.ToString(), "Was Init"), false);
            cdeP tThrot = GetProperty("Throttle", true);

            tThrot.RegisterEvent(eThingEvents.PropertyChanged, sinkThrottleChanged);
            mIsInitialized = DoInit();
            if (string.IsNullOrEmpty(MyBaseThing.ID))
            {
                MyBaseThing.ID = Guid.NewGuid().ToString();
            }
            return(mIsInitialized);
        }
예제 #14
0
        /// <summary>
        /// The possible types of WeMo devices that can be detected
        /// </summary>
        #endregion

        public bool Init()
        {
            if (mIsInitCalled)
            {
                return(false);
            }
            mIsInitCalled          = true;
            MyBaseThing.EngineName = eEngineName.NMIService;
            MyBaseThing.DeviceType = "NMI Editor";
            TheThing.SetSafePropertyBool(MyBaseThing, "IsLiveTag", true);
            MyBaseThing.FireEvent("OnInitialized", this, new TSM(MyBaseThing.cdeMID.ToString(), "Was Init"), false);
            cdeP tThrot = GetProperty("Throttle", true);

            tThrot.RegisterEvent(eThingEvents.PropertyChanged, sinkThrottleChanged);
            mIsInitialized = DoInit();    //we have to follow your design to have mIsINitialzed called at the end. This can lead to problems for live tags
            if (string.IsNullOrEmpty(MyBaseThing.ID))
            {
                MyBaseThing.ID = Guid.NewGuid().ToString();
            }
            return(mIsInitialized);
        }
예제 #15
0
        public bool Init()
        {
            if (mIsInitCalled)
            {
                return(false);
            }

            mIsInitCalled           = true;
            MyBaseThing.StatusLevel = 1;

            MyBaseThing.Version      = TheBaseAssets.MyAppInfo.CurrentVersion.ToString(CultureInfo.InvariantCulture);
            MyBaseThing.Capabilities = TheBaseAssets.MyAppInfo.Capabilities;
            MyBaseThing.Address      = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false);
            TheThing.SetSafePropertyString(MyBaseThing, "Description", TheBaseAssets.MyAppInfo.LongDescription);
            mIsInitialized = true;

            TheThing.SetSafePropertyBool(MyBaseThing, "EnableKPIs", TheCommonUtils.CBool(TheBaseAssets.MySettings.GetSetting("EnableKPIs")));

            if (TheBaseAssets.MyServiceHostInfo.EnableTaskKPIs)
            {
                var taskKpiThread = new System.Threading.Thread(() =>
                {
                    TheSystemMessageLog.ToCo($"Tasks {DateTime.Now}: NodeHost starting Task KPI thread");
                    do
                    {
                        Thread.Sleep(1000); // Keeping it simple here, to minimize interference on task scheduler/thread scheduler etc. (Assumption: not used on production systems) // TheCommonUtils.SleepOneEye(1000, 1000);
                        var kpis = TheCommonUtils.GetTaskKpis(null);
                        TheSystemMessageLog.ToCo($"Tasks {DateTime.Now}: {TheCommonUtils.SerializeObjectToJSONString(kpis)}");
                    } while (TheBaseAssets.MasterSwitch && TheBaseAssets.MyServiceHostInfo.EnableTaskKPIs);
                    TheSystemMessageLog.ToCo($"Tasks {DateTime.Now}: NodeHost ending Task KPI thread");
                });
                taskKpiThread.Start();
            }
            KPIHarvestInterval = TheCommonUtils.CInt(TheBaseAssets.MySettings.GetAppSetting("KPIHarvestIntervalInSeconds", "5", false, true));
            if (KPIHarvestInterval > 0)
            {
                TheQueuedSenderRegistry.RegisterHealthTimer(sinkCyclic);
            }
            return(true);
        }
예제 #16
0
        public override bool DoInit()
        {
            MyBaseThing.StatusLevel = 0;
            MyBaseThing.LastMessage = "Timer Ready";
            IsActive = false;

            if (string.IsNullOrEmpty(MyBaseThing.ID))
            {
                MyBaseThing.ID = Guid.NewGuid().ToString();
                TheThing.SetSafePropertyBool(MyBaseThing, "IsStateSensor", true);
                TheThing.SetSafePropertyString(MyBaseThing, "StateSensorType", "analog");
                TheThing.SetSafePropertyString(MyBaseThing, "StateSensorUnit", "ticks");
                TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorMaxValue", 60000);
                TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorAverage", 1000);
                TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorMinValue", 0);
            }
            if (TheThing.GetSafePropertyBool(MyBaseThing, "AutoStart"))
            {
                sinkTriggered(null);
            }
            return(true);
        }
예제 #17
0
        public override bool DoInit()
        {
            if (Frequency < 100)
            {
                Frequency = 100;
            }

            GetProperty(nameof(StartValue), true).RegisterEvent(eThingEvents.PropertyChanged, sinkTriggered);
            GetProperty(nameof(StartValue), true).RegisterEvent(eThingEvents.PropertyChanged, sinkStartValueChanged);
            GetProperty("Value", true).RegisterEvent(eThingEvents.PropertyChanged, sinkValueReset);

            this.MyBaseThing.DeclareSensorProperty("Value", ePropertyTypes.TNumber, new cdeP.TheSensorMeta {
                RangeMax = 100, RangeMin = 0, Units = "ticks",
            });

            if (!TheThing.GetSafePropertyBool(MyBaseThing, "IsStateSensor"))
            {
                TheThing.SetSafePropertyBool(MyBaseThing, "IsStateSensor", true);
                TheThing.SetSafePropertyString(MyBaseThing, "StateSensorType", "analog");
                TheThing.SetSafePropertyString(MyBaseThing, "StateSensorUnit", "ticks");
                TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorMaxValue", 100);
                TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorAverage", 50);
                TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorMinValue", 0);
            }
            if (!IsActive)
            {
                IsActive = false;
                MyBaseThing.StatusLevel = 0;
                MyBaseThing.LastMessage = "Countdown ready";
                if (AutoStart && mTimer == null)
                {
                    sinkTriggered(this.GetProperty("Value", false));
                }
            }
            return(true);
        }
예제 #18
0
        public virtual bool MonitorTag(Subscription subscription, out string error, bool bApplySubscription = true, bool bReadInitialValue = true)
        {
            error = null;
            if (subscription == null || subscription.Session == null)
            {
                error = "Error: No OPC session.";
                return(false);
            }

            lock (subscription.MonitoredItems)
            {
                if (MyMonitoredItem != null && !subscription.MonitoredItems.Contains(MyMonitoredItem))
                {
                    // Monitored item was removed: recreate from scratch. Otherwise modify in place
                    MyMonitoredItem = null;
                }


                if (!this.IsSubscribedAsThing && !this.IsSubscribedAsProperty)
                {
                    // Nothing to be monitored
                    error = "Error: Nothing to be monitored";
                    return(false);
                }

                if (TheThing.GetSafePropertyBool(MyBaseThing, "DontMonitor") || SampleRate < -1)
                {
                    return(false);
                }
                // can only subscribe to local variables.
                //if (TagRef == null || TagRef.NodeId.IsAbsolute || TagRef.NodeClass != NodeClass.Variable)
                var resolvedNodeId = GetResolvedNodeIdName();
                if (resolvedNodeId == null) // || NodeId.IsAbsolute || TagRef.NodeClass != NodeClass.Variable)
                {
                    error = "Error: No or invalid NodeId";
                    return(false);
                }


                var previousMonitoredItem = subscription.MonitoredItems.FirstOrDefault(mi => mi.Handle == this || this.RefersToSamePropertyAndTag(mi.Handle));
                if (previousMonitoredItem != null)
                {
                    if (!previousMonitoredItem.StartNodeId.Equals(resolvedNodeId))
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(78201, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("OPC", $"[{MyOPCServer.GetLogAddress()}] Internal Error - monitored item {previousMonitoredItem.StartNodeId} replaced with {resolvedNodeId}. Change will not take effect!", eMsgLevel.l4_Message));
                    }
                    MyMonitoredItem = previousMonitoredItem;
                }
                else
                {
                    MyMonitoredItem = new MonitoredItem(subscription.DefaultItem);
                }
                //MyMonitoredItem.StartNodeId = (NodeId)TagRef.NodeId;
                MyMonitoredItem.StartNodeId    = resolvedNodeId;
                MyMonitoredItem.AttributeId    = Attributes.Value;
                MyMonitoredItem.DisplayName    = DisplayName; // Utils.Format("{0}", TagRef);
                MyMonitoredItem.MonitoringMode = MonitoringMode.Reporting;
                if ((!this.HistoryStartTime.HasValue || this.HistoryStartTime.Value == DateTimeOffset.MinValue) && MyOPCServer.DefHistoryStartTime != DateTimeOffset.MinValue)
                {
                    this.HistoryStartTime = MyOPCServer.DefHistoryStartTime;
                }

                if (this.HistoryStartTime.HasValue && this.HistoryStartTime.Value != DateTimeOffset.MinValue)
                {
                    MyMonitoredItem.Filter = new AggregateFilter()
                    {
                        StartTime          = this.HistoryStartTime.Value.UtcDateTime,
                        ProcessingInterval = this.SampleRate,
                        AggregateType      = ObjectIds.AggregateFunction_Interpolative,
                    };
                    MyMonitoredItem.QueueSize        = uint.MaxValue;
                    MyMonitoredItem.SamplingInterval = 0;
                }
                else
                {
                    DataChangeFilter filter = null;
                    // TODO Remove this special case: pass parameters for deadband filters and StatusValueTimestamp (this breaks P08!!!)
                    if (this.DeadbandFilterValue != 0)
                    {
                        filter = new DataChangeFilter
                        {
                            DeadbandType  = (uint)(this.DeadbandFilterValue > 0 ? DeadbandType.Absolute : DeadbandType.Percent),
                            DeadbandValue = Math.Abs(this.DeadbandFilterValue)
                        };
                    }

                    if (ChangeTrigger != 1)
                    {
                        if (filter == null)
                        {
                            filter = new DataChangeFilter();
                        }
                        filter.Trigger = (DataChangeTrigger)ChangeTrigger;
                    }

                    if (filter != null)
                    {
                        MyMonitoredItem.Filter = filter;
                    }
                    MyMonitoredItem.SamplingInterval = SampleRate;

                    // For Events, the sample rate should be 0 (per spec), but is really ignored and thus should not affect the aggregate sample rate for the server
                    // All other sample rates are at least 50ms per other checks

                    if (SampleRate <= subscription.PublishingInterval * 2 && SampleRate > 0)
                    {
                        // 3.220: PublishingInterval is now independent of the sample rate: it only affects the frequency of the traffic from the server, not the content
                        //MyOPCServer.Subscription.PublishingInterval = SampleRate;

                        // Request the QueueSize to be 50 times the expected data points, so that no data is lost in normal operation
                        MyMonitoredItem.QueueSize = (uint)Math.Ceiling((((double)subscription.PublishingInterval) / SampleRate) * 50);
                        if (MyMonitoredItem.QueueSize < 50)
                        {
                            MyMonitoredItem.QueueSize = 50;
                        }
                    }
                    else
                    {
                        MyMonitoredItem.QueueSize = 50; // Request at least 50
                    }
                }
                MyMonitoredItem.DiscardOldest = true;

                MyMonitoredItem.Notification -= MonitoredItem_Notification;
                MyMonitoredItem.Notification += MonitoredItem_Notification;

                TheOPCMonitoredItemBase previousTag = null;
                if (previousMonitoredItem != null && previousMonitoredItem.Handle != this)
                {
                    previousTag = previousMonitoredItem.Handle as TheOPCMonitoredItemBase;
                    if (previousTag != null)
                    {
                        previousTag.ReleaseMonitoredItem();
                    }
                }

                MyMonitoredItem.Handle = this;

                InitializeMonitoredItem(previousTag);

                if (previousMonitoredItem == null)
                {
                    subscription.AddItem(MyMonitoredItem);
                }
            }
            if (bApplySubscription)
            {
#if OLD_UA
                var items = subscription.ApplyChanges();
                if (!items.Contains(MyMonitoredItem))
#else
                subscription.ApplyChanges();
                if (!subscription.MonitoredItems.Contains(MyMonitoredItem))
#endif
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(78201, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("OPC", $"[{MyOPCServer.GetLogAddress()}] Internal Error: Monitored item not found after applying changes {GetNodeIdForLogs()}. Actual values: Sampling {MyMonitoredItem.Status.SamplingInterval}, Queue {MyMonitoredItem.Status.QueueSize}", eMsgLevel.l1_Error));
                    error = "Error: Monitored item not found after applying changes";
                    return(false);
                }
                else
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(78201, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("OPC", $"[{MyOPCServer.GetLogAddress()}] Added monitored item {GetNodeIdForLogs()}. Actual values: Sampling {MyMonitoredItem.Status.SamplingInterval}, Queue {MyMonitoredItem.Status.QueueSize}", eMsgLevel.l4_Message));
                }
            }

            if (ServiceResult.IsBad(MyMonitoredItem.Status.Error))
            {
                TheThing.SetSafePropertyString(MyBaseThing, "LastMessage", MyMonitoredItem.Status.Error.StatusCode.ToString());
                TheBaseAssets.MySYSLOG.WriteToLog(78201, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("OPC", $"[{MyOPCServer.GetLogAddress()}] Error adding monitored item {GetNodeIdForLogs()}", eMsgLevel.l4_Message, MyMonitoredItem.Status.Error.ToString()));
                error = "Error: " + MyMonitoredItem.Status.Error.ToString();
                return(false);
            }
            else
            {
                MyOPCServer.RegisterEvent("DisconnectComplete", sinkDisconnected);
            }

            TheThing.SetSafePropertyBool(MyBaseThing, "IsActive", true);
            return(true);
        }
예제 #19
0
        internal static TheScreenInfo GenerateLiveScreen(Guid pScreenId, TheClientInfo tClientInfo) // Guid pUserGuid, int lcid, int pFlag)
        {
            if (TheCDEngines.MyNMIService == null)
            {
                return(null);
            }

            TheScreenInfo tInfo = new TheScreenInfo
            {
                cdeMID          = pScreenId,
                MyDashboard     = null,
                MyStorageInfo   = new List <TheFormInfo>(),
                MyStorageMeta   = new cdeConcurrentDictionary <string, TheFormInfo>(),
                MyStorageMirror = new List <object>(),
                MyDashPanels    = new List <TheDashPanelInfo>()
            };

            TheThing tLiveForm = TheThingRegistry.GetThingByMID("*", pScreenId);

            if (tLiveForm == null || !TheUserManager.HasUserAccess(tClientInfo.UserID, tLiveForm.cdeA))
            {
                return(null); //V3.1: BUG 126 - could lead to racing condition. TODO: Revisit later
                //TheFormInfo tI = new TheFormInfo(tLiveForm) { FormTitle = (tLiveForm == null ? "Form not Found!" : "Access Denied!") };
                //tI.TargetElement = pScreenId.ToString();
                //tI.AssociatedClassName = pScreenId.ToString();
                //tInfo.MyStorageInfo.Add(tI);
                //tI.FormFields = new List<TheFieldInfo>();
                //TheFieldInfo tFldInfo = new TheFieldInfo(null, null, 10, 0, 0);
                //tFldInfo.Type = eFieldType.SmartLabel;
                //tFldInfo.Header = (tLiveForm == null ? "This Form was defined but has not Meta-Data associated with it." : "You do not have the required access permissions!");
                //tI.FormFields.Add(tFldInfo);
                //return tInfo;
            }
            string          tFormName = TheThing.GetSafePropertyString(tLiveForm, "FriendlyName");
            List <TheThing> tFields   = TheThingRegistry.GetThingsByFunc("*", s => s.cdeO == TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID && TheThing.GetSafePropertyString(s, "FormName") == tFormName && TheThing.GetSafePropertyBool(s, "IsLiveTag") && (s.UID == Guid.Empty || s.UID == tClientInfo.UserID));

            if (tFields != null && tFields.Any())
            {
                string tFormTitle = TheThing.GetSafePropertyString(tLiveForm, "FormTitle");
                if (string.IsNullOrEmpty(tFormTitle))
                {
                    tFormTitle = tFormName;
                }
                TheFormInfo tI = new TheFormInfo(tLiveForm)
                {
                    FormTitle           = tFormTitle,
                    TargetElement       = pScreenId.ToString(),
                    DefaultView         = eDefaultView.Form,
                    TileWidth           = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(tLiveForm, "TileWidth")),
                    TileHeight          = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(tLiveForm, "TileHeight")),
                    IsUsingAbsolute     = TheThing.GetSafePropertyBool(tLiveForm, "IsAbsolute"),
                    AssociatedClassName = pScreenId.ToString()
                };
                tInfo.MyStorageInfo.Add(tI);
                tI.FormFields = new List <TheFieldInfo>();
                int fldNo = 10;
                foreach (TheThing tTh in tFields)
                {
                    int tfldNo = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(tTh, "FldOrder"));
                    if (tfldNo == 0)
                    {
                        tfldNo = fldNo;
                    }
                    int          tFlags   = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(tTh, "Flags"));
                    cdeP         ValProp  = tTh.GetProperty("Value");
                    bool         IsNewFld = true;
                    TheFieldInfo tFldInfo = TheNMIEngine.GetFieldById(TheThing.GetSafePropertyGuid(tTh, "FldID"));
                    if (tFldInfo == null)
                    {
                        tFldInfo = new TheFieldInfo(tTh, "Value", tfldNo, tFlags & 0xFFBF, tTh.GetBaseThing().cdeA);
                    }
                    else
                    {
                        tFldInfo.FldOrder = tfldNo;
                        tFldInfo.Flags    = tFlags;
                        IsNewFld          = false;
                    }
                    if (tFldInfo.PropertyBag == null)
                    {
                        tFldInfo.PropertyBag = new ThePropertyBag();
                    }
                    ThePropertyBag.PropBagUpdateValue(tFldInfo.PropertyBag, "IsOnTheFly", "=", "True");
                    ThePropertyBag.PropBagUpdateValue(tFldInfo.PropertyBag, "UXID", "=", $"{tTh.cdeMID}");
                    tFldInfo.Header = tTh.FriendlyName;
                    RegisterNMISubscription(tClientInfo, "Value", tFldInfo);

                    string tControlType = TheThing.GetSafePropertyString(tTh, "ControlType");
                    if (TheCommonUtils.CInt(tControlType) == 0 && !TheCommonUtils.IsNullOrWhiteSpace(tControlType))
                    {
                        tFldInfo.Type = eFieldType.UserControl;
                        RegisterFieldEvents(tTh, ValProp, IsNewFld, tFldInfo, tControlType);
                    }
                    else
                    {
                        tFldInfo.Type = (eFieldType)TheCommonUtils.CInt(tControlType);
                    }
                    tFldInfo.DefaultValue = ValProp?.ToString();
                    tFldInfo.TileWidth    = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(tTh, "TileWidth"));
                    tFldInfo.TileHeight   = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(tTh, "TileHeight"));

                    foreach (cdeP prop in tTh.GetNMIProperties())
                    {
                        ThePropertyBag.PropBagUpdateValue(tFldInfo.PropertyBag, prop.Name, "=", prop.ToString());
                    }
                    if (tFldInfo.Type == eFieldType.TileButton)
                    {
                        tTh.DeclareNMIProperty("IsDown", ePropertyTypes.TBoolean);
                        ThePropertyBag.PropBagUpdateValue(tFldInfo.PropertyBag, "EnableTap", "=", "True");
                        tFldInfo.RegisterUXEvent(tTh, eUXEvents.OnPropertyChanged, "IsDown", (pThing, pObj) =>
                        {
                            if (!(pObj is TheProcessMessage pMsg) || pMsg.Message == null)
                            {
                                return;
                            }
                            TheThing.SetSafePropertyBool(pThing, "IsDown", TheCommonUtils.CBool(pMsg.Message.PLS));
                        });
예제 #20
0
        public override bool CreateUX()
        {
            if (mIsUXInitCalled)
            {
                return(false);
            }
            mIsUXInitCalled = true;
            if (!MyBaseEngine.GetEngineState().IsService)
            {
                return(true);
            }
            //NUI Definition for All clients
            // File Service Main Tile
            mMyDashboard = TheNMIEngine.AddDashboard(MyBaseThing, new TheDashboardInfo(MyBaseEngine, "0")
            {
                OnChangeName = "Value",
                PropertyBag  =
                    new nmiDashboard()
                {
                    Category = "Devices", Format = "Network Status<br>Issues: {0}", LabelFormat = "Current Issues: {0}", Thumbnail = "FA5:f6ff", ClassName = "cdeLiveTile cdeLiveTileBar", SideBarTitle = "Network Services"
                }
            });
            mMyDashboard.RegisterOnLoad((pDash) =>
            {
                if (RootDashPanel == null)
                {
                    RootDashPanel = pDash;
                    sinkStatChanged(null);
                    ThePropertyBag.PropBagUpdateValue(pDash.PropertyBag, "Foreground", "=", "white");    // "background-image:url('GlasButton.png');color:white;background-color:gray");
                    ThePropertyBag.PropBagUpdateValue(pDash.PropertyBag, "sStyle", "=", "color:white;"); // "background-image:url('GlasButton.png');color:white;background-color:gray");
                    ScanAllServices();
                }
            });
            // File Service Form: single instance for multi-agents
            TheFormInfo tAllFileServers = TheNMIEngine.AddForm(new TheFormInfo(MyBaseEngine)
            {
                cdeMID = TheThing.GetSafeThingGuid(MyBaseThing, "NETS"), FormTitle = "All Network Services", AddButtonText = "Add a Service"
            });

            TheNMIEngine.AddFormToThingUX(MyBaseThing, tAllFileServers, "CMyTable", "<i class='fa faIcon fa-5x'>&#xf0ce;</i></br>Network Services", 1, 1, 0x0, TheNMIEngine.GetNodeForCategory(), null, new nmiDashboardTile()
            {
            });

            TheNMIEngine.AddCommonTableColumns(MyBaseThing, tAllFileServers, new eNetworkServiceTypes(), eNetworkServiceTypes.PingService);
            TheNMIEngine.AddSmartControl(MyBaseThing, tAllFileServers, eFieldType.Number, 21, 64, 0, "RTT", "Value", new nmiCtrlNumber {
                TileWidth = 1
            });



            //Easy To add Wizard
            var tFlds = TheNMIEngine.AddNewWizard(MyBaseThing, tAllFileServers.cdeMID, "Add new Network Service", null, (item, client) =>
            {
                if (item != null)
                {
                    TheThing t = item as TheThing;
                    TheThing.SetSafePropertyBool(t, "AutoConnect", true);
                    TheThing.SetSafePropertyBool(t, "AllowRTT", true);
                }
            });
            TheFormInfo tF = tFlds["Form"] as TheFormInfo;

            tAllFileServers.AddTemplateType = tF.cdeMID.ToString();
            TheNMIEngine.AddNewWizardPage(MyBaseThing, tF, 0, 1, 0, "Add new Service");
            TheNMIEngine.AddWizardControl(MyBaseThing, tF, eFieldType.SingleEnded, 1, 1, 2, 0, "Name your Service", "FriendlyName");
            TheNMIEngine.AddWizardControl(MyBaseThing, tF, eFieldType.ComboBox, 1, 2, 2, 0, "Service Type", "DeviceType", new nmiCtrlComboBox {
                Options = new eNetworkServiceTypes(), DefaultValue = eNetworkServiceTypes.PingService
            });
            TheNMIEngine.AddWizardControl(MyBaseThing, tF, eFieldType.SingleEnded, 1, 3, 2, 0, "Address", "Address");
            TheNMIEngine.AddWizardControl(MyBaseThing, tF, eFieldType.SmartLabel, 1, 4, 0, 0, null, null, new nmiCtrlSmartLabel {
                NoTE = true, FontSize = 32, Text = "Once you click finish the service will be created and started."
            });


            TheNMIEngine.AddAboutButton(MyBaseThing, true, "REFRESH_DASH", 0xc0);
            mIsUXInitialized = true;
            return(true);
        }
예제 #21
0
        static protected TheThing StartOPCServer(bool disableSecurity)
        {
#if OPCUASERVER
            // TODO Actually use our own OPC Server for the unit test
            var opcServerThing = TheThingRegistry.GetThingsOfEngine("CDMyOPCUAServer.cdeMyOPCServerService").FirstOrDefault();
            Assert.IsNotNull(opcServerThing, $"Unable to obtain OPC Server thing: error loading plug-in or server not yet initialized?");

            lock (opcServerStartupLock)
            {
                if (!TheThing.GetSafePropertyBool(opcServerThing, "IsRunning"))
                {
                    TheThing.SetSafePropertyBool(opcServerThing, "DisableSecurity", disableSecurity);
                    TheThing.SetSafePropertyBool(opcServerThing, "NoServerCertificate", disableSecurity);

                    var theOpcThing = new TheThing();
                    theOpcThing.EngineName = "OPCTestEng";
                    theOpcThing.DeviceType = "OPCTestDT";
                    theOpcThing.Address    = "OPCTestAddress";
                    theOpcThing.SetProperty("OpcProp01", "0001");
                    theOpcThing.SetProperty("OpcProp02", "0002");
                    theOpcThing.SetProperty("OpcProp03", "0003");
                    theOpcThing.SetProperty("OpcProp04", "0004");
                    theOpcThing.SetProperty("OpcProp05", "0005");
                    theOpcThing.SetProperty("OpcProp06", "0006");
                    theOpcThing.SetProperty("OpcProp07", "0007");
                    theOpcThing.SetProperty("OpcProp08", "0008");
                    theOpcThing.SetProperty("OpcProp09", "0009");
                    theOpcThing.SetProperty("OpcProp10", "0010");
                    var tThing = TheThingRegistry.RegisterThing(theOpcThing);
                    Assert.IsNotNull(tThing);

                    var addThingResponse = TheCommRequestResponse.PublishRequestJSonAsync <MsgAddThingsToServer, MsgAddThingsToServerResponse>(myContentService, opcServerThing, new MsgAddThingsToServer
                                                                                                                                               (
                                                                                                                                                   new TheThingToAddToServer
                    {
                        cdeMID = Guid.NewGuid(),
                        ReplaceExistingThing = false,
                        ThingMID             = TheCommonUtils.cdeGuidToString(theOpcThing.cdeMID),
                    }
                                                                                                                                               ), new TimeSpan(0, 0, 30)).Result;

                    Assert.IsNotNull(addThingResponse, "No reply to OPC Server MsgAddThingToServer");
                    Assert.IsTrue(string.IsNullOrEmpty(addThingResponse.Error), $"Error adding thing to OPC Server: '{addThingResponse.Error}'.");
                    Assert.AreEqual(1, addThingResponse.ThingStatus.Count, $"Error adding thing to OPC Server.");
                    Assert.IsTrue(string.IsNullOrEmpty(addThingResponse.ThingStatus[0].Error), $"Error adding thing to OPC Server: '{addThingResponse.ThingStatus[0].Error}'.");

                    MsgStartStopServerResponse responseStart;
                    int retryCount = 1;
                    do
                    {
                        responseStart = TheCommRequestResponse.PublishRequestJSonAsync <MsgStartStopServer, MsgStartStopServerResponse>(myContentService, opcServerThing,
                                                                                                                                        new MsgStartStopServer
                        {
                            Restart = true,
                        },
                                                                                                                                        new TimeSpan(0, 0, 30)).Result;
                        retryCount--;
                    } while (retryCount >= 0 && responseStart == null);

                    Assert.IsNotNull(responseStart, "Failed to send MsgStartStopServer message to restart OPC UA Server");
                    Assert.IsTrue(string.IsNullOrEmpty(responseStart.Error), $"Error restarting OPC Server: '{addThingResponse.Error}'.");
                    Assert.IsTrue(responseStart.Running, $"OPC Server not running after MsgStartStopServer Restart message");
                }
            }
            return(opcServerThing);
#else
            return(null);
#endif
        }
예제 #22
0
 protected void sinkDisconnected(ICDEThing pThing, object p)
 {
     Reset();
     TheThing.SetSafePropertyBool(MyBaseThing, "IsActive", false);
 }
예제 #23
0
 public void Disconnect()
 {
     TheQueuedSenderRegistry.UnregisterHealthTimer(sinkTimer);
     TheThing.SetSafePropertyBool(MyBaseThing, "IsConnected", false);
 }