static TimeSpan MaxTimeOut = new TimeSpan(1, 0, 0); // TODO Add to TheBaseAssets and make configurable?

        private static TSM PrepareRequestMessage(TheMessageAddress originator, TheMessageAddress target, string messageName, Guid correlationToken, string[] txtParameters, string PLS, byte[] PLB)
        {
            var parameterText = CreateParameterText(txtParameters);

            if (parameterText == null)
            {
                return(null);
            }

            TSM msg = new TSM(target.EngineName, String.Format("{0}:{1}:{2}", messageName, TheCommonUtils.cdeGuidToString(correlationToken), parameterText), PLS);

            if (PLB != null)
            {
                msg.PLB = PLB;
            }
            if (originator.ThingMID != Guid.Empty)
            {
                msg.SetOriginatorThing(originator.ThingMID);
            }
            if (target.ThingMID != Guid.Empty)
            {
                msg.OWN = TheCommonUtils.cdeGuidToString(target.ThingMID);
            }
            if (!string.IsNullOrEmpty(target.Route))
            {
                msg.GRO = target.Route;
            }
            return(msg);
        }
        internal static List <TheThreadInfo> GetThreadInfo()
        {
            List <TheThreadInfo> tList = new List <TheThreadInfo>();

#if CDE_STANDARD //No Thread Name Diagnostics
#else
            try
            {
                int cid = NativeMethods.GetCurrentThreadId();
                foreach (ProcessThread pt in Process.GetCurrentProcess().Threads)
                {
                    TheThreadInfo t = new TheThreadInfo()
                    {
                        Priority = PriorityToString(pt.CurrentPriority),
                        ID       = pt.Id
                    };
                    if (t.ID < MAX_IDS)
                    {
                        t.Name = MyThreadNames[t.ID];
                        //t.StackFrame = MyThreadStacks[t.ID];
                        if (t.ID == cid)
                        {
                            t.Name = "GETTHREADINFO";
                        }
                        else
                        {
                            if (MyThreadStacks[t.ID] != null)
                            {
                                t.IsBackground = MyThreadStacks[t.ID].IsBackground;
                                t.IsPooled     = MyThreadStacks[t.ID].IsThreadPoolThread;
#pragma warning disable CS0618 // System.Diagnostics.StrackTrace requires the thread to be suspended
                                MyThreadStacks[t.ID].Suspend();
                                t.StackFrame = TheCommonUtils.GetStackInfo(new System.Diagnostics.StackTrace(MyThreadStacks[t.ID], true));
                                MyThreadStacks[t.ID].Resume();
#pragma warning restore CS0618
                            }
                        }
                    }
                    t.CoreTimeInMs = pt.PrivilegedProcessorTime.TotalMilliseconds;
                    t.State        = ThreadStateToString(pt.ThreadState);
                    t.UserTimeInMs = pt.UserProcessorTime.TotalMilliseconds;
                    if (ThreadState.Wait != pt.ThreadState)
                    {
                        t.WaitReason = "Not Waiting";
                    }
                    else
                    {
                        t.WaitReason = ThreadWaitReasonToString(pt.WaitReason);
                    }
                    t.StartTime = pt.StartTime;
                    tList.Add(t);
                }
            }
            catch (Exception e)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(999, new TSM("Diagnostics", "Thread Diagnostics Failed", eMsgLevel.l1_Error, e.ToString()));
            }
#endif
            return(tList);
        }
Exemple #3
0
        private void SetCtrlType()
        {
            if (CountBar == null)
            {
                return;
            }
            string     tControl  = ThePropertyBag.PropBagGetValue(CountBar.PropertyBag, "ControlType", "=");
            eFieldType tCtrlType = eFieldType.SingleEnded;

            if (!string.IsNullOrEmpty(tControl) && TheCommonUtils.CInt(tControl) == 0 && tControl.Length > 0)
            {
                TheControlType tType = TheNMIEngine.GetControlTypeByType(tControl);
                if (tType != null)
                {
                    ThePropertyBag.PropBagUpdateValue(CountBar.PropertyBag, "EngineName", "=", tType.BaseEngineName);
                }
                tCtrlType = eFieldType.UserControl;
            }
            else
            {
                tCtrlType = (eFieldType)TheCommonUtils.CInt(tControl);
            }
            CountBar.Type        = tCtrlType;
            CountBar.Flags       = TheCommonUtils.CInt(ThePropertyBag.PropBagGetValue(CountBar.PropertyBag, "Flags", "="));
            CountBar.PropertyBag = new TheNMIBaseControl {
                ParentFld = 1
            };
            CountBar.UpdateUXProperties(Guid.Empty);
            CountBar.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "click", (sener, para) => {
                TheThing.SetSafePropertyBool(MyBaseThing, "ClickState", !TheThing.GetSafePropertyBool(MyBaseThing, "ClickState"));
            });
        }
Exemple #4
0
        private void SetCtrlType()
        {
            if (MySampleControl == null)
            {
                return;
            }
            string     tControl  = ThePropertyBag.PropBagGetValue(MySampleControl.PropertyBag, "ControlType", "=");
            eFieldType tCtrlType = eFieldType.SingleEnded;

            if (!string.IsNullOrEmpty(tControl) && TheCommonUtils.CInt(tControl) == 0 && tControl.Length > 0)
            {
                TheControlType tType = TheNMIEngine.GetControlTypeByType(tControl);
                if (tType != null)
                {
                    ThePropertyBag.PropBagUpdateValue(MySampleControl.PropertyBag, "EngineName", "=", tType.BaseEngineName);
                }
                tCtrlType = eFieldType.UserControl;
            }
            else
            {
                tCtrlType = (eFieldType)TheCommonUtils.CInt(tControl);
            }
            MySampleControl.Type  = tCtrlType;
            MySampleControl.Flags = TheCommonUtils.CInt(ThePropertyBag.PropBagGetValue(MySampleControl.PropertyBag, "Flags", "="));
            MySampleControl.UpdateUXProperties(Guid.Empty);
        }
Exemple #5
0
        private void OnDownloadClick(ICDEThing pThing, object pPara)
        {
            TheProcessMessage pMSG = pPara as TheProcessMessage;

            if (pMSG == null || pMSG.Message == null)
            {
                return;
            }

            string[] cmd = pMSG.Message.PLS.Split(':');
            if (cmd.Length > 2)
            {
                TheThing tThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(cmd[2]), true);
                if (tThing == null)
                {
                    return;
                }

                TSM tFilePush = new TSM(eEngineName.ContentService, string.Format("CDE_FILE:{0}.JSON:application/zip", tThing.FriendlyName))
                {
                    SID = pMSG.Message.SID,
                    PLS = "bin",
                    PLB = TheCommonUtils.CUTF8String2Array(TheCommonUtils.SerializeObjectToJSONString(tThing))
                };
                TheCommCore.PublishToOriginator(pMSG.Message, tFilePush);
            }
        }
Exemple #6
0
        bool ProcessCDEngine(TheUPnPDeviceInfo tHistory, Uri tLocationUrl)
        {
            if ((tLocationUrl.Host.Equals(TheBaseAssets.MyServiceHostInfo.MyStationIP) && tLocationUrl.Port == TheBaseAssets.MyServiceHostInfo.MyStationPort) || !tHistory.PacketString.Contains(TheBaseAssets.MyServiceHostInfo.ApplicationName) || tLocationUrl.Host.Contains("127.0.0.1"))
            {
                return(true);
            }
            TheBaseAssets.MySYSLOG.WriteToLog(111, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("UPnP", string.Format("C-DEngine Root Device Found: {0}", tHistory), eMsgLevel.l7_HostDebugMessage));
            if (!TheBaseAssets.MyServiceHostInfo.DisableUPnPAutoConnect && TheBaseAssets.MyServiceHostInfo.ApplicationName.Equals(tHistory.ModelName))
            {
                if (!string.IsNullOrEmpty(tHistory.CDEContextID))
                {
                    if (!string.IsNullOrEmpty(tHistory.CDEProvisionUrl))
                    {
                        TheBaseAssets.MySettings.SetSetting("AutoProvisioningUrl", tHistory.CDEProvisionUrl);
                    }
                    if (!TheBaseAssets.MyScopeManager.IsScopingEnabled ||
                        (TheBaseAssets.MyScopeManager.IsScopingEnabled && !TheBaseAssets.MyScopeManager.ScopeID.Equals(TheBaseAssets.MyScopeManager.GetRealScopeID(tHistory.CDEContextID))))    //GRSI: rare
                    {
                        return(false);
                    }
                }
                else
                {
                    if (TheBaseAssets.MyScopeManager.IsScopingEnabled || !TheBaseAssets.MyServiceHostInfo.AllowUnscopedMesh)
                    {
                        return(false);
                    }
                }

                if (!TheCommonUtils.DoesContainLocalhost(tHistory.CDEConnectUrl) && !TheCommonUtils.DoesContainLocalhost(tHistory.CDEConnectWsUrl))
                {
                    string strStationRoles = tHistory.FriendlyName;
                    int    pos             = strStationRoles.LastIndexOf(':') + 1;
                    if (!string.IsNullOrEmpty(strStationRoles) && pos >= 0)
                    {
                        strStationRoles = strStationRoles.Substring(pos, strStationRoles.Length - pos);
                        string[]      sRoles = strStationRoles.Split(';');
                        List <string> discoveredStationRoles = new List <string>();
                        foreach (string gt in sRoles)
                        {
                            discoveredStationRoles.Add(TheBaseAssets.MyScopeManager.AddScopeID(gt));
                        }
                        string[] apps    = TheCommonUtils.cdeSplit(tHistory.FriendlyName, " at:", false, false);
                        string   appName = "Unknown App"; if (apps != null && apps.Length > 0)
                        {
                            appName = apps[0].Trim();
                        }
                        string tConnectUrl = tHistory.CDEConnectUrl;
                        if (!string.IsNullOrEmpty(tHistory.CDEConnectWsUrl))
                        {
                            tConnectUrl = tHistory.CDEConnectWsUrl;
                        }
                        TheBaseAssets.MySYSLOG.WriteToLog(112, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("UPnP", $"Compatible Service Found: {tHistory.FriendlyName} {tHistory.Manufacturer} {tHistory.ModelName} {tHistory.ModelNumber} {tHistory.SerialNumber} {tConnectUrl}", eMsgLevel.l7_HostDebugMessage));
                        eventWSDMatchFound?.Invoke(tHistory.CDENodeID, tConnectUrl, discoveredStationRoles);
                        TheBaseAssets.MySYSLOG.WriteToLog(113, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("UPnP", "New " + appName + " Station found at: " + tConnectUrl, eMsgLevel.l3_ImportantMessage));
                    }
                }
            }
            return(true);
        }
Exemple #7
0
        public void ScanKnownDevices(string pUid)
        {
            if (pUid == null)
            {
                return;
            }

            if ((pUid.Equals("*") && mUPnpUIDs[pUid] == null) || MyUPnPDiscoveryPast?.MyMirrorCache == null)
            {
                return;
            }
            foreach (TheUPnPDeviceInfo tHistory in MyUPnPDiscoveryPast.MyMirrorCache.TheValues)
            {
                string[] stParts = TheCommonUtils.cdeSplit(pUid, ";:;", true, true);
                if (stParts.Length == 1)
                {
                    if (pUid == "*" || tHistory?.ST?.ToUpper().Contains(pUid.ToUpper()) == true)
                    {
                        mUPnpUIDs[pUid]?.Invoke(tHistory);
                    }
                }
                else
                {
                    if (CompareUPnPField(tHistory, stParts[0], stParts[1]))
                    {
                        mUPnpUIDs[pUid]?.Invoke(tHistory);
                    }
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// Handles Messages sent from a host sub-engine to its clients
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="pIncoming"></param>
        public override void HandleMessage(ICDEThing sender, object pIncoming)
        {
            TheProcessMessage pMsg = pIncoming as TheProcessMessage;

            if (pMsg == null)
            {
                return;
            }

            string[] cmd = pMsg.Message.TXT.Split(':');
            switch (cmd[0])
            {
            case "CDE_INITIALIZED":
                MyBaseEngine.SetInitialized(pMsg.Message);
                break;

            case "GET_CHARTDATA":
                Type td = typeof(CDMyC3.TheC3ChartsFactory);
                TheChartFactory.PushChartsData(TheCommonUtils.CGuid(pMsg.Message.PLS), pMsg.Message.GetOriginator(), td.AssemblyQualifiedName);
                break;

            default:
                break;
            }
        }
Exemple #9
0
        public override bool CreateUX()
        {
            if (!mIsUXInitCalled)
            {
                mIsUXInitCalled = true;
                TheNMIEngine.RegisterControlType(MyBaseEngine, "C3 Chart", "CDMyC3.ctrlC3Chart", "CDMyC3.ctrlC3Chart");
                TheNMIEngine.RegisterControlType(MyBaseEngine, "Time Line Chart", "CDMyC3.ctrlTimeLineChart", "CDMyC3.ctrlTimeLineChart");
                TheNMIEngine.RegisterControlType(MyBaseEngine, "Live Chart", "CDMyC3.ctrlProLiveChart");
                TheNMIEngine.RegisterControlType(MyBaseEngine, "Stack Chart", "CDMyC3.ctrlC3StackChart");
                TheNMIEngine.RegisterControlType(MyBaseEngine, "Cyto Chart", "CDMyC3.ctrlProCytoChart");
                TheNMIEngine.RegisterControlType(MyBaseEngine, "Line Chart", "CDMyC3.ctrlC3Line");
                //NUI Definition for All clients

                if (TheCommonUtils.CBool(TheBaseAssets.MySettings.GetSetting("ShowSamples")))
                {
                    mMyDashboard = TheNMIEngine.AddDashboard(MyBaseThing, new TheDashboardInfo(MyBaseEngine, "C3 Charts")
                    {
                        FldOrder = 7010, PropertyBag = new ThePropertyBag()
                        {
                            "Category=NMI Extensions", "HideShowAll=true", "Caption=<span style='font-size:64px'>C3</span><br>Charts"
                        }
                    });
                    TheFormInfo tMyForm = TheNMIEngine.AddForm(new TheFormInfo(MyBaseThing)
                    {
                        FormTitle = "C3 Samples Page", DefaultView = eDefaultView.Form
                    });
                    TheNMIEngine.AddFormToThingUX(MyBaseThing, tMyForm, "CMyForm", "My Sample Form", 3, 3, 0, TheNMIEngine.GetNodeForCategory(), null, null);

                    TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.CollapsibleGroup, 10, 2, 0, "Value Tester", null, new nmiCtrlCollapsibleGroup {
                        TileWidth = 6, ClassName = "AXGroup", IsSmall = true
                    });
                    TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.SingleEnded, 11, 2, 0, "My Sample Value Is", "SampleProperty", new nmiCtrlSingleEnded {
                        ParentFld = 10
                    });
                    TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.BarChart, 12, 2, 0, "My Sample Value Bar", "SampleProperty", new nmiCtrlBarChart()
                    {
                        ParentFld = 10, MaxValue = 255, TileHeight = 2
                    });

                    //TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.CollapsibleGroup, 29, 2, 0, "Pie Demo", null, new nmiCtrlCollapsibleGroup { /*TileHeight = 5, */TileWidth = 6, ClassName = "AXGroup", IsSmall = true });
                    //TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.UserControl, 30, 2, 0, "My Pie", "SampleProperty", new ctrlC3Chart { ChartType="pie", UpdateData = true, NoTE = true, ParentFld = 29, TileHeight = 4, TileWidth = 6, SetSeries = "[[\"Dogs\", 100],[\"Cats\", 20],[\"Birds\", 34]]" });

                    //TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.CollapsibleGroup, 34, 2, 0, "Pie Demo", null, new nmiCtrlCollapsibleGroup { /*TileHeight = 5, */TileWidth = 6, ClassName = "AXGroup", IsSmall = true });
                    //TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.UserControl, 35, 2, 0, "My Gauge", "SampleProperty", new ctrlC3Chart { ChartType="gauge", UpdateData = true, TileHeight = 4, ParentFld = 34, MaxValue = 255, TileWidth = 6, SetSeries = "[[\"Dogs\", 100]]" });

                    TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.CollapsibleGroup, 39, 2, 0, "Chart Demo", null, new nmiCtrlCollapsibleGroup { /*TileHeight = 5, */
                        TileWidth = 12, ClassName = "AXGroup", IsSmall = true
                    });
                    ctrlC3Chart.AddC3Chart(MyBaseThing, tMyForm, 50, 39, true, new ctrlC3Chart {
                        NoTE = true, TileHeight = 4, ParentFld = 39, ChartType = "bar", TileWidth = 12, SetSeries = "[[\"Dogs\", 100],[\"Cats\", 20],[\"Birds\", 34]]", Group = "[[\"Dogs\", \"Cats\"]]"
                    });

                    TheNMIEngine.AddAboutButton(MyBaseThing);
                }

                TheNMIEngine.RegisterEngine(MyBaseEngine);
                mIsUXInitialized = true;
            }
            return(true);
        }
Exemple #10
0
        public void CollectInformation()
        {
            try
            {
                var nodeInfo = new CdeNodeInfo(_hostInfo);

                var targetDir = Path.Combine(_hostInfo.FileSystemUserBasePath, "diagnostics");
                if (!Directory.Exists(targetDir))
                {
                    Directory.CreateDirectory(targetDir);
                }

                var file       = $"CdeServiceHost_{_hostInfo.Id}.json";
                var targetFile = Path.Combine(targetDir, file);
                if (File.Exists(targetFile))
                {
                    File.Delete(targetFile);
                }

                var serializedInfo = TheCommonUtils.SerializeObjectToJSONString(nodeInfo);
                File.WriteAllText(targetFile, serializedInfo);
            }
            catch (Exception ex)
            {
                _log.LogError(ex, $"Failed to collect and save service host diagnostic information!");
            }
        }
Exemple #11
0
        private void sinkOnNewTraceFile(object sender, FileSystemEventArgs e)
        {
            TheCDEKPIs.IncrementKPI(eKPINames.IISRejectedClientConnections);
            // Log any other necessary KPIs here
            if (!DisableWriteToSYSLOG)
            {
                var    failedReqInfo = ReadIISFailedReqTrace(e.FullPath);
                string errorMsg      = "IIS Failed Request: ";
                errorMsg += failedReqInfo.Verb != null ? $"{failedReqInfo.Verb} request " : "Request ";
                errorMsg += failedReqInfo.RequestURL != null ? $"on {failedReqInfo.RequestURL} " : "";
                errorMsg += failedReqInfo.ClientIP != null ? $"by {failedReqInfo.ClientIP} " : "";
                errorMsg += failedReqInfo.StatusCode != null ? $"returned code {failedReqInfo.StatusCode} " : "returned ";
                errorMsg += failedReqInfo.TimeTaken != null ? $"in {failedReqInfo.TimeTaken} ms " : "";
                errorMsg += failedReqInfo.ErrorCode != null ? $"- {failedReqInfo.ErrorCode}" : "";

                try
                {
                    // For now, just discard any messages if queue has hit its capacity
                    if (queuedErrorMessages.Count < queuedErrorMessages.BoundedCapacity)
                    {
                        TheCommonUtils.cdeRunTaskAsync("QueueIISError" + errorCount, (o) =>
                        {
                            queuedErrorMessages.TryAdd(errorMsg, bcTimeOutSeconds * 1000, TheBaseAssets.MasterSwitchCancelationToken);
                        });
                    }
                }
                catch (Exception) { }
            }
        }
 internal static string CreateCDEX(TheServicesMarketPlace tPlace, string tMetaFile, bool bForce, out string tCDEXFilePath)
 {
     tCDEXFilePath = null;
     try
     {
         tPlace.FileName = string.Format(CultureInfo.InvariantCulture, "{1} V{0:0.0000}.CDEX", tPlace.CurrentVersion, tPlace.ServiceName.Replace('.', '-'));
         string tTarget = Path.Combine(tMetaFile, tPlace.FileName);
         tCDEXFilePath = tTarget;
         if (!bForce && File.Exists(tTarget) && !TheCommonUtils.CBool(TheBaseAssets.MySettings.GetSetting("AlwaysCreateCDEXOnStartup")))
         {
             return("Target Exists");
         }
         TheCommonUtils.CreateDirectories(tTarget);
         if (File.Exists(tTarget))
         {
             File.Delete(tTarget);
         }
         System.IO.Compression.ZipFile.CreateFromDirectory(tMetaFile + "new", tTarget, System.IO.Compression.CompressionLevel.Optimal, false);
         FileInfo f = new FileInfo(tTarget);
         tPlace.Size = f.Length;
         Directory.Delete(tMetaFile + "new", true);
     }
     catch (Exception e)
     {
         return($"Plugin {tPlace.ServiceName} with ID:{tPlace.PluginID} could not be created: {e}");
     }
     return(null);
 }
        public override bool Init()
        {
            if (!mIsInitCalled)
            {
                mIsInitCalled           = true;
                MyBaseThing.StatusLevel = 4;
                SetMessage("Service has started", DateTimeOffset.Now);

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

                // If not lengthy initialized you can remove cdeRunasync and call this synchronously
                TheCommonUtils.cdeRunAsync(MyBaseEngine.GetEngineName() + " Init Services", true, (o) =>
                {
                    // Perform any long-running initialization (i.e. network access, file access) here that must finish before other plug-ins or the C-DEngine can use the plug-in
                    InitServices();

                    // Declare the thing initialized
                    mIsInitialized = true;                                 // For future IsInit() calls
                    FireEvent(eThingEvents.Initialized, this, true, true); // Notify the C-DEngine and other plug-ins that the thing is initialized
                    MyBaseEngine.ProcessInitialized();                     //Set the status of the Base Engine according to the status of the Things it manages
                });
            }
            return(false);
        }
        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);
                }
            });
        }
Exemple #15
0
        public static bool IsTokenValid(Dictionary <string, string> aParameters)
        {
            bool bSuccess = false;

            CleanupOldTokens();

            if (aParameters.TryGetValue("key", out string strToken))
            {
                if (!String.IsNullOrEmpty(strToken))
                {
                    Guid     guidToken = TheCommonUtils.CGuid(strToken);
                    DateTime dt;

                    if (dictValidAccessTokens != null)
                    {
                        if (dictValidAccessTokens.TryGetValue(guidToken, out dt))
                        {
                            bSuccess = true;
                        }
                    }
                }
            }


            return(bSuccess);
        }
        private void sinkEnergyFound(ICDEThing sender, object incoming)
        {
            if (!(incoming is TSM pMessage))
            {
                return;
            }

            if (pMessage.TXT.Equals("NEWENERGYREADING"))
            {
                int pos = pMessage.PLS.IndexOf("\"Watts\":");
                if (pos >= 0)
                {
                    string t    = pMessage.PLS.Substring(pos);
                    int    pos2 = t.IndexOf(",");
                    if (pos2 < 0)
                    {
                        pos2 = t.IndexOf("}");
                    }
                    if (pos2 >= 0)
                    {
                        t = t.Substring("\"Watts\":".Length, pos2 - "\"Watts\":".Length);
                        LastStationWatts = TheCommonUtils.CDbl(t);
                    }
                }
            }
        }
Exemple #17
0
        public override bool Init()
        {
            if (mIsInitCalled)
            {
                return(false);
            }
            mIsInitCalled = true;

            ReqBuffer = new TheMirrorCache <TheRequestData>(0);
            string t = TheCommonUtils.CStr(TheBaseAssets.MySettings.GetSetting("WRA_RequestTimeout"));

            if (!string.IsNullOrEmpty(t))
            {
                RequestTimeout = TheCommonUtils.CInt(t);
            }
            if (RequestTimeout < 15)
            {
                RequestTimeout = 15;
            }

            InitServices();

            TheCommCore.MyHttpService.RegisterHttpInterceptorB4("/", InterceptHttpRequest);
            TheScopeManager.RegisterScopeChanged(sinkScopeIDUpdate);
            MyBaseThing.RegisterEvent(eEngineEvents.IncomingMessage, HandleMessage);

            mIsInitialized = true;
            MyBaseEngine.ProcessInitialized();
            return(true);
        }
        public void IncomingMessageEventTest()
        {
            var    contentServiceThing = TheThingRegistry.GetBaseEngineAsThing(eEngineName.ContentService);
            var    contentServiceEng   = contentServiceThing.GetBaseEngine();
            int    numberOfMessages    = 0;
            string txt     = "TEST_TXT";
            string payload = "TestPayload";
            TSM    testMsg = new TSM(eEngineName.ContentService, txt, payload);

            contentServiceEng?.RegisterEvent(eEngineEvents.IncomingMessage, (t, o) =>
            {
                numberOfMessages++;
                if (o is TheProcessMessage msg)
                {
                    Assert.AreEqual(msg.Message.TXT, txt);
                    Assert.AreEqual(msg.Message.PLS, payload);
                    Assert.AreEqual(msg.Message.ENG, contentServiceEng.GetEngineName());
                    testMsg.PLS = "TestPayload2";
                    //Assert.AreNotEqual(msg.Message.PLS, testMsg.PLS); // This fails
                }
                if (t is ICDEThing thing)
                {
                    Assert.AreEqual(thing.GetBaseThing().cdeMID, contentServiceThing.cdeMID);
                }
            });
            TheCommCore.PublishCentral(testMsg, true);
            TheCommonUtils.SleepOneEye(5000, 1000);
            Assert.AreEqual(numberOfMessages, 1);
        }
Exemple #19
0
        private void sinkDeviceExpired(TheUPnPDeviceInfo tHistory)
        {
            foreach (string tUID in mUPnpLost.Keys)
            {
                if (mUPnpLost[tUID] == null)
                {
                    continue;
                }

                if (tUID.Equals("*"))
                {
                    mUPnpLost[tUID](tHistory);
                }
                else
                {
                    string[] stParts = TheCommonUtils.cdeSplit(tUID, ";:;", true, true);
                    if (stParts.Length == 1)
                    {
                        if (tUID == "*" || tHistory?.ST?.ToUpper().Contains(tUID.ToUpper()) == true)
                        {
                            mUPnpLost[tUID](tHistory);
                        }
                    }
                    else
                    {
                        if (CompareUPnPField(tHistory, stParts[0], stParts[1]))
                        {
                            mUPnpLost[tUID](tHistory);
                        }
                    }
                }
            }
        }
Exemple #20
0
 // Override if new properties in a derived class need to be considered in the comparison
 internal virtual bool IsEqual(TheSenderThing senderThingToAdd)
 {
     return
         (senderThingToAdd != null
          //&& cdeMID == senderThingToAdd.cdeMID
          && ChangeBufferLatency == senderThingToAdd.ChangeBufferLatency &&
          ChangeBufferTimeBucketSize == senderThingToAdd.ChangeBufferTimeBucketSize &&
          ChangeNaNToNull == senderThingToAdd.ChangeNaNToNull &&
          Disable == senderThingToAdd.Disable &&
          PartitionKey == senderThingToAdd.PartitionKey &&
          EventFormat == senderThingToAdd.EventFormat &&
          StaticProperties == senderThingToAdd.StaticProperties &&
          AddThingIdentity == senderThingToAdd.AddThingIdentity &&
          TheCommonUtils.CGuid(ThingMID) == TheCommonUtils.CGuid(senderThingToAdd.ThingMID) &&
          PropertiesIncluded == senderThingToAdd.PropertiesIncluded &&
          PropertiesExcluded == senderThingToAdd.PropertiesExcluded &&
          (ForceAllProperties ?? false) == (senderThingToAdd.ForceAllProperties ?? false) &&
          (ForceConfigProperties ?? false) == (senderThingToAdd.ForceConfigProperties ?? false) &&
          PreserveOrder == senderThingToAdd.PreserveOrder &&
          SendUnchangedValue == senderThingToAdd.SendUnchangedValue &&
          (SendInitialValues ?? false) == (senderThingToAdd.SendInitialValues ?? false) &&
          (IgnoreExistingHistory ?? false) == (senderThingToAdd.IgnoreExistingHistory ?? false) &&
          TokenExpirationInHours == senderThingToAdd.TokenExpirationInHours &&
          KeepDurableHistory == senderThingToAdd.KeepDurableHistory &&
          MaxHistoryCount == senderThingToAdd.MaxHistoryCount &&
          MaxHistoryTime == senderThingToAdd.MaxHistoryTime &&
          IgnorePartialFailure == senderThingToAdd.IgnorePartialFailure &&
          EngineName == senderThingToAdd.EngineName &&
          FriendlyName == senderThingToAdd.FriendlyName &&
          DeviceType == senderThingToAdd.DeviceType &&
          PropertiesToMatch == senderThingToAdd.PropertiesToMatch &&
          ContinueMatching == senderThingToAdd.ContinueMatching
         );
 }
        IEnumerable <JSonOpcArrayElement> GetJSONArray(TheThingStore thingEvent)
        {
            // TODO Replace with linkid some identifier that represents the activated instance/customer, and make this more efficient (avoid or cache thing registry lookup)
            string linkid;
            var    tThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(thingEvent.cdeMID), true);

            if (tThing != null && !String.IsNullOrEmpty(tThing.FriendlyName))
            {
                linkid = tThing.FriendlyName;
            }
            else
            {
                if (thingEvent.PB.ContainsKey("Address"))
                {
                    linkid = TheCommonUtils.CStr(thingEvent.PB["Address"]);
                }
                else
                {
                    if (tThing != null)
                    {
                        linkid = tThing.Address;
                    }
                    else
                    {
                        linkid = TheCommonUtils.cdeGuidToString(thingEvent.cdeMID);
                    }
                }
            }

            var jsonArray = new List <JSonOpcArrayElement>();

            jsonArray.AddRange(thingEvent.PB.Select(propKV => GetJSONArrayElement(linkid, propKV.Key, thingEvent.cdeCTIM, propKV.Value)));
            return(jsonArray.OrderBy(ev => ev.sourcetimestamp));
        }
Exemple #22
0
 public static void CreateEvtLogFeed(TheRequestData pRequest, List <TheEventLogData> pLogData, int MaxCnt)
 {
     if (pRequest.RequestUri != null && !string.IsNullOrEmpty(pRequest.RequestUri.Query) && pRequest.RequestUri.Query.Length > 1)
     {
         var QParts = TheCommonUtils.ParseQueryString(pRequest.RequestUri.Query); //.Split('=');
         //if (QParts.ContainsKey("SID") && (!TheScopeManager.IsValidScopeID(TheScopeManager.GetScrambledScopeIDFromEasyID(QParts["SID"])) || QParts.ContainsKey("NID")))
         //{
         //    pRequest.SessionState.SScopeID = TheScopeManager.GetScrambledScopeIDFromEasyID(QParts["SID"]);
         //    Guid tTarget = Guid.Empty;
         //    if (QParts.ContainsKey("NID"))
         //        tTarget = TheCommonUtils.CGuid(QParts["NID"]);
         //    TheHttpService.cdeStreamFile(pRequest, true, 300, tTarget);
         //    if (pRequest.ResponseBuffer == null)
         //        TheRSSGenerator.CreateRSS(pRequest, new List<TheEventLogData>() { new TheEventLogData() { EventName = "Relay did not answer" } }, 1);
         //    return;
         //}
     }
     if (pLogData != null)
     {
         TheRSSGenerator.CreateRSS(pRequest, pLogData, 200);
     }
     else
     {
         TheRSSGenerator.CreateRSS(pRequest, new List <TheEventLogData>()
         {
             new TheEventLogData()
             {
                 EventName = "No Eventlog on this Node"
             }
         }, 1);
     }
 }
Exemple #23
0
        private void UpdateUx(TheThing pThing)
        {
            ThePropertyBag.MergeUXBagFromProperties(MySampleControl?.PropertyBag, pThing);
            SetCtrlType();

            TheThingRegistry.UnmapPropertyMapper(MapperGuid);
            if (!string.IsNullOrEmpty(pThing.Address))
            {
                MapperGuid = TheThingRegistry.PropertyMapper(TheCommonUtils.CGuid(pThing.Address), TheThing.GetSafePropertyString(pThing, "SourceProp"), pThing.cdeMID, "Value", true);
                if (MapperGuid != Guid.Empty)
                {
                    pThing.StatusLevel = 1;
                    pThing.LastMessage = "Mapper engaged";
                }
                else
                {
                    pThing.StatusLevel = 2;
                    pThing.LastMessage = "Mapper failed to engaged";
                }
            }
            else
            {
                pThing.StatusLevel = 0;
                pThing.LastMessage = "Mapper not engaged";
            }
        }
        bool Connect(TheProcessMessage pMsg)
        {
            bool bSuccess = false;

            try
            {
                MyBaseThing.StatusLevel = 4; // ReaderThread will set statuslevel to 1
                foreach (var field in MyModFieldStore.TheValues)
                {
                    var p = MyBaseThing.GetProperty(field.PropertyName, true);
                    p.cdeM = "MODPROP";
                    p.UnregisterEvent(eThingEvents.PropertyChangedByUX, null);
                    p.RegisterEvent(eThingEvents.PropertyChangedByUX, sinkPChanged);
                }
                SetupModbusProperties(true, pMsg);
                IsConnected             = true;
                MyBaseThing.LastMessage = $"{DateTime.Now} - Device Connecting";
                TheBaseAssets.MySYSLOG.WriteToLog(10000, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseThing.EngineName, MyBaseThing.LastMessage, eMsgLevel.l4_Message));
                TheCommonUtils.cdeRunAsync($"ModRunThread{MyBaseThing.FriendlyName}", true, (o) =>
                {
                    ReaderThread();
                });
                bSuccess = true;
            }
            catch (Exception e)
            {
                MyBaseThing.StatusLevel = 3;
                string error = $"Error connecting: {e.Message}";
                MyBaseThing.LastMessage = $"{DateTimeOffset.Now}: {error}";
                TheBaseAssets.MySYSLOG.WriteToLog(10000, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, error, eMsgLevel.l1_Error, e.ToString()));
                IsConnected = false;
            }
            return(bSuccess);
        }
Exemple #25
0
        private async void OnWatchDogTimer(object state)
        {
            try
            {
                OnSendAttempt(null);
                var timeSinceLastAttempt = DateTimeOffset.Now - LastSendAttemptTime;
                if (timeSinceLastAttempt > new TimeSpan(0, 0, WatchDogIdleRecycleIntervalInMinutes, 0))
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(95014, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"WatchDog: No activity since {LastSendAttemptTime}. Disconnecting Sender and waiting 5 seconds to reconnect.", eMsgLevel.l4_Message));
                    Disconnect(true);
                    try
                    {
                        await TheCommonUtils.TaskDelayOneEye(5000, 100);
                    }
                    catch (TaskCanceledException) { }

                    if (TheBaseAssets.MasterSwitch)
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(95015, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"WatchDog: Reconnecting Sender.", eMsgLevel.l4_Message));
                        Connect();
                    }
                }
            }
            catch (Exception ex)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(95302, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"WatchDog: Internal error.", eMsgLevel.l1_Error, ex.ToString()));
            }
        }
        void SetupModbusProperties(bool bReload, TheProcessMessage pMsg)
        {
            if (MyModConnectForm != null)
            {
                List <TheFieldInfo> tLst = TheNMIEngine.GetFieldsByFunc(s => s.FormID == MyModConnectForm.cdeMID);
                foreach (TheFieldInfo tInfo in tLst)
                {
                    if (tInfo.FldOrder >= 600 && TheCommonUtils.CInt(tInfo.PropBagGetValue("ParentFld")) == 500)
                    {
                        TheNMIEngine.DeleteFieldById(tInfo.cdeMID);
                    }
                }

                List <cdeP> props  = MyBaseThing.GetPropertiesMetaStartingWith("MODPROP");
                int         fldCnt = 600;
                foreach (var p in props)
                {
                    var field = MyModFieldStore.MyMirrorCache.GetEntryByFunc(s => s.PropertyName == p.Name);
                    if (field != null)
                    {
                        TheNMIEngine.AddSmartControl(MyBaseThing, MyModConnectForm, eFieldType.SingleEnded, fldCnt++, field.AllowWrite ? 2 : 0, 0, p.Name, p.Name, new nmiCtrlSingleEnded()
                        {
                            TileWidth = 6, ParentFld = 500
                        });
                    }
                }
                MyModConnectForm.Reload(pMsg, bReload);
            }
        }
Exemple #27
0
        public static bool Init(string strGuid, string strUserScopeID, string strAppID)
        {
            TheScopeManager.SetApplicationID(strAppID); // SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS!

            TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application)
            {
                ApplicationName  = "$safeprojectname$",                            // Friendly Name of Application
                cdeMID           = TheCommonUtils.CGuid(strGuid),
                Title            = "My-Relay (C) $registeredorganization$ $year$", // Title of this Host Service
                ApplicationTitle = "$safeprojectname$",                            // Title visible in the NMI Portal
                CurrentVersion   = 1.0001,                                         // Version of this Service, increase this number when you publish a new version that the store displays the correct update icon
                DebugLevel       = eDEBUG_LEVELS.OFF,                              // Define a DebugLevel for the SystemLog output.
                SiteName         = "http://cloud.c-labs.com",                      // Link to the main Cloud Node of this host. this is not required and for documentation only

                ISMMainExecutable = "$safeprojectname$",                           // Name of the executable (without .exe)
                IgnoreAdminCheck  = true,                                          // if set to true, the host will not start if launched without admin priviledges.

                LocalServiceRoute = "LOCALHOST",                                   // Will be replaced by the full DNS name of the host during startup.
                MyStationPort     = 8700,                                          // Port for REST access to this Host node. If your PC already uses port 80 for another webserver, change this port. We recommend using Port 8700 and higher for UPnP to work properly.
                MyStationWSPort   = 8701,                                          // Enables WebSockets on the station port. If UseRandomDeviceID is false, this Value cannot be changed here once the App runs for the first time. On Windows 8 and higher running under "Adminitrator" you can use the same port
            };

            if (strUserScopeID.Length > 0)
            {
                strScopeID = strUserScopeID;
            }
            else
            {
                strScopeID = TheScopeManager.GenerateNewScopeID();  // TIP: instead of creating a new random ID every time your host starts, you can put a breakpoint in the next line, record the ID and feed it in the "SetScopeIDFromEasyID". Or even set a fixed ScopeID here. (FOR TESTING ONLY!!)
            }
            return(true);
        }
        public void ExecuteSimulation()
        {
            try
            {
                var timestamp = DateTimeOffset.Now;

                var dict = new Dictionary <string, object>();
                dict["Timestamp"] = timestamp;

                foreach (var field in MyModFieldStore.TheValues)
                {
                    double rndVal = TheCommonUtils.GetRandomDouble() * 1000.0;
                    if (field.SourceType == "double")
                    {
                        dict[field.PropertyName] = rndVal;
                    }
                    else if (field.SourceType == "float")
                    {
                        dict[field.PropertyName] = rndVal;
                    }
                }
                MyBaseThing.SetProperties(dict, timestamp);
            }
            catch (Exception)
            {
                // Console.WriteLine("Ignoring exception: " + ex.Message);
                //Console.WriteLine(ex.StackTrace);
            }
        }
Exemple #29
0
        private void UpdateUx()
        {
            ThePropertyBag.MergeUXBagFromProperties(CountBar?.PropertyBag, MyBaseThing);
            SetCtrlType();

            if (TimestampField != null)
            {
                TimestampField?.SetUXProperty(Guid.Empty, $"Visibility={ShowTimestamp}");
                ChangeTimestampField?.SetUXProperty(Guid.Empty, $"Visibility={ShowChangeTimestamp}");
            }

            TheThingRegistry.UnmapPropertyMapper(MapperGuid);
            if (!string.IsNullOrEmpty(MyBaseThing.Address))
            {
                MapperGuid = TheThingRegistry.PropertyMapper(TheCommonUtils.CGuid(MyBaseThing.Address), TheThing.GetSafePropertyString(MyBaseThing, "SourceProp"), MyBaseThing.cdeMID, "Value", true);
                if (MapperGuid != Guid.Empty)
                {
                    MyBaseThing.StatusLevel = 1;
                    MyBaseThing.LastMessage = "Mapper engaged";
                }
                else
                {
                    MyBaseThing.StatusLevel = 2;
                    MyBaseThing.LastMessage = "Mapper failed to engaged";
                }
            }
            else
            {
                MyBaseThing.StatusLevel = 0;
                MyBaseThing.LastMessage = "Mapper not engaged";
            }
        }
        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
                };
            }
        }