Exemple #1
0
        private void CreateRule(string pFriendlyName, TheThing pTriggerThing, string pTriggerProperty, eRuleTrigger pTriggerCondition, string pTriggerValue, bool pDoLogRule, bool bIsRuleActive)
        {
            TriggerStartTime = DateTimeOffset.MinValue;
            TriggerEndTime   = DateTimeOffset.MaxValue;

            //TriggerObjectType = "CDE_THING";
            TriggerObject = pTriggerThing.cdeMID.ToString();
            if (!TheCommonUtils.IsNullOrWhiteSpace(pTriggerProperty))
            {
                TriggerProperty = pTriggerProperty;
            }
            else
            {
                pTriggerProperty = "Value";
            }
            TriggerCondition = pTriggerCondition;
            TriggerValue     = pTriggerValue;


            FriendlyName = pFriendlyName;
            IsRuleLogged = pDoLogRule;
            IsRuleActive = bIsRuleActive;

            if (string.IsNullOrEmpty(MyBaseThing.EngineName))
            {
                MyBaseThing.EngineName = eEngineName.ThingService;
            }
            MyBaseThing.DeviceType = eKnownDeviceTypes.TheThingRule;
            MyBaseThing.ID         = MyBaseThing.cdeMID.ToString();
            RegisterEvent("RuleFired", null);
            MyBaseThing.SetIThingObject(this);
        }
        private static void SendGlobalThings(Guid targetNodeId)
        {
            // Do not send more often than every 60 seconds
            if (lastGlobalThingSendPerNode.TryGetValue(targetNodeId, out thingSendStatus timeAndPending))
            {
                if (DateTimeOffset.Now.Subtract(timeAndPending.lastSend).TotalSeconds < 59) // && !timeAndPending.Pending)
                {
                    return;
                }
            }
            var globalThings = TheThingRegistry.GetThingsByFunc("*", (t) => TheThing.GetSafePropertyBool(t, "IsRegisteredGlobally") && t.IsOnLocalNode());

            if (globalThings != null)
            {
                TSM tTSM = new TSM(eEngineName.ContentService, "CDE_SYNC_THINGS", TheCommonUtils.SerializeObjectToJSONString(globalThings));
                tTSM.SetToServiceOnly(true);
                if (targetNodeId == Guid.Empty)
                {
                    TheCommCore.PublishCentral(tTSM);
                }
                else
                {
                    TheCommCore.PublishToNode(targetNodeId, tTSM);
                }
                lastGlobalThingSendPerNode[targetNodeId] = new thingSendStatus {
                    lastSend = DateTimeOffset.Now, Pending = false
                };
            }
        }
Exemple #3
0
 public ConsumerRegistration(TheThing tThing, Guid token, TheHistoryParameters param) : base(param)
 {
     Token      = token;
     cdeMID     = token;
     ThingMid   = tThing.cdeMID;
     LastAccess = DateTimeOffset.Now;
 }
Exemple #4
0
 internal TheThing GetThing()
 {
     if (_thing == null)
     {
         _thing = TheThingRegistry.GetThingByMID(ThingMid, true);
     }
     return(_thing);
 }
Exemple #5
0
        public TheThingRule(Guid pKey, string pFriendlyName, TheThing pTriggerThing, string pTriggerValue, bool pDoLogRule, bool bIsRuleActive)
        {
            if (pTriggerThing == null)
            {
                return;
            }
            MyBaseThing = new TheThing()
            {
                cdeMID = pKey
            };

            CreateRule(pFriendlyName, pTriggerThing, null, eRuleTrigger.Equals, pTriggerValue, pDoLogRule, bIsRuleActive);
        }
Exemple #6
0
        public TheThingRule(Guid pKey, string pFriendlyName, TheThing pTriggerThing, string pTriggerProperty, eRuleTrigger pTriggerCondition, string pTriggerValue, bool pDoLogRule, bool bIsRuleActive)
        {
            if (pTriggerThing == null)
            {
                return;
            }
            MyBaseThing = new TheThing()
            {
                cdeMID = pKey
            };

            CreateRule(pFriendlyName, pTriggerThing, pTriggerProperty, pTriggerCondition, pTriggerValue, pDoLogRule, bIsRuleActive);
        }
Exemple #7
0
        internal static ConsumerRegistration Create <T>(TheThing tThing, Guid token, TheHistoryParameters registrationParameters, TheStorageMirror <T> store) where T : TheDataBase, INotifyPropertyChanged, new()
        {
            ConsumerRegistration registration;

            if (registrationParameters.MaintainHistoryStore)
            {
                registration = new TheStorageMirrorHistorian.ConsumerRegistrationWithStore <T>(tThing, token, registrationParameters, store);
            }
            else
            {
                registration = new ConsumerRegistration(tThing, token, registrationParameters);
            }
            return(registration);
        }
Exemple #8
0
        public TheThingRule(TheThing pBaseThing)
        {
            if (pBaseThing == null)
            {
                pBaseThing = new TheThing();
            }
            MyBaseThing = pBaseThing;

            TriggerStartTime = DateTimeOffset.MinValue;
            TriggerEndTime   = DateTimeOffset.MaxValue;

            if (string.IsNullOrEmpty(MyBaseThing.EngineName))
            {
                MyBaseThing.EngineName = eEngineName.ThingService;
            }
            MyBaseThing.DeviceType = eKnownDeviceTypes.TheThingRule;
            MyBaseThing.ID         = MyBaseThing.cdeMID.ToString();
            RegisterEvent("RuleFired", null);
            MyBaseThing.SetIThingObject(this);
        }
Exemple #9
0
 public TheProviderInfo(TheThing providerThing, TheThing.TheSensorSubscription subscription)
 {
     Provider     = providerThing;
     Subscription = subscription;
 }
        /// <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;
            }
        }
Exemple #11
0
 public override bool Init()
 {
     TT.SetSafePropertyNumber(MyBaseThing, "ManufacturingCarbonFootprint", 0.001); //1KG if not specified
     TheCDEngines.RegisterNewMiniRelay("EnergyMessages");
     return(base.Init());
 }
Exemple #12
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);
                    }
                }
            }
        }