示例#1
0
        public bool LogEvent(TheEventLogData pItem)
        {
            if (pItem == null)
            {
                return(false);
            }
            bool            bRet     = false;
            List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(MyBaseThing.EngineName);

            if (tDevList?.Count > 0)
            {
                foreach (TheThing tDev in tDevList)
                {
                    var tTwin = tDev.GetObject() as ICDELoggerEngine;
                    var tRes  = tTwin?.LogEvent(pItem);
                    if (!bRet && tRes == true)
                    {
                        bRet = true;
                    }
                }
            }
            if (PublishEvents) //This allows to have a logger on a different node
            {
                TheCommCore.PublishCentral(new TSM(eEngineName.ContentService, eEngineEvents.NewEventLogEntry, pItem.EventLevel, TheCommonUtils.SerializeObjectToJSONString(pItem)), true);
            }
            return(bRet);
        }
示例#2
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;
                    }
                }
            }
        }
示例#3
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);
        }
示例#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);
        }
示例#5
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.");
        }
示例#6
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);
        }
        /// <summary>
        /// If this is a service the SimplexProc event will be called when the C-DEngine receives a new event sent by a subscriber to this service
        /// </summary>
        /// <param name="pMsg">The Message to be Processed</param>
        private void ProcessServiceMessage(TheProcessMessage pMsg)
        {
            string[] cmd = pMsg.Message.TXT.Split(':');
            switch (cmd[0]) //string 2 cases
            {
            case "WEBRELAY_RESPONSE":
                TheRequestData tState = TheCommonUtils.DeserializeJSONStringToObject <TheRequestData>(pMsg.Message.PLS);
                if (pMsg.Message.PLB != null && pMsg.Message.PLB.Length > 0)
                {
                    tState.ResponseBuffer = pMsg.Message.PLB;
                }
                tState.RequestUri = new Uri(tState.RequestUriString);
                //tState.SessionState = new TheSessionState() { SScopeID = pMsg.SID };
                sinkResults(tState);
                break;

            case "WEBRELAY_REQUEST":
                TheRequestData tData = TheCommonUtils.DeserializeJSONStringToObject <TheRequestData>(pMsg.Message.PLS);
                if (tData != null)
                {
                    tData.RequestUri = new Uri(tData.RequestUriString);
                    //tData.SessionState = new TheSessionState() { SScopeID = pMsg.SID };
                    if (pMsg.Message.PLB != null && pMsg.Message.PLB.Length > 0)
                    {
                        tData.PostData = pMsg.Message.PLB;
                    }
                    tData.CookieObject = pMsg.Message;
                    ReadHttpPage(tData, tData.SessionState.ARApp, null, sinkProcessResponse);
                    //InterceptHttpRequest(tData,tData.SessionState.ARApp);
                }
                break;

            case "WEBRELAY_REQUESTWRA":
                TSM             tTSM    = new TSM();
                List <TheThing> webApps = TheThingRegistry.GetThingsOfEngine(MyBaseEngine.GetEngineName());
                foreach (TheThing tApp in webApps)
                {
                    if (tApp.Address.Equals(pMsg.Message.PLS))
                    {
                        tTSM.PLS = $"/CDEWRA{tApp.cdeMID}" + TheThing.GetSafePropertyString(tApp, "HomePage");
                        break;
                    }
                }
                if (!string.IsNullOrEmpty(tTSM.PLS))
                {
                    string[]    org          = pMsg.Message.ORG.Split(':');
                    TheThing    senderThing  = TheThingRegistry.GetThingByMID(TheCommonUtils.CGuid(org[1]), true);
                    IBaseEngine senderEngine = TheThingRegistry.GetBaseEngine(senderThing, true);
                    tTSM.ENG = senderEngine.GetEngineName();
                    tTSM.TXT = "RESPONSEWRA";
                    TheCommCore.PublishToOriginator(pMsg.Message, tTSM, true);
                }
                break;
            }
        }
示例#8
0
        private void InitNetworkServices()
        {
            List <TheThing> tDeviceList = TheThingRegistry.GetThingsOfEngine(MyBaseThing.EngineName);

            foreach (TheThing tDevice in tDeviceList)
            {
                switch (tDevice.DeviceType)
                {
                case eNetworkServiceTypes.PingService:
                    CreateOrUpdateService <ThePingService>(tDevice, true);
                    break;
                }
            }
            MyBaseEngine.SetStatusLevel(-1);
            sinkStatChanged(null);
        }
        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
        }
示例#10
0
        void InitServices()
        {
            List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(MyBaseThing.EngineName);

            if (tDevList.Count > 0)
            {
                foreach (TheThing tDev in tDevList)
                {
                    switch (tDev.DeviceType)
                    {
                    case eImageTypes.Bitmap:
                        CreateOrUpdateService <TheBitmapImage>(tDev, true);
                        break;
                    }
                }
            }
            MyBaseEngine.SetStatusLevel(-1); //Calculates the current statuslevel of the service/engine
        }
示例#11
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
        }
        void ShutdownServers()
        {
            List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(this.MyBaseEngine.GetEngineName());

            if (tDevList.Count > 0)
            {
                foreach (TheThing tDev in tDevList)
                {
                    if (tDev.HasLiveObject)
                    {
                        var t = tDev.GetObject();

                        if (t is TheConnectionBase)
                        {
                            (t as TheConnectionBase).Disconnect(true);
                        }
                    }
                }
            }
        }
        private static TheMirrorCache <TheRequestData> ReqBuffer;    //DIC-Allowed

        private void sinkScopeIDUpdate(bool DoReq)
        {
            List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(MyBaseEngine.GetEngineName());

            if (tDevList.Count > 0)
            {
                foreach (TheThing tDev in tDevList)
                {
                    if (tDev.DeviceType == eWebAppTypes.TheWebApp)
                    {
                        TheRelayAppInfo tApp = tDev.GetObject() as TheRelayAppInfo;
                        if (tApp != null && TheCommonUtils.IsUrlLocalhost(tApp.HostUrl)) // tApp.HostUrl.Equals(TheBaseAssets.MyServiceHostInfo.MyStation URL))
                        {
                            tApp.SSID = TheScopeManager.GetScrambledScopeID();
                            TheThingRegistry.UpdateThing(tDev, true);
                        }
                    }
                }
            }
        }
示例#14
0
        private void ScanAllServices()
        {
            int             CombinedCode = 0;
            List <TheThing> tDeviceList  = TheThingRegistry.GetThingsOfEngine(MyBaseThing.EngineName);

            foreach (TheThing tDevice in tDeviceList)
            {
                if (tDevice.HasLiveObject)
                {
                    TheNetworkServiceBase tHid = tDevice.GetObject() as TheNetworkServiceBase;
                    if (tHid?.GetBaseThing().StatusLevel > 1)
                    {
                        CombinedCode++; // = tHid.StatusLevel;
                    }
                }
            }
            MyBaseEngine.SetStatusLevel(-1);
            MyBaseEngine.LastMessage = "Scanning done";
            MyBaseThing.Value        = CombinedCode.ToString();
            sinkStatChanged(null);
        }
        public bool Init()
        {
            if (mIsInitCalled)
            {
                return(false);
            }
            mIsInitCalled = true;

            MyBaseThing.RegisterEvent(eEngineEvents.IncomingMessage, HandleMessage);
            MyBaseEngine.RegisterEvent(eEngineEvents.ThingDeleted, OnDeletedThing);
            MyBaseEngine.RegisterEvent(eEngineEvents.ThingRegistered, OnThingRegistered);
            MyBaseEngine.RegisterEvent(eEngineEvents.ShutdownEvent, OnShutdown);
            TheCommonUtils.cdeRunAsync("Init Mesh Receiver Connections", false, (state) =>
            {
                // Migrate instances from previous versions
                List <TheThing> tLegacyDeviceList = TheThingRegistry.GetThingsOfEngine("CDMyCloudServices.cdeMyCloudService");
                foreach (var tLegacyDevice in tLegacyDeviceList)
                {
                    if (!tLegacyDevice.HasLiveObject)
                    {
                        switch (tLegacyDevice.DeviceType)
                        {
                        case "Mesh Receiver":
                            tLegacyDevice.EngineName = MyBaseThing.EngineName;
                            tLegacyDevice.DeviceType = MeshDeviceTypes.MeshReceiver;
                            TheThingRegistry.UpdateThing(tLegacyDevice, false);
                            break;
                        }
                    }
                }

                //await System.Threading.Tasks.Task.Delay(30000);
                InitServers();
                mIsInitialized = true;
                FireEvent(eThingEvents.Initialized, this, true, true);
                MyBaseEngine.ProcessInitialized();
            }, null);

            return(false);
        }
        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);
        }
示例#17
0
        private void OnThingDeleted(ICDEThing t, object o)
        {
            // TODO: Close any network connections or free up any other resources held
            List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(MyBaseThing.EngineName);

            if (tDevList.Count > 0)
            {
                foreach (TheThing tDev in tDevList)
                {
                    if (tDev.DeviceType != "IBaseEngine")
                    {
                        //TheThingClass tS = null;
                        //if (!tDev.HasLiveObject)
                        //{
                        //    try
                        //    {
                        //        tDev.OnThingDeleted(t, o); // Only needed if the thing needs to free up any resources
                        //    }
                    }
                }
            }
            MyBaseEngine.SetStatusLevel(-1); //Calculates the current statuslevel of the service/engine
        }
示例#18
0
        void InitServices()
        {
            bool            CreatedATextLogger = false;
            List <TheThing> tDevList           = TheThingRegistry.GetThingsOfEngine(MyBaseThing.EngineName);

            if (tDevList.Count > 0)
            {
                foreach (TheThing tDev in tDevList)
                {
                    switch (tDev.DeviceType)
                    {
                    case eTheLoggerServiceTypes.TextLogger:
                        var tt = CreateOrUpdateService <TheTextLogger>(tDev, true);
                        CreatedATextLogger = true;
                        break;

                    case eTheLoggerServiceTypes.GELF:
                        CreateOrUpdateService <TheGELF>(tDev, true);
                        break;

                    case eTheLoggerServiceTypes.StatusLogger:
                        CreateOrUpdateService <TheStatusLogger>(tDev, true);
                        break;

                    case eTheLoggerServiceTypes.IISLogger:
                        CreateOrUpdateService <TheIISLogger>(tDev, true);
                        break;

                    case eTheLoggerServiceTypes.RSSLogger:
                        CreateOrUpdateService <TheRSSFeed>(tDev, true);
                        break;

                    case eTheLoggerServiceTypes.InternalLogger:
                        CreateOrUpdateService <TheInternalLogger>(tDev, true);
                        break;

                    case eTheLoggerServiceTypes.DiscordLogger:
                        CreateOrUpdateService <TheDiscordLogger>(tDev, true);
                        break;
                    }
                }
            }
            if (!CreatedATextLogger && TheBaseAssets.MyCmdArgs?.ContainsKey("CreateEventLog") == true)
            {
                var           tLogName = TheBaseAssets.MyCmdArgs["CreateEventLog"];
                TheTextLogger tThin    = null;
                try
                {
                    tThin = CreateOrUpdateService <TheTextLogger>(null, true);
                    tThin.FriendlyName     = $"Auto Event Log: {(string.IsNullOrEmpty(tLogName) ? "EventLog" : tLogName)}";
                    tThin.Address          = string.IsNullOrEmpty(tLogName) ? "EventLog" : tLogName;
                    tThin.AutoConnect      = true;
                    tThin.EachDayInOwnFile = true;
                    tThin.Connect(null);
                }
                catch (Exception e)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(25010, new TSM(MyBaseEngine.GetEngineName(), $"Could not auto-create Event Log. Address {tLogName} - Path: {tThin?.MyCurLog}", eMsgLevel.l1_Error, e.ToString()));
                }
            }
            MyBaseEngine.SetStatusLevel(-1); //Calculates the current statuslevel of the service/engine
        }
示例#19
0
        private void GenerateMetrics()
        {
            foreach (var senderThing in MySenderThings.TheValues)
            {
                if (senderThing.Disable)
                {
                    continue;
                }
                List <TheThing> thingsToSend = null;
                {
                    var tThing = senderThing.GetThing();
                    if (tThing == null)
                    {
                        if (!string.IsNullOrEmpty(senderThing.EngineName))
                        {
                            thingsToSend = TheThingRegistry.GetThingsOfEngine(senderThing.EngineName, true, true);
                            if (!string.IsNullOrEmpty(senderThing.DeviceType))
                            {
                                thingsToSend.RemoveAll(t => t.DeviceType != senderThing.DeviceType);
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(senderThing.DeviceType))
                            {
                                thingsToSend = TheThingRegistry.GetThingsByFunc("*", t => t.DeviceType.Equals(senderThing.DeviceType, StringComparison.Ordinal), true);
                            }
                        }
                    }
                    else
                    {
                        thingsToSend = new List <TheThing> {
                            tThing
                        };
                    }
                }
                if (thingsToSend == null || thingsToSend.Count == 0)
                {
                    continue;
                }
                //if (string.IsNullOrEmpty(senderThing.PropertiesIncluded)) senderThing.PropertiesIncluded = "Value"; //Make sure we have at least one included
                var propsIncludedConf  = string.IsNullOrEmpty(senderThing.PropertiesIncluded) ? null : TheCommonUtils.cdeSplit(senderThing.PropertiesIncluded, ',', false, false);
                var propsExcluded      = string.IsNullOrEmpty(senderThing.PropertiesExcluded) ? null : TheCommonUtils.cdeSplit(senderThing.PropertiesExcluded, ',', false, false);
                var propsIncludedSplit = propsIncludedConf?.Select(p => TheCommonUtils.cdeSplit(p, ';', false, false));
                var propsIncluded      = propsIncludedSplit?.Select(p => p[0]);

                foreach (var tThing in thingsToSend)
                {
                    // Capture the metrics as specified in the sender thing
                    var tMetricThing = nsCDEngine.ViewModels.TheThingStore.CloneFromTheThing(tThing, false, true, true, propsIncluded, propsExcluded);

                    // Unpack any JSON objects (i.e. DeviceGateLogMesh) into separate properties

                    foreach (var tMetric in tMetricThing.PB.ToList())
                    {
                        if (tMetric.Value?.ToString().Contains("{") == true)
                        {
                            var metricValue = tMetric.Value.ToString().Trim();
                            if (metricValue.StartsWith("{") && metricValue.EndsWith("}"))
                            {
                                try
                                {
                                    var jsonBag = TheCommonUtils.DeserializeJSONStringToObject <Dictionary <string, object> >(metricValue);
                                    if (jsonBag?.Count > 0)
                                    {
                                        if (jsonBag.TryGetValue("PLO", out var payload))
                                        {
                                            // Unpack the PLO in case the payload is a KPI TSM
                                            try
                                            {
                                                var payloadBag = TheCommonUtils.DeserializeJSONStringToObject <Dictionary <string, object> >(payload.ToString());
                                                if (payloadBag != null && payloadBag.Count > 0)
                                                {
                                                    jsonBag = payloadBag as Dictionary <string, object>;
                                                }
                                            }
                                            catch { }
                                        }
                                        foreach (var prop in jsonBag)
                                        {
                                            var metricPrefix = $"[{tMetric.Key.Trim(new char[] { '[', ']' })}]";
                                            var metricName   = $"{metricPrefix}.[{prop.Key}]";
                                            if (propsIncluded?.Contains(metricName) == true || propsIncluded?.Contains($"{metricPrefix}.*") == true)
                                            {
                                                tMetricThing.PB[metricName] = prop.Value;
                                            }
                                        }
                                        if (tMetricThing.PB.ContainsKey(tMetric.Key))
                                        {
                                            tMetricThing.PB.Remove(tMetric.Key);
                                        }
                                    }
                                }
                                catch { }
                            }
                        }
                    }

                    foreach (var tMetric in tMetricThing.PB)
                    {
                        string metricName = "";
                        try
                        {
                            var propertyName = tMetric.Key;
                            var metricInfo   = propsIncludedSplit.FirstOrDefault(ps => ps[0] == propertyName);
                            if (metricInfo != null && metricInfo.Length > 1)
                            {
                                metricName = metricInfo[1];
                            }
                            else
                            {
                                metricName = GetValidLabelName(tMetric.Key);
                            }

                            var valueToReport = GetMetricValue(tMetric.Value);
                            if (senderThing.ChangeNaNToNull && valueToReport == 0) //CM: closest reuse of disable sending of null/0
                            {
                                continue;
                            }
                            var labels = GetMetricLabels(senderThing, propertyName, metricName);

                            switch (senderThing.TargetType?.ToLowerInvariant())
                            {
                            case "counter":
                            {
                                var counter = myCountersByMetricName.GetOrAdd(metricName,
                                                                              (s) =>
                                    {
                                        Prometheus.Counter cs;
                                        try
                                        {
                                            cs = Metrics.CreateCounter(s, "", labels);
                                            return(cs);
                                        }
                                        catch (Exception e)
                                        {
                                            TheBaseAssets.MySYSLOG.WriteToLog(95307, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"Error creating metric {s} in server: {this.MyBaseThing?.Address}", eMsgLevel.l1_Error, e.ToString()));
                                        }
                                        return(null);
                                    });
                                if (counter != null)
                                {
                                    if (counter.LabelNames.Length > 0)
                                    {
                                        var labelValues  = GetLabelValues(tThing, counter.LabelNames);
                                        var labelCounter = counter.Labels(labelValues);
                                        var valueInc     = valueToReport - labelCounter.Value;
                                        if (valueInc > 0)
                                        {
                                            labelCounter.Inc(valueInc);
                                        }
                                        else if (valueInc < 0)
                                        {
                                            TheBaseAssets.MySYSLOG.WriteToLog(95307, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(strPrometheusExporter, $"Error reporting metric {metricName} in '{this.MyBaseThing?.Address} {this.MyBaseThing}'. Counter value {valueToReport} smaller than reported {labelCounter.Value}", eMsgLevel.l1_Error));
                                        }
                                    }
                                    else
                                    {
                                        counter.Inc(valueToReport - counter.Value);
                                    }
                                }
                            }
                            break;

                            case null:
                            case "":
                            case "gauge":
                            {
                                var gauge = myGaugesByMetricName.GetOrAdd(metricName, (s) => Metrics.CreateGauge(s, "", labels));
                                if (gauge != null)
                                {
                                    if (gauge.LabelNames.Length > 0)
                                    {
                                        var labelValues = GetLabelValues(tThing, gauge.LabelNames);
                                        gauge.Labels(labelValues).Set(valueToReport);
                                    }
                                    else
                                    {
                                        gauge.Set(valueToReport);
                                    }
                                }
                            }
                            break;

                            case "histogram":
                            {
                                var histogram = myHistogramsByMetricName.GetOrAdd(metricName, (s) => Metrics.CreateHistogram(s, "", GetHistogramBuckets(senderThing, propertyName, metricName, labels)));
                                if (histogram != null)
                                {
                                    if (histogram.LabelNames.Length > 0)
                                    {
                                        var labelValues = GetLabelValues(tThing, histogram.LabelNames);
                                        histogram.Labels(labelValues).Observe(valueToReport);
                                    }
                                    else
                                    {
                                        histogram.Observe(valueToReport);
                                    }
                                }
                            }
                            break;

                            case "summary":
                            {
                                var summary = mySummariesByMetricName.GetOrAdd(metricName, (s) => Metrics.CreateSummary(s, "", labels));
                                if (summary != null)
                                {
                                    if (summary.LabelNames.Length > 0)
                                    {
                                        var labelValues = GetLabelValues(tThing, summary.LabelNames);
                                        summary.Labels(labelValues).Observe(valueToReport);
                                    }
                                    else
                                    {
                                        summary.Observe(valueToReport);
                                    }
                                }
                            }
                            break;

                            default:
                                TheBaseAssets.MySYSLOG.WriteToLog(95307, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"Unexpected metric type in server: {this.MyBaseThing?.Address}", eMsgLevel.l1_Error, senderThing.TargetType));
                                break;
                            }
                        }
                        catch (Exception e)
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(95307, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"Error reporting metric {metricName} in server: {this.MyBaseThing?.Address}", eMsgLevel.l1_Error, e.ToString()));
                        }
                    }
                }
            }
        }
示例#20
0
        private static async Task GetThingPipelineConfigurationRecursiveAsync(TheThing tThing, bool bGeneralize, List <TheThingConfiguration> pipelineConfig, List <TheThing> thingsVisited)
        {
            if (tThing == null || thingsVisited.Contains(tThing))
            {
                return;
            }

            thingsVisited.Add(tThing);

            var thingConfig = await tThing.GetThingConfigurationAsync(bGeneralize, true);

            if (thingConfig == null)
            {
                return;
            }

            if (thingConfig.ConfigurationValues != null)
            {
                var thingReferencesFromProperties = thingConfig.ConfigurationValues.Where(cv => cv.IsThingReference == true);
                foreach (var thingReferenceProps in thingReferencesFromProperties)
                {
                    // This is sub optimal: inside GetThingConfiguratioAsync we already have the thing. Export is not perf sensitive so doing it this way instead of restructuring the code
                    var tReferencedThing = TheThingRegistry.GetThingByMID(TheCommonUtils.CGuid(thingReferenceProps.Value), true);
                    if (tReferencedThing == null)
                    {
                        try
                        {
                            var tThingReference = TheCommonUtils.DeserializeJSONStringToObject <TheThingReference>(TheCommonUtils.CStr(thingReferenceProps.Value));
                            tReferencedThing = tThingReference?.GetMatchingThing();
                        }
                        catch { }
                    }
                    if (tReferencedThing != null)
                    {
                        await GetThingPipelineConfigurationRecursiveAsync(tReferencedThing, bGeneralize, pipelineConfig, thingsVisited);
                    }
                }
            }
            if (thingConfig.SensorSubscriptions != null)
            {
                var sensorTargetThings = thingConfig.SensorSubscriptions.SelectMany(sub => sub.TargetThing.GetMatchingThings()).Distinct();
                // Find any things into which this provider is sending sensor data
                foreach (var sensorTargetThing in sensorTargetThings)
                {
                    if (sensorTargetThing != null)
                    {
                        await GetThingPipelineConfigurationRecursiveAsync(sensorTargetThing, bGeneralize, pipelineConfig, thingsVisited);
                    }
                }
            }

            if (thingConfig.ThingSubscriptions != null)
            {
                // Find any things that this consumer gets data from
                var consumedThings = thingConfig.ThingSubscriptions.SelectMany(sub => sub.ThingReference.GetMatchingThings()).Distinct().ToList();
                foreach (var consumedThing in consumedThings)
                {
                    if (consumedThing != null)
                    {
                        await GetThingPipelineConfigurationRecursiveAsync(consumedThing, bGeneralize, pipelineConfig, thingsVisited);
                    }
                }
            }

            if (thingConfig.ThingReferences != null)
            {
                // Find any things that this thing declares to have a reference to
                var referencedThings = thingConfig.ThingReferences.SelectMany(thingRef => thingRef.GetMatchingThings()).Distinct().ToList();
                foreach (var referencedThing in referencedThings)
                {
                    if (referencedThing != null)
                    {
                        await GetThingPipelineConfigurationRecursiveAsync(referencedThing, bGeneralize, pipelineConfig, thingsVisited);
                    }
                }
            }

            // Add this thing after any things it depends on (and that it needs to be created before it gets created)
            pipelineConfig.Add(thingConfig);
            // Subsequent things depend on this thing


            // Find things that consumer data from this thing

            // First find any history consumers (more efficient)
            var historyConsumers = tThing.Historian?.GetConsumerRegistrations();

            if (historyConsumers != null)
            {
                foreach (var historyConsumer in historyConsumers)
                {
                    if (historyConsumer.OwnerThing != null)
                    {
                        await GetThingPipelineConfigurationRecursiveAsync(historyConsumer.OwnerThing, bGeneralize, pipelineConfig, thingsVisited);
                    }
                }
            }

            // Enumerate all consumers and find the ones that subscribe to this thing
            foreach (var consumerThing in TheThingRegistry.GetBaseEnginesByCap(eThingCaps.SensorConsumer).SelectMany(eng => TheThingRegistry.GetThingsOfEngine(eng.GetEngineName(), eThingCaps.SensorConsumer).Where(thing => !thingsVisited.Contains(thing))))
            {
                var thingSubscriptionResponse = await consumerThing.GetThingSubscriptionsAsync(new MsgGetThingSubscriptions { Generalize = bGeneralize });

                if (thingSubscriptionResponse != null && string.IsNullOrEmpty(thingSubscriptionResponse.Error))
                {
                    foreach (var thingConsumed in thingSubscriptionResponse.ThingSubscriptions.SelectMany(sub => sub.ThingReference.GetMatchingThings()).Where(thingConsumed => thingConsumed == tThing))
                    {
                        await GetThingPipelineConfigurationRecursiveAsync(consumerThing, bGeneralize, pipelineConfig, thingsVisited);
                    }
                }
                else
                {
                    // TODO should we fail the export? Log it? Report the error(s) to the caller?
                }
            }

            // Find any provider things that provide data into a sensor property in this thing
            var sensorProperties = tThing.GetSensorPropertyMetaData();

            if (sensorProperties?.Any() == true)
            {
                var providerThings = sensorProperties.Select(sensorProp => sensorProp.ProviderInfo.Provider).Distinct().ToList();
                foreach (var providerThing in providerThings)
                {
                    if (providerThing != null && !thingsVisited.Contains(providerThing))
                    {
                        await GetThingPipelineConfigurationRecursiveAsync(providerThing, bGeneralize, pipelineConfig, thingsVisited);
                    }
                }
            }
        }
        /// <summary>
        /// sinkThingApiInterceptor - Called when our URL is referenced.
        /// </summary>
        /// <param name="pRequest"></param>
        public void sinkThingApiInterceptor(TheRequestData pRequest)
        {
            string[] astrURLPath = pRequest.cdeRealPage.Split(new char[1] {
                '/'
            }, StringSplitOptions.RemoveEmptyEntries);
            bool bHandled = false;

            if (astrURLPath.Length > 1)
            {
                Dictionary <string, string> aParameters = new Dictionary <string, string>();
                ParseQueryParameters(pRequest.RequestUri.Query, aParameters);

                string strEngineContext   = astrURLPath[1];
                string strThingContext    = (astrURLPath.Length < 3) ? "" : astrURLPath[2];
                string strPropertyContext = (astrURLPath.Length < 4) ? "" : astrURLPath[3];
                string strPropertyName    = (astrURLPath.Length < 5) ? "" : astrURLPath[4];

                // Login is only user action that does not require a login key.
                if (strEngineContext.StartsWith("Login"))
                {
                    // Is user logging in?
                    //
                    // Sample URL:
                    //     http://c-labs-paul-yao-laptop:8700/ThingApi/Login?User=paul&Pwd=yao
                    //
                    // Sample Return value:
                    //     "a6221f63-c88c-4aa1-8a83-b0fd18a6811e"
                    ValidateUserCredentials(pRequest, astrURLPath, aParameters);
                    bHandled = true;
                }
                else if (IsTokenValid(aParameters))
                {
                    if (strEngineContext.StartsWith("Engines"))
                    {
                        // Is user enumerating engines?
                        //
                        // Sample URL:
                        //     http://c-labs-paul-yao-laptop:8700/ThingApi/Engines?key=a6221f63-c88c-4aa1-8a83-b0fd18a6811e
                        //
                        // Sample Return value:
                        //     ["NMIService.TheNMIHtml5RT","NMIService","ThingService","CDMyThingInspector.cdePluginService1","ContentService"]

                        List <string> listEngines = TheThingRegistry.GetEngineNames(true);
                        pRequest.ResponseMimeType = "application/json";
                        string strJson = TheCommonUtils.SerializeObjectToJSONString <List <string> >(listEngines);
                        pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array(strJson);
                        pRequest.StatusCode     = (int)eHttpStatusCode.OK;
                        pRequest.DontCompress   = true;
                        pRequest.AllowStatePush = false;
                        bHandled = true;
                    }
                    else
                    {
                        // Is user performing a query on a specific engine?
                        //
                        // Sample URL:
                        //     http://c-labs-paul-yao-laptop:8700/ThingApi/NMIService/Things?key=a6221f63-c88c-4aa1-8a83-b0fd18a6811e
                        //
                        // Sample Return value:
                        //     ["b0710f68-5d0f-4e00-93ea-b32c1a5a40c7", "d7bec9f2-4dbc-4119-97e0-f34ed09e5ae1"]
                        //
                        // Sample URL to get all things for all engines:
                        //     http://c-labs-paul-yao-laptop:8700/ThingApi/*/Things?key=a6221f63-c88c-4aa1-8a83-b0fd18a6811e
                        //
                        bool bEngineFound = IsValidEngine(strEngineContext);
                        if (bEngineFound)
                        {
                            if (!String.IsNullOrEmpty(strThingContext))
                            {
                                if (strThingContext == "Things")
                                {
                                    // Enumerate available things for this engine.
                                    List <TheThing> listThings       = TheThingRegistry.GetThingsOfEngine(strEngineContext);
                                    List <string>   listReturnValues = new List <string>();
                                    foreach (TheThing t in listThings)
                                    {
                                        listReturnValues.Add(t.cdeMID.ToString());
                                    }

                                    pRequest.ResponseMimeType = "application/json";
                                    string strJson = TheCommonUtils.SerializeObjectToJSONString <List <string> >(listReturnValues);
                                    pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array(strJson);
                                    pRequest.StatusCode     = (int)eHttpStatusCode.OK;
                                    pRequest.DontCompress   = true;
                                    pRequest.AllowStatePush = false;
                                    bHandled = true;
                                }
                                else
                                {
                                    // Is user performing a query on all of the properties of a specific thing?
                                    //
                                    // Sample URL:
                                    //     http://c-labs-paul-yao-laptop:8700/ThingApi/*/b0710f68-5d0f-4e00-93ea-b32c1a5a40c7/Properties?key=a6221f63-c88c-4aa1-8a83-b0fd18a6811e
                                    //
                                    // Sample Return value:
                                    //     ["Id", "Value", "FriendlyName"]
                                    //
                                    // Sample URL to get all things for all engines:
                                    //     http://c-labs-paul-yao-laptop:8700/ThingApi/*/Things?key=a6221f63-c88c-4aa1-8a83-b0fd18a6811e
                                    //
                                    // Value is Guid for a specific thing
                                    List <TheThing> listThings       = TheThingRegistry.GetThingsOfEngine(strEngineContext);
                                    List <string>   listReturnValues = new List <string>();
                                    foreach (TheThing t in listThings)
                                    {
                                        if (strThingContext == t.cdeMID.ToString())
                                        {
                                            if (strPropertyContext == "Properties")
                                            {
                                                // Enumerate all properties for the thing.

                                                bHandled = true;
                                            }
                                            else if (strPropertyContext == "Property")
                                            {
                                                // Act on an individual property

                                                bHandled = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (!bHandled)
            {
                ResponseNotImplemented(pRequest);
            }
        }
示例#22
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
        }
示例#23
0
        private IEnumerable <TheThing> GetMatchingThings(Subscription subscription)
        {
            var things = new List <TheThing>();

            if (_thingReference.ThingMID.HasValue && _thingReference.ThingMID != Guid.Empty)
            {
                var thing = TheThingRegistry.GetThingByMID(_thingReference.ThingMID.Value, true);
                if (thing != null)
                {
                    things.Add(thing);
                }
                return(things);
            }

            IBaseEngine     baseEngine     = null;
            List <TheThing> matchingThings = null;

            if (!string.IsNullOrEmpty(_thingReference.EngineName))
            {
                baseEngine = TheThingRegistry.GetBaseEngine(_thingReference.EngineName);
                if (baseEngine == null)
                {
                    TheCDEngines.RegisterNewMiniRelay(_thingReference.EngineName);
                    baseEngine = TheThingRegistry.GetBaseEngine(_thingReference.EngineName);
                }
                if (baseEngine != null)
                {
                    subscription?.AddSubscription(baseEngine, this);
                    matchingThings = TheThingRegistry.GetThingsOfEngine(_thingReference.EngineName, true, true);
                }
            }
            else
            {
                object deviceTypeObj = null;
                if (_thingReference.PropertiesToMatch?.TryGetValue("DeviceType", out deviceTypeObj) == true)
                {
                    var deviceType = TheCommonUtils.CStr(deviceTypeObj);
                    if (!string.IsNullOrEmpty(deviceType))
                    {
                        matchingThings = TheThingRegistry.GetThingsByFunc("*", t => t.DeviceType.Equals(deviceType, StringComparison.Ordinal), true);
                    }
                }
            }

            if (matchingThings != null)
            {
                foreach (var thing in matchingThings)
                {
                    if (Matches(thing))
                    {
                        if (baseEngine == null)
                        {
                            subscription?.AddSubscription(thing.GetBaseEngine(), this);
                        }
                        things.Add(thing);
                    }
                }
            }

            return(things);
        }