示例#1
0
        void InitServers()
        {
            List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(MyBaseThing.EngineName); // TheThingRegistry.GetThingsByProperty("*", Guid.Empty, "DeviceType", eOPCDeviceTypes.OPCServer);

            if (tDevList.Count > 0)
            {
                foreach (TheThing tDev in tDevList)
                {
                    switch (tDev.DeviceType)
                    {
                    case eMessageTypes.EMAIL:
                        TheEmailMessage tS = null;
                        if (!tDev.HasLiveObject)
                        {
                            tS = new TheEmailMessage(tDev, this);
                            TheThingRegistry.RegisterThing(tS);
                        }
                        break;

                    case eMessageTypes.SMS:
                        TheSMSMessage tSMS = null;
                        if (!tDev.HasLiveObject)
                        {
                            tSMS = new TheSMSMessage(tDev, this);
                            TheThingRegistry.RegisterThing(tSMS);
                        }
                        break;
                    }
                }
            }
            MyBaseEngine.SetStatusLevel(-1);
        }
示例#2
0
        T CreateOrUpdateService <T>(TheThing tDevice, bool bRegisterThing) where T : TheLoggerBase
        {
            T tServer;

            if (tDevice == null || !tDevice.HasLiveObject)
            {
                tServer = (T)Activator.CreateInstance(typeof(T), tDevice, this);
                if (bRegisterThing)
                {
                    TheThingRegistry.RegisterThing((ICDEThing)tServer);
                }
            }
            else
            {
                tServer = tDevice.GetObject() as T;
                if (tServer != null)
                {
                    tServer.Connect(null);    //Expose a Connect(TheProcessMessage) method on TheThing
                }
                else
                {
                    tServer = (T)Activator.CreateInstance(typeof(T), tDevice, this);
                }
            }
            return(tServer);
        }
        public void StartPropertyUpdateLoop()
        {
            testThing = new TheThing()
            {
                FriendlyName = "MyTestSensor"
            };
            TheThingRegistry.RegisterThing(testThing);
            Random rand = new Random(); // Used for generating "fake" sensor values

            cdeP[] props = new cdeP[propertyCount];

            // Run the loop on another thread
            TheCommonUtils.cdeRunAsync("PropertyUpdateLoop", true, (o) =>
            {
                while (TheBaseAssets.MasterSwitch)
                {
                    // Set the properties and log
                    props[0] = testThing.SetProperty(properties[0], rand.Next(25, 51));
                    props[1] = testThing.SetProperty(properties[1], rand.NextDouble());
                    props[2] = testThing.SetProperty(properties[2], rand.Next(10000, 50000));
                    LogChanges(false, props);

                    // Wait timeout of 1 second between property updates
                    TheCommonUtils.SleepOneEye(1000, 500);
                }
            });
        }
示例#4
0
        void  InitServers()
        {
            List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(MyBaseThing.EngineName); // TheThingRegistry.GetThingsByProperty("*", Guid.Empty, "DeviceType", eOPCDeviceTypes.OPCServer);

            if (tDevList.Count > 0)
            {
                foreach (TheThing tDev in tDevList)
                {
                    if (!tDev.HasLiveObject)
                    {
                        switch (tDev.DeviceType)
                        {
                        case eOPCDeviceTypes.OPCRemoteServer:
                            TheOPCUARemoteServer tS = new TheOPCUARemoteServer(tDev, this, null);
                            TheThingRegistry.RegisterThing(tS);
                            break;

                        case eOPCDeviceTypes.OPCLiveTag:
                            TheOPCUATagThing tag = new TheOPCUATagThing(tDev, null);
                            TheThingRegistry.RegisterThing(tag);
                            break;

                        case eOPCDeviceTypes.OPCMethod:
                            TheOPCUAMethodThing tMeth = new TheOPCUAMethodThing(tDev, MyBaseEngine.GetEngineName());
                            TheThingRegistry.RegisterThing(tMeth);
                            break;
                        }
                    }
                }
            }
            MyBaseEngine.SetStatusLevel(-1);
        }
        void sinkRegisterIsos()
        {
            var tEngs = TheThingRegistry.GetBaseEnginesAsThing(false, true);

            foreach (var t in tEngs)
            {
                if (TheThing.GetSafePropertyBool(t, "IsIsolated"))
                {
                    IBaseEngine tBase = TheThingRegistry.GetBaseEngine(t, true);
                    if (tBase != null && tBase.GetISOLater() != null)
                    {
                        TheThing tT   = TheThingRegistry.GetThingByFunc(MyBaseEngine.GetEngineName(), s => s.DeviceType == TheISOlaterKPIs.eDeviceType && TheThing.GetSafePropertyString(s, "ISOLaterName") == t.EngineName);
                        var      tKPI = new TheISOlaterKPIs(tT, this, t.EngineName);
                        TheThingRegistry.RegisterThing(tKPI);
                    }
                }
            }
            List <TheThing> tDevList = TheThingRegistry.GetThingsByProperty(MyBaseEngine.GetEngineName(), Guid.Empty, "DeviceType", TheKPIReport.eDeviceType);

            if (tDevList.Count > 0)
            {
                foreach (TheThing tDev in tDevList)
                {
                    if (tDev.GetObject() == null)
                    {
                        TheKPIReport cs = new TheKPIReport(tDev, this);
                        TheThingRegistry.RegisterThing(cs);
                    }
                }
            }
        }
示例#6
0
        string LoadXMLDefinition(string pFile)
        {
            string path = TheCommonUtils.cdeFixupFileName(pFile);

            TheBaseAssets.MySYSLOG.WriteToLog(500, new TSM(MyBaseEngine.GetEngineName(), $"Trying to open Modbus configuration file: {pFile}"));

            ModbusConfiguration config = null;

            try
            {
                config = ModbusConfiguration.ReadFromFile(path);
            }
            catch (IOException)
            {
                return("File not found or parsing failed");
            }

            List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(MyBaseThing.EngineName);

            foreach (var dd in config.Devices)
            {
                var tDev = tDevList.Find((t) => t.FriendlyName == dd.Name);
                if (tDev == null || !tDev.HasLiveObject)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(500, new TSM(MyBaseEngine.GetEngineName(), $"Adding Modbus Device {dd.Name}"));
                    var pm = new ModbusTCPDevice(tDev, this, dd);
                    TheThingRegistry.RegisterThing(pm);
                }
            }

            return("XML Definition loaded correctly.");
        }
示例#7
0
        void InitServers()
        {
            List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(this.MyBaseEngine.GetEngineName());

            if (tDevList.Count > 0)
            {
                foreach (TheThing tDev in tDevList)
                {
                    try
                    {
                        if (!tDev.HasLiveObject)
                        {
                            switch (tDev.DeviceType)
                            {
                            case PrometheusDeviceTypes.PrometheusExporter:
                                var tPS = new ThePrometheusExporter(tDev, this);
                                TheThingRegistry.RegisterThing(tPS);
                                break;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(181001, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, $"Error creating exporter instance {tDev?.cdeMID} / {tDev?.FriendlyName}", eMsgLevel.l1_Error, e.ToString()));
                    }
                }
            }

            MyBaseEngine.SetStatusLevel(-1);
        }
示例#8
0
        T CreateOrUpdateService <T>(TheThing tDevice, bool bRegisterThing) where T : TheNetworkServiceBase
        {
            T tServer;

            if (tDevice == null || !tDevice.HasLiveObject)
            {
                tServer = (T)Activator.CreateInstance(typeof(T), tDevice, this);
                if (bRegisterThing)
                {
                    TheThingRegistry.RegisterThing(tServer);
                    tServer.GetBaseThing().RegisterOnChange("DeviceType", OnServerDeviceTypeChanged);
                }
            }
            else
            {
                tServer = tDevice.GetObject() as T;
                if (tServer != null)
                {
                    //tServer.InitServer(null);
                }
                else
                {
                    tServer = (T)Activator.CreateInstance(typeof(T), tDevice, this);
                }
            }
            return(tServer);
        }
示例#9
0
        private void InitServices()
        {
            if (TheBaseAssets.MyServiceHostInfo.IsCloudService)
            {
                return;
            }
            List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(MyBaseEngine.GetEngineName());

            if (tDevList.Count > 0)
            {
                foreach (TheThing tDev in tDevList)
                {
                    switch (tDev.DeviceType)
                    {
                    case eWebAppTypes.TheWebApp:
                        TheRelayAppInfo tApp = new TheRelayAppInfo(tDev, null, this);
                        if (string.IsNullOrEmpty(tApp.HomePage))
                        {
                            tApp.HomePage = "/";
                        }
                        if (!tApp.HomePage.StartsWith("/"))
                        {
                            tApp.HomePage = "/" + tApp.HomePage;
                        }
                        tApp.SSID = TheScopeManager.GetScrambledScopeID();
                        TheThingRegistry.RegisterThing(tApp);
                        break;
                    }
                }
            }
        }
示例#10
0
        public bool RegisterRule(TheThingRule pRule)
        {
            if (pRule == null || TheBaseAssets.MyServiceHostInfo.IsCloudService)
            {
                return(false);
            }

            pRule.GetBaseThing().EngineName = MyBaseEngine.GetEngineName();
            if (pRule.TriggerCondition == eRuleTrigger.Set)
            {
                pRule.ActionValue = null;
            }
            pRule.IsRuleRunning        = false;
            pRule.IsRuleWaiting        = true;
            pRule.IsIllegal            = false;
            pRule.IsTriggerObjectAlive = false;
            pRule.Parent = MyBaseThing.ID;
            pRule.GetBaseThing().EngineName = MyBaseEngine.GetEngineName();
            TheSystemMessageLog.WriteLog(4445, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(eKnownDeviceTypes.TheThingRule, $"Rule {pRule.FriendlyName} stopped during Register Rule - waiting for startup"), false);

            TheThing.SetSafePropertyDate(pRule.GetBaseThing(), "LastTriggered", DateTimeOffset.MinValue);
            TheThing.SetSafePropertyDate(pRule.GetBaseThing(), "LastAction", DateTimeOffset.MinValue);
            TheThingRegistry.RegisterThing(pRule);
            return(true);
        }
示例#11
0
 public TheDemoBase(TheThing tBaseThing, ICDEPlugin pPluginBase)
 {
     MyBaseThing            = tBaseThing ?? new TheThing();
     MyBaseEngine           = pPluginBase.GetBaseEngine();
     MyBaseThing.EngineName = MyBaseEngine.GetEngineName();
     MyBaseThing.SetIThingObject(this);
     TheThingRegistry.RegisterThing(this);
 }
示例#12
0
        private void ShowKPI(int pFldOrder, string pLabel, string pUpdName, int MaxVal = 100, int AveVal = 50, string pUnits = "bytes")
        {
            TheNMIEngine.AddSmartControl(MyBaseThing, mMyForm, eFieldType.TileGroup, pFldOrder, 0, 0, null, null, new nmiCtrlTileGroup {
                ParentFld = 300, TileWidth = 6
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, mMyForm, eFieldType.SmartLabel, pFldOrder + 1, 0, 0, null, null, new nmiCtrlSmartLabel {
                ParentFld = pFldOrder, Text = pLabel, NoTE = true, TileFactorY = 2, TileHeight = 1, TileWidth = 5, ClassName = "cdeTileGroupHeaderSmall"
            });
            var tBut = TheNMIEngine.AddSmartControl(MyBaseThing, mMyForm, eFieldType.TileButton, pFldOrder + 2, 2, 0, "V-Tise", null, new nmiCtrlTileButton {
                ParentFld = pFldOrder, NoTE = true, TileFactorY = 2, TileHeight = 1, TileWidth = 1, ClassName = "cdeGlassButton"
            });

            tBut.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, $"But{pUpdName}", (sender, para) =>
            {
                TheThing tT = TheThingRegistry.GetThingByID(MyBaseEngine.GetEngineName(), $"ISO{MyBaseThing.cdeMID}:{pUpdName}");
                if (tT == null)
                {
                    TheKPIReport tRep = new TheKPIReport(null, MyPlugin);
                    TheThing.SetSafePropertyGuid(tRep, "RealSensorThing", MyBaseThing.cdeMID);
                    tRep.GetBaseThing().ID = $"ISO{MyBaseThing.cdeMID}:{pUpdName}";
                    MyBaseThing.GetProperty(pUpdName, true);
                    TheThing.SetSafePropertyString(tRep, "RealSensorProperty", pUpdName);
                    TheThing.SetSafePropertyNumber(tRep, "StateSensorMaxValue", MaxVal);
                    TheThing.SetSafePropertyNumber(tRep, "StateSensorAverage", AveVal);
                    TheThing.SetSafePropertyNumber(tRep, "StateSensorSteps", MaxVal / 15);
                    TheThing.SetSafePropertyString(tRep, "StateSensorValueName", pLabel);
                    TheThing.SetSafePropertyString(tRep, "StateSensorUnit", pUnits);
                    TheThing.SetSafePropertyString(tRep, "FriendlyName", MyBaseThing.FriendlyName);
                    TheThing.SetSafePropertyString(tRep, "ReportName", $"ISO-KPI: {MyBaseThing.FriendlyName} - {pLabel}");
                    TheThing.SetSafePropertyString(tRep, "ReportCategory", "ISO KPI Reports");
                    ThePluginInfo tI = MyPlugin.GetBaseEngine().GetPluginInfo();
                    if (tI != null)
                    {
                        TheThing.SetSafePropertyString(tRep, "SerialNumber", TheCommonUtils.CStr(tI.CurrentVersion));
                        TheThing.SetSafePropertyString(tRep, "VendorName", TheCommonUtils.CStr(tI.Developer));
                        TheThing.SetSafePropertyString(tRep, "ProductName", TheCommonUtils.CStr(tI.ServiceDescription));
                        TheThing.SetSafePropertyString(tRep, "ProductText", TheCommonUtils.CStr(tI.LongDescription));
                        TheThing.SetSafePropertyString(tRep, "VendorText", TheCommonUtils.CStr(tI.DeveloperUrl));
                        TheThing.SetSafePropertyString(tRep, "ProductID", TheCommonUtils.CStr(tI.cdeMID));
                    }
                    TheThingRegistry.RegisterThing(tRep);
                    MyBaseEngine.ProcessMessage(new TheProcessMessage(new TSM(MyBaseEngine.GetEngineName(), "REFRESH_DASH")));
                }
                else
                {
                    TheCommCore.PublishToOriginator((para as TheProcessMessage).Message, new TSM(eEngineName.NMIService, "NMI_TTS", tT.cdeMID.ToString()));
                }
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, mMyForm, eFieldType.SmartLabel, pFldOrder + 3, 0, 0, null, pUpdName, new nmiCtrlSingleEnded {
                ParentFld = pFldOrder, TileWidth = 2
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, mMyForm, eFieldType.BarChart, pFldOrder + 4, 0, 0, null, pUpdName, new nmiCtrlBarChart()
            {
                ParentFld = pFldOrder, MaxValue = MaxVal, TileWidth = 4, NoTE = true, Foreground = "blue"
            });
        }
 public TheServiceHealthData(string pEngineName, string pURL)
 {
     MyBaseThing = TheThingRegistry.GetThingByProperty(pEngineName, Guid.Empty, "ID", "PCH@" + TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID) ?? new TheThing
     {
         DeviceType = "PC-Health",
         ID         = "PCH@" + TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID,
         EngineName = pEngineName
     };
     cdeMID = MyBaseThing.cdeMID;
     cdeA   = MyBaseThing.cdeA;
     MyBaseThing.SetIThingObject(this);
     TheThingRegistry.RegisterThing(this);
 }
示例#14
0
 public TheCPUInfo(string pEngineName, string pURL)
 {
     MyBaseThing = TheThingRegistry.GetThingByProperty(pEngineName, Guid.Empty, "ID", "CPU@" + TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString());
     if (MyBaseThing == null)
     {
         MyBaseThing            = new TheThing();
         MyBaseThing.DeviceType = "CPUInfo";
         MyBaseThing.ID         = "CPU@" + TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString();
         MyBaseThing.EngineName = pEngineName;
     }
     cdeMID = MyBaseThing.cdeMID;
     MyBaseThing.SetIThingObject(this);
     TheThingRegistry.RegisterThing(this);
 }
示例#15
0
        //private ApplicationConfiguration m_configuration;
        private void GetEndpoints()
        {
            try
            {
                // set a short timeout because this is happening in the drop down event.
                EndpointConfiguration configuration = EndpointConfiguration.Create();
                configuration.OperationTimeout = 20000;

                // Connect to the local discovery server and find the available servers.
                using (DiscoveryClient client = DiscoveryClient.Create(new Uri(Utils.Format("opc.tcp://{0}:4840", MyBaseThing.Address)), configuration))
                {
                    ApplicationDescriptionCollection servers = client.FindServers(null);

                    // populate the drop down list with the discovery URLs for the available servers.
                    for (int ii = 0; ii < servers.Count; ii++)
                    {
                        // don't show discovery servers.
                        if (servers[ii].ApplicationType == ApplicationType.DiscoveryServer)
                        {
                            continue;
                        }

                        for (int jj = 0; jj < servers[ii].DiscoveryUrls.Count; jj++)
                        {
                            string discoveryUrl = servers[ii].DiscoveryUrls[jj];

                            // Many servers will use the '/discovery' suffix for the discovery endpoint.
                            // The URL without this prefix should be the base URL for the server.
                            if (discoveryUrl.EndsWith("/discovery"))
                            {
                                discoveryUrl = discoveryUrl.Substring(0, discoveryUrl.Length - "/discovery".Length);
                            }

                            TheThing tDev = TheThingRegistry.GetThingByFunc(MyBaseEngine.GetEngineName(), s => s.GetProperty("Address", false).ToString() == discoveryUrl);
                            if (tDev == null)
                            {
                                TheOPCUARemoteServer tS = new TheOPCUARemoteServer(null, this, discoveryUrl);
                                TheThingRegistry.RegisterThing(tS);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            finally
            {
            }
        }
示例#16
0
        void sinkFileReceived(ICDEThing pThing, object pFileName)
        {
            TheProcessMessage pMsg = pFileName as TheProcessMessage;

            if (pMsg?.Message == null)
            {
                return;
            }

            var tb = new TheBitmapImage(null, this);

            TheThing.SetSafePropertyString(tb, "CurrentImage", pMsg.Message.TXT);
            tb.GetBaseThing().FriendlyName = pMsg.Message.TXT.Substring(pMsg.Message.TXT.IndexOf('\\') + 1);
            TheThingRegistry.RegisterThing(tb);
            TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", string.Format("###Image-File ({0}) received!###", pMsg.Message.TXT)));
        }
        void InitServices()
        {
            List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(MyBaseThing.EngineName);

            foreach (TheThing tDev in tDevList)
            {
                if (!tDev.HasLiveObject)
                {
                    // There is no .Net class instance associated with this TheThing: create and register it, so the C-DEngine can find it
                    switch (tDev.DeviceType)
                    {
                    // If your class does not follow the naming convention CDMyPlugin1.<fieldname>, you may need to instantiate it explicitly like this:
                    //case e$safeprojectname$DeviceTypes.cdeThingDeviceTypeA:
                    //    TheThingRegistry.RegisterThing(new cdeThingDeviceTypeA(tDev, this.GetBaseEngine()));
                    //    break;
                    default:
                        // Assume the e$safeprojectname$DeviceTypes field names match the class names: find the field that corresponds to the TheThing.DeviceType being requested
                        var fields = typeof(e$safeprojectname$DeviceTypes).GetFields();
                        foreach (FieldInfo deviceTypeField in fields)
                        {
                            var deviceTypeValue = deviceTypeField.GetValue(new e$safeprojectname$DeviceTypes()) as string;
                            if (deviceTypeValue == null || deviceTypeField.FieldType.FullName != "System.String")
                            {
                                continue;
                            }
                            if (deviceTypeValue == tDev.DeviceType)
                            {
                                // Found a matching field: create an instance of the class based on the field's name, and register it with the C-DEngine
                                var deviceTypeClass = Type.GetType("$safeprojectname$." + deviceTypeField.Name);
                                if (deviceTypeClass == null)
                                {
                                    deviceTypeClass = Type.GetType("$safeprojectname$.ViewModel." + deviceTypeField.Name);
                                }
                                if (deviceTypeClass != null)
                                {
                                    TheThingRegistry.RegisterThing(Activator.CreateInstance(deviceTypeClass, tDev, this) as ICDEThing);
                                }
                                break;
                            }
                        }
                        break;
                    }
                }
            }
            MyBaseEngine.SetStatusLevel(-1); //Calculates the current statuslevel of the service/engine
        }
示例#18
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);
        }
示例#19
0
        void InitServices()
        {
            List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(MyBaseThing.EngineName);

            if (tDevList.Count > 0)
            {
                foreach (TheThing tDev in tDevList)
                {
                    if (tDev.DeviceType != "IBaseEngine")
                    {
                        if (!tDev.HasLiveObject)
                        {
                            try
                            {
                                switch (tDev.DeviceType)
                                {
                                case eModbusType.ModbusTCPDevice:
                                {
                                    var tS = new ModbusTCPDevice(tDev, this, null);
                                    TheThingRegistry.RegisterThing(tS);
                                }
                                break;

                                case eModbusType.ModbusRTUDevice:
                                {
                                    var tS = new ModbusRTUDevice(tDev, this, null);
                                    TheThingRegistry.RegisterThing(tS);
                                }
                                break;
                                }
                            }
                            catch (Exception)
                            {
                                TheBaseAssets.MySYSLOG.WriteToLog(500, new TSM(MyBaseEngine.GetEngineName(), $"Failed to start Modbus Device {tDev.FriendlyName}", eMsgLevel.l1_Error));
                                MyBaseThing.StatusLevel = 2;
                            }
                        }
                    }
                }
            }
            MyBaseEngine.SetStatusLevel(-1); //Calculates the current statuslevel of the service/engine
        }
示例#20
0
        T CreateOrUpdateService <T>(TheThing tDevice, bool bRegisterThing) where T : TheBitmapImage
        {
            T tServer;

            if (tDevice == null || !tDevice.HasLiveObject)
            {
                tServer = (T)Activator.CreateInstance(typeof(T), tDevice, this);
                if (bRegisterThing)
                {
                    TheThingRegistry.RegisterThing((ICDEThing)tServer);
                }
            }
            else
            {
                tServer = tDevice.GetObject() as T;
                if (tServer == null)
                {
                    tServer = (T)Activator.CreateInstance(typeof(T), tDevice, this);
                }
            }
            return(tServer);
        }
        void InitServers()
        {
            List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(this.MyBaseEngine.GetEngineName());

            if (tDevList.Count > 0)
            {
                foreach (TheThing tDev in tDevList)
                {
                    if (!tDev.HasLiveObject)
                    {
                        switch (tDev.DeviceType)
                        {
                        case MeshDeviceTypes.MeshReceiver:
                            TheMeshReceiver tMR = new TheMeshReceiver(tDev, this);
                            TheThingRegistry.RegisterThing(tMR);
                            break;
                        }
                    }
                }
            }

            MyBaseEngine.SetStatusLevel(-1);
        }
示例#22
0
        private async Task RunPlaybackAsync(IEnumerable <cdeP> allProperties, IEnumerable <object> thingUpdates, TimeSpan startupDelayRange, bool bFromAutoStart, double propCountBefore)
        {
            for (int j = 1; j <= ReplayCount; j++)
            {
                playbackCancel?.Cancel();
                playbackCancel = new CancellationTokenSource();
                var cancelCombined = CancellationTokenSource.CreateLinkedTokenSource(playbackCancel.Token, TheBaseAssets.MasterSwitchCancelationToken);
                IsStarted = true;
                MyBaseThing.StatusLevel = 1;
                MyBaseThing.LastMessage = $"Playback started: {ItemCount} items. {ParallelPlaybackCount} things.";
                for (int i = 1; i <= ParallelPlaybackCount; i++)
                {
                    TheThing tThingOverride = null;
                    if (!string.IsNullOrEmpty(PlaybackEngineName))
                    {
                        if (TheThingRegistry.GetBaseEngine(PlaybackEngineName) == null)
                        {
                            TheCDEngines.RegisterNewMiniRelay(PlaybackEngineName);
                        }

                        var thingName = $"{MyBaseThing.FriendlyName}{i:D6}";
                        tThingOverride = TheThingRegistry.GetThingByID(PlaybackEngineName, thingName, true);
                        if (tThingOverride == null)
                        {
                            tThingOverride = new TheThing
                            {
                                FriendlyName = thingName,
                                ID           = thingName,
                                EngineName   = PlaybackEngineName,
                                DeviceType   = PlaybackDeviceType,
                            };

                            foreach (var prop in allProperties)
                            {
                                tThingOverride.SetProperty(prop.Name, prop.Value, prop.cdeT);
                            }
                            TheThingRegistry.RegisterThing(tThingOverride);
                        }
                        // This only works if the plug-in is actually installed, not with mini relay
                        //var createThingInfo = new TheThingRegistry.MsgCreateThingRequestV1
                        //{
                        //    EngineName = PlaybackEngineName,
                        //    DeviceType = PlaybackDeviceType,
                        //    InstanceId = thingName,
                        //    FriendlyName = thingName,
                        //    CreateIfNotExist = true,
                        //    DoNotModifyIfExists = true,
                        //    OwnerAddress = MyBaseThing,
                        //    Properties = new Dictionary<string, object> { { "ID", thingName } },
                        //};
                        //tThingOverride = await TheThingRegistry.CreateOwnedThingAsync(createThingInfo, new TimeSpan(0, 1, 0));
                        if (tThingOverride == null)
                        {
                            MyBaseThing.LastMessage = "Error creating playback thing";
                            break;
                        }
                    }
                    var playbackTask = TheCommonUtils.cdeRunTaskChainAsync($"Playback{i}", o => PlaybackLoop(tThingOverride, cancelCombined.Token, thingUpdates, startupDelayRange, bFromAutoStart), true);
                    playbackTasks.Add(playbackTask);
                }

                _ = await TheCommonUtils.TaskWhenAll(playbackTasks).ContinueWith(async(t) =>
                {
                    try
                    {
                        PlaybackDuration = sw.Elapsed;
                        sw.Stop();
                        OnKpiUpdate(null);
                        var propCount = Gen_Stats_PropertyCounter - propCountBefore;
                        var message   = $"Playback done. {propCount} props in {PlaybackDuration}. {propCount / PlaybackDuration.TotalSeconds} props/s. {ItemCount * ParallelPlaybackCount / PlaybackDuration.TotalSeconds} items/s.";
                        //MyBaseThing.LastMessage = message;
                        TheBaseAssets.MySYSLOG.WriteToLog(700, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseThing.EngineName, message, eMsgLevel.l6_Debug));
                        await StopPlaybackAsync(message);
                        _ = new CDMyMeshManager.Contracts.MsgReportTestStatus
                        {
                            NodeId           = TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID,
                            PercentCompleted = (j * 1.0 / ReplayCount) * 100,
                            SuccessRate      = 100,
                            Status           = j == ReplayCount ? CDMyMeshManager.Contracts.eTestStatus.Success : CDMyMeshManager.Contracts.eTestStatus.Running,
                            TestRunId        = TheCommonUtils.CGuid(TheBaseAssets.MySettings.GetSetting("TestRunID")),
                            Timestamp        = DateTimeOffset.Now,
                            ResultDetails    = new Dictionary <string, object>
                            {
                                { "Message", message },
                                { "PropertyCount", propCount },
                                { "DurationInSeconds", PlaybackDuration.TotalSeconds }
                            },
                        }.Publish().Result;
                    }
                    catch { }
                }, TaskContinuationOptions.OnlyOnRanToCompletion);
            }
        }
示例#23
0
        public void TestSensorConsumerModel()
        {
            var deviceTypes = TheThingRegistry.GetAllDeviceTypesByCap(nsCDEngine.ViewModels.eThingCaps.SensorConsumer, true);

            Assert.Greater(deviceTypes.Count, 0, "No sensor consumer device types found");

            var sensorThing = new TheThing {
                EngineName = "CDMyVThings.TheVThings", DeviceType = "Memory Tag", ID = "TestSensorThing01"
            };

            TheThingRegistry.RegisterThing(sensorThing);
            sensorThing.DeclareSensorProperty("Sensor01_1", ePropertyTypes.TNumber, new cdeP.TheSensorMeta {
            }).Value = 12345.67;
            sensorThing.DeclareSensorProperty("Sensor01_2", ePropertyTypes.TString, new cdeP.TheSensorMeta {
            }).Value = "Hello World!";
            sensorThing.DeclareSensorProperty("Sensor01_3", ePropertyTypes.TDate, new cdeP.TheSensorMeta {
            }).Value = DateTimeOffset.Now;

            var sensorThing2 = new TheThing {
                EngineName = "CDMyVThings.TheVThings", DeviceType = "Memory Tag", ID = "TestSensorThing02"
            };

            TheThingRegistry.RegisterThing(sensorThing);
            sensorThing2.DeclareSensorProperty("Sensor02_1", ePropertyTypes.TNumber, new cdeP.TheSensorMeta {
            }).Value = 12345.67;
            sensorThing2.DeclareSensorProperty("Sensor02_2", ePropertyTypes.TString, new cdeP.TheSensorMeta {
            }).Value = "Hello World!";
            sensorThing2.DeclareSensorProperty("Sensor02_3", ePropertyTypes.TDate, new cdeP.TheSensorMeta {
            }).Value = DateTimeOffset.Now;

            foreach (var deviceType in deviceTypes)
            {
                TestInfo testInfo;
                var      consumer = CreateThingForTest(deviceType, out testInfo);
                WriteLine($"{deviceType}: Consumer created");

                var thingSubscriptions = new List <TheThing.TheThingSubscription>
                {
                    new TheThing.TheThingSubscription {
                        ThingReference = sensorThing,
                    },
                    new TheThing.TheThingSubscription {
                        ThingReference = sensorThing2,
                    },
                };

                {
                    var subscribeToThingsResponse = consumer.SubscribeToThingsAsync(thingSubscriptions).Result;

                    Assert.NotNull(subscribeToThingsResponse, $"Timeout or subscribe to things message not implemented by consumer {deviceType}");
                    Assert.IsTrue(string.IsNullOrEmpty(subscribeToThingsResponse.Error), $"Error from consumer {deviceType}: {subscribeToThingsResponse.Error}");
                    Assert.GreaterOrEqual(thingSubscriptions.Count, subscribeToThingsResponse.SubscriptionStatus.Count, $"Not enough status reports for {deviceType}");
                    foreach (var subStatus in subscribeToThingsResponse.SubscriptionStatus)
                    {
                        Assert.IsTrue(string.IsNullOrEmpty(subStatus.Error), $"Error from consumer {deviceType}: {subStatus.Error}");
                        Assert.IsTrue(subStatus.Subscription.SubscriptionId.HasValue && subStatus.Subscription.SubscriptionId != Guid.Empty, $"No subscriptionid from consumer {deviceType}: {subStatus.Subscription.SubscriptionId}");
                    }
                }
                // TODO verify that subscriptions are actually getting consumed (at least for some consumer plug-ins)
                {
                    var getSubscriptionsResponse = consumer.GetThingSubscriptionsAsync().Result;

                    Assert.NotNull(getSubscriptionsResponse, $"Timeout or get things message not implemented by consumer {deviceType}");
                    Assert.IsTrue(string.IsNullOrEmpty(getSubscriptionsResponse.Error), $"Error from consumer {deviceType}: {getSubscriptionsResponse.Error}");
                    Assert.AreEqual(thingSubscriptions.Count, getSubscriptionsResponse.ThingSubscriptions.Count, $"Missing subscriptions for {deviceType}");
                    foreach (var sub in getSubscriptionsResponse.ThingSubscriptions)
                    {
                        Assert.IsTrue(sub.SubscriptionId.HasValue && sub.SubscriptionId != Guid.Empty, $"No subscriptionid from consumer {deviceType}: {sub.SubscriptionId}");
                    }

                    var unsubscribeResponse = consumer.UnsubscribeFromThingsAsync(getSubscriptionsResponse.ThingSubscriptions.Select(sub => sub.SubscriptionId ?? Guid.Empty).Take(1)).Result;
                    Assert.NotNull(unsubscribeResponse, $"Timeout or unsubscribe things message not implemented by consumer {deviceType}");
                    Assert.IsTrue(string.IsNullOrEmpty(unsubscribeResponse.Error), $"Error from consumer {deviceType}: {unsubscribeResponse.Error}");
                    Assert.IsTrue(unsubscribeResponse.Failed != null && unsubscribeResponse.Failed.Count == 0, $"Errors during unsubscribe from consumer {deviceType}: {unsubscribeResponse.Failed.Aggregate("", (s, us) => $"{s} {us.Subscription.SubscriptionId}:{us.Error}")}");
                }

                {
                    var getSubscriptionsResponse = consumer.GetThingSubscriptionsAsync().Result;

                    Assert.NotNull(getSubscriptionsResponse, $"Timeout or get things message not implemented by consumer {deviceType}");
                    Assert.IsTrue(string.IsNullOrEmpty(getSubscriptionsResponse.Error), $"Error from consumer {deviceType}: {getSubscriptionsResponse.Error}");
                    Assert.AreEqual(thingSubscriptions.Count - 1, getSubscriptionsResponse.ThingSubscriptions.Count, $"Missing subscriptions for {deviceType}");
                    foreach (var sub in getSubscriptionsResponse.ThingSubscriptions)
                    {
                        Assert.IsTrue(sub.SubscriptionId.HasValue && sub.SubscriptionId != Guid.Empty, $"No subscriptionid from consumer {deviceType}: {sub.SubscriptionId}");
                    }

                    var unsubscribeResponse = consumer.UnsubscribeFromThingsAsync(getSubscriptionsResponse.ThingSubscriptions.Select(sub => sub.SubscriptionId ?? Guid.Empty)).Result;
                    Assert.NotNull(unsubscribeResponse, $"Timeout or unsubscribe things message not implemented by consumer {deviceType}");
                    Assert.IsTrue(string.IsNullOrEmpty(unsubscribeResponse.Error), $"Error from consumer {deviceType}: {unsubscribeResponse.Error}");
                    Assert.IsTrue(unsubscribeResponse.Failed != null && unsubscribeResponse.Failed.Count == 0, $"Errors during unsubscribe from consumer {deviceType}: {unsubscribeResponse.Failed.Aggregate("", (s, us) => $"{s} {us.Subscription.SubscriptionId}:{us.Error}")}");
                }
                {
                    var getSubscriptionsResponse = consumer.GetThingSubscriptionsAsync().Result;

                    Assert.NotNull(getSubscriptionsResponse, $"Timeout or get things message not implemented by consumer {deviceType}");
                    Assert.IsTrue(string.IsNullOrEmpty(getSubscriptionsResponse.Error), $"Error from consumer {deviceType}: {getSubscriptionsResponse.Error}");
                    Assert.AreEqual(0, getSubscriptionsResponse.ThingSubscriptions.Count, $"Leaked subscriptions for {deviceType}");
                }

                if (consumer.DeviceType != eKnownDeviceTypes.IBaseEngine)
                {
                    TheThingRegistry.DeleteThing(consumer);
                }
            }
            TheThingRegistry.DeleteThing(sensorThing);
            TheThingRegistry.DeleteThing(sensorThing2);
        }
示例#24
0
        public void TestSensorPipeline()
        {
            var sensorThing = new TheThing {
                EngineName = "CDMyVThings.TheVThings", DeviceType = "Memory Tag", ID = "TestSensorThing03"
            };

            TheThingRegistry.RegisterThing(sensorThing);
            //sensorThing = TheThingRegistry.GetThingByMID(sensorThing.cdeMID);

            // Make all providers send properties into the memory thing
            var providers = new List <TheThing>();
            {
                var deviceTypes = TheThingRegistry.GetAllDeviceTypesByCap(nsCDEngine.ViewModels.eThingCaps.SensorProvider, true);
                Assert.Greater(deviceTypes.Count, 0, "No sensor provider device types found");
                foreach (var deviceType in deviceTypes)
                {
                    TestInfo testInfo;
                    var      provider = CreateThingForTest(deviceType, out testInfo);
                    WriteLine($"{deviceType}: Provider created");

                    int subscriptionCount = BrowseAndSubscribeAllSensors(provider, sensorThing, testInfo.MaximumBrowseTags, testInfo.MinimumBrowseTags, out var browseResponse, out var sensorSubscriptionResponse, out var successfullSubscriptions);

                    var getSubscriptionResponse = provider.GetSensorProviderSubscriptionsAsync().Result;
                    Assert.IsNotNull(getSubscriptionResponse, "Timeout or get subscriptions message not implemented by plug-in");
                    Assert.IsTrue(string.IsNullOrEmpty(getSubscriptionResponse.Error), $"Error from GetSensorSubscriptions: {getSubscriptionResponse.Error}");

                    Assert.AreEqual(subscriptionCount, getSubscriptionResponse.Subscriptions.Count);

                    if (sensorSubscriptionResponse.SubscriptionStatus.Count <= 0)
                    {
                        WriteLine($"{deviceType}: No subscriptions found after subscribe request");
                    }
                    providers.Add(provider);
                }
            }

            var consumers = new List <TheThing>();
            {
                var deviceTypes = TheThingRegistry.GetAllDeviceTypesByCap(nsCDEngine.ViewModels.eThingCaps.SensorConsumer, true);
                Assert.Greater(deviceTypes.Count, 0, "No sensor consumer device types found");

                foreach (var deviceType in deviceTypes)
                {
                    TestInfo testInfo;
                    var      consumer = CreateThingForTest(deviceType, out testInfo);
                    WriteLine($"{deviceType}: Consumer created");

                    var thingSubscriptions = new List <TheThing.TheThingSubscription>
                    {
                        new TheThing.TheThingSubscription {
                            ThingReference = sensorThing,
                        },
                    };

                    {
                        var subscribeToThingsResponse = consumer.SubscribeToThingsAsync(thingSubscriptions).Result;

                        Assert.NotNull(subscribeToThingsResponse, $"Timeout or subscribe to things message not implemented by consumer {deviceType}");
                        Assert.IsTrue(string.IsNullOrEmpty(subscribeToThingsResponse.Error), $"Error from consumer {deviceType}: {subscribeToThingsResponse.Error}");
                        Assert.GreaterOrEqual(thingSubscriptions.Count, subscribeToThingsResponse.SubscriptionStatus.Count, $"Not enough status reports for {deviceType}");
                        foreach (var subStatus in subscribeToThingsResponse.SubscriptionStatus)
                        {
                            Assert.IsTrue(string.IsNullOrEmpty(subStatus.Error), $"Error from consumer {deviceType}: {subStatus.Error}");
                            Assert.IsTrue(subStatus.Subscription.SubscriptionId.HasValue && subStatus.Subscription.SubscriptionId != Guid.Empty, $"No subscriptionid from consumer {deviceType}: {subStatus.Subscription.SubscriptionId}");
                        }
                    }
                    // TODO verify that subscriptions are actually getting consumed (at least for some consumer plug-ins)
                    {
                        var getSubscriptionsResponse = consumer.GetThingSubscriptionsAsync().Result;

                        Assert.NotNull(getSubscriptionsResponse, $"Timeout or get things message not implemented by consumer {deviceType}");
                        Assert.IsTrue(string.IsNullOrEmpty(getSubscriptionsResponse.Error), $"Error from consumer {deviceType}: {getSubscriptionsResponse.Error}");
                        Assert.AreEqual(thingSubscriptions.Count, getSubscriptionsResponse.ThingSubscriptions.Count, $"Missing or too many subscriptions for {deviceType}");
                        foreach (var sub in getSubscriptionsResponse.ThingSubscriptions)
                        {
                            Assert.IsTrue(sub.SubscriptionId.HasValue && sub.SubscriptionId != Guid.Empty, $"No subscriptionid from consumer {deviceType}: {sub.SubscriptionId}");
                        }
                    }

                    consumers.Add(consumer);
                }
            }

            var pipelineConfig = sensorThing.GetThingPipelineConfigurationAsync(true).Result;

            foreach (var thing in consumers)
            {
                if (thing.DeviceType != eKnownDeviceTypes.IBaseEngine)
                {
                    TheThingRegistry.DeleteThing(thing);
                }
            }

            foreach (var thing in providers)
            {
                if (thing.DeviceType != eKnownDeviceTypes.IBaseEngine)
                {
                    TheThingRegistry.DeleteThing(thing);
                }
            }
            // TODO Verify that provider properties are gone

            TheThingRegistry.DeleteThing(sensorThing);

            foreach (var thingConfig in pipelineConfig.ThingConfigurations)
            {
                if (configs.TryGetValue($"{thingConfig.ThingIdentity.EngineName}/{thingConfig.ThingIdentity.DeviceType}", out var testInfo))
                {
                    if (testInfo.SpecializationValues != null)
                    {
                        foreach (var propKV in testInfo.SpecializationValues)
                        {
                            thingConfig.ThingSpecializationParameters[propKV.Key] = propKV.Value;
                        }
                    }
                }
            }

            var owner  = TheThingRegistry.GetBaseEngineAsThing(eEngineName.ContentService);
            var things = TheThing.CreateThingPipelineFromConfigurationAsync(owner, pipelineConfig).Result;

            Assert.AreEqual(pipelineConfig.ThingConfigurations.Count, things.Count, "Not all pipeline things were created.");
            Assert.AreEqual(pipelineConfig.ThingConfigurations.Count(cfg => cfg.ThingSpecializationParameters != null), things.Count, "Not all specialization parameters were created.");
            int i = 0;

            foreach (var thing in things)
            {
                Assert.NotNull(thing, $"Thing {i} not created: {pipelineConfig.ThingConfigurations[i].ThingIdentity}");
                i++;
            }
            var memoryThing = things.FirstOrDefault(t => t.EngineName == sensorThing.EngineName);

            Assert.NotNull(memoryThing);
            var minimumTagCount = configs.Sum(c => c.Value.MinimumBrowseTags);

            Assert.Greater(memoryThing.MyPropertyBag.Count, minimumTagCount); // TODO adjust this to actual sensors, not just the OPC UA client subscription count

            foreach (var thing in things)
            {
                if (thing.DeviceType != eKnownDeviceTypes.IBaseEngine)
                {
                    TheThingRegistry.DeleteThing(thing);
                }
            }
        }
示例#25
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
        }
示例#26
0
        /// <summary>
        /// Message Handler of TheThingEngine
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="pIncoming"></param>
        public override void HandleMessage(ICDEThing sender, object pIncoming)
        {
            if (!(pIncoming is TheProcessMessage pMsg) || pMsg.Message == null)
            {
                return;
            }
            string[] tCmd = pMsg.Message.TXT.Split(':');
            switch (tCmd[0])   //string 2 cases
            {
            case "CDE_INITIALIZED":
                MyBaseEngine.SetInitialized(pMsg.Message);
                break;

            case "CDE_INITIALIZE":
                if (!MyBaseEngine.GetEngineState().IsEngineReady)
                {
                    MyBaseEngine.SetInitialized(pMsg.Message);
                }
                MyBaseEngine.ReplyInitialized(pMsg.Message);
                break;

            case "CDE_REGISTERPROPERTY":
                if (tCmd.Length > 1)
                {
                    TheThing tThing2 = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(tCmd[1]));
                    if (tThing2 != null)
                    {
                        cdeP tProp = tThing2.GetProperty(pMsg.Message.PLS);
                        if (tProp == null)
                        {
                            return;
                        }
                        tProp.SetPublication(true, pMsg.Message.GetOriginator());       //OK - Very late "Binding"
                    }
                }
                break;

            case "CDE_REGISTERTHING":
                if (MyThingRegistry != null)
                {
                    //if (TheScopeManager.IsNodeTrusted(pMsg.Message.GetOriginator())) // CODE-REVIEW: This security enhancement will not all Global Things to work anymore. WE need to bring this back when we have the meshmanager working
                    //{
                    //    TheBaseAssets.MySYSLOG.WriteToLog(7678, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(eEngineName.ContentService, String.Format("Register Thing from untrusted node received {0} - disallowed", pMsg.Message.GetOriginator()), eMsgLevel.l3_ImportantMessage));
                    //    return;
                    //}
                    TheThing tThing = TheCommonUtils.DeserializeJSONStringToObject <TheThing>(pMsg.Message.PLS);
                    if (tThing != null)
                    {
                        TheThingRegistry.RegisterThing(tThing);
                    }
                }
                break;

            case "CDE_UNREGISTERTHING":
                if (MyThingRegistry != null)
                {
                    //if (TheScopeManager.IsNodeTrusted(pMsg.Message.GetOriginator()))
                    //{
                    //    TheBaseAssets.MySYSLOG.WriteToLog(7678, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(eEngineName.ContentService, String.Format("Unregister Thing from untrusted node received {0} - disallowed", pMsg.Message.GetOriginator()), eMsgLevel.l3_ImportantMessage));
                    //    return;
                    //}
                    TheThingRegistry.DeleteThingByID(TheCommonUtils.CGuid(pMsg.Message.PLS));
                }
                break;

            case "CDE_SETP":
                if (!string.IsNullOrEmpty(pMsg.Message.PLS) && tCmd.Length > 1)
                {
                    TheThing tG = TheThingRegistry.GetThingByMID(TheCommonUtils.CGuid(tCmd[1]), true);
                    if (tG != null)
                    {
                        cdeP p = TheCommonUtils.DeserializeJSONStringToObject <cdeP>(pMsg.Message.PLS);
                        if (p != null)
                        {
                            tG.UpdatePropertyInBag(p, true, true);
                        }
                    }
                }
                break;

            case "CDE_SYNC_THINGS":
                if (pMsg.Message.PLS.Length > 2)
                {
                    List <TheThing> tList = TheCommonUtils.DeserializeJSONStringToObject <List <TheThing> >(pMsg.Message.PLS);
                    TheBaseAssets.MySYSLOG.WriteToLog(7678, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(eEngineName.ContentService, String.Format("CDE_SYNC_THINGS: Received for node {0}", pMsg.Message.GetOriginator()), eMsgLevel.l3_ImportantMessage));     //, pMsg.Message.PLS));
                    TheThingRegistry.SyncGlobalThings(pMsg.Message.GetOriginator(), tList);
                }
                break;

            case "CDE_SEND_GLOBAL_THINGS":
                SendGlobalThings(pMsg.Message.GetOriginator());
                break;

            case "CDE_REGISTERRULE":
                var tEngs = TheThingRegistry.GetBaseEnginesByCap(eThingCaps.RulesEngine);
                foreach (var t in tEngs)
                {
                    t.GetBaseThing()?.HandleMessage(sender, pMsg);
                }
                break;
            }
        }