public void IncomingMessage2EventTest()
        {
            var    contentServiceThing = TheThingRegistry.GetBaseEngineAsThing(eEngineName.ContentService);
            var    contentServiceEng   = contentServiceThing.GetBaseEngine();
            int    numberOfMessages    = 0;
            string txt     = "CDE_GET_SERVICEINFO";
            string payload = "CHNL";
            TSM    testMsg = new TSM(eEngineName.ContentService, txt, payload);

            contentServiceThing?.RegisterEvent(eEngineEvents.IncomingEngineMessage, (t, o) =>
            {
                // Two messages should be received here - The first intercepts the CDE_GET_SERVICEINFO
                // The second intercepts the CDE_SERVICEINFO response (since originator Thing was set to ContentService)
                numberOfMessages++;
            });
            testMsg.SetOriginatorThing(contentServiceThing);
            TheCommCore.PublishCentral(testMsg, true);
            TheCommonUtils.SleepOneEye(5000, 1000);
            Assert.AreEqual(numberOfMessages, 2);
        }
示例#2
0
        public void SendHealthInfo(Guid pOrg)
        {
            GetISMHealthData();
            TSM tMsg = new TSM(MyEngineName, "ISMHEALTH", TheCommonUtils.SerializeObjectToJSONString <TheServiceHealthData>(MyHealthData));

            if (!TheBaseAssets.MyServiceHostInfo.IsCloudService) //Cloud would send unscoped Message going nowhere!
            {
                tMsg.SetNoDuplicates(true);
                if (pOrg == Guid.Empty)
                {
                    TheCommCore.PublishCentral(MyEngineName, tMsg);
                }
                else
                {
                    TheCommCore.PublishToNode(pOrg, tMsg);
                }
            }
            eventNewHealthData?.Invoke(MyHealthData);
            TheBaseAssets.MySYSLOG.WriteToLog(8004, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : tMsg);
        }
        void sinkFileReceived(ICDEThing pThing, object pFileName)
        {
            TheProcessMessage pMsg = pFileName as TheProcessMessage;

            if (pMsg?.Message == null)
            {
                return;
            }
            try
            {
                string tGuid = $"THH{Guid.NewGuid()}";
                //File.Copy(TheCommonUtils.cdeFixupFileName(pMsg.Message.TXT), TheCommonUtils.cdeFixupFileName($"/cache/{tGuid}"));
                CreateTHHUx(tGuid, TheCommonUtils.cdeFixupFileName(pMsg.Message.TXT));
                TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", string.Format("KPI File ({0}) received - Creating UX", pMsg.Message.TXT)));
                MyPCVitalsDashboard.Reload(pMsg, true);
            }
            catch (Exception)
            {
                TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_ERROR", $"KPI File ({pMsg.Message.TXT}) received but creating UX failed!"));
            }
        }
示例#4
0
        static void sinkReady()
        {
            Debug.WriteLine("Registering events for engine... ");

            TheCDEngines.MyContentEngine.RegisterEvent(eEngineEvents.IncomingMessage, sinkIncoming);
            if (TheCDEngines.MyNMIService != null)
            {
                TheCDEngines.MyNMIService.RegisterEvent(eEngineEvents.IncomingMessage, sinkIncoming);
                //TheCDEngines.MyContentEngine.RegisterEvent(eEngineEvents.ChannelConnected, sinkEstablished);
            }
            TheCommonUtils.cdeRunAsync("LoopDiDoop", true, (o) =>
            {
                TheThing tTimer    = null;
                TheThing GoogleDNS = null;
                TheThing ThingBar  = null;
                while (TheBaseAssets.MasterSwitch)
                {
                    TheCommonUtils.SleepOneEye(5000, 100);

                    if (ThingBar == null)
                    {
                        ThingBar = TheThingRegistry.GetThingByProperty("*", Guid.Empty, "FriendlyName", "ThingBar");
                        if (ThingBar != null)
                        {
                            TheThingRegistry.RegisterEventOfThing(ThingBar, eThingEvents.ValueChanged, (sender, para) =>
                            {
                                TSM tTSM2 = new TSM(eEngineName.ContentService, "UNITY:GAUGE", para.ToString());
                                TheCommCore.PublishCentral(tTSM2);
                            });
                        }
                    }
                    if (tTimer == null)
                    {
                        tTimer = TheThingRegistry.GetThingByProperty("*", Guid.Empty, "DeviceType", "Timer");
                        if (tTimer != null)
                        {
                            TheThingRegistry.RegisterEventOfThing(tTimer, eThingEvents.ValueChanged, (sender, para) =>
                            {
                                TSM tTSM2 = new TSM(eEngineName.ContentService, "UNITY:TIMER", para.ToString());
                                TheCommCore.PublishCentral(tTSM2);
                            });
                        }
                    }
                    if (GoogleDNS == null)
                    {
                        GoogleDNS = TheThingRegistry.GetThingByProperty("*", Guid.Empty, "FriendlyName", "Google DNS");
                        if (GoogleDNS != null)
                        {
                            TheThingRegistry.RegisterEventOfThing(GoogleDNS, eThingEvents.PropertyChanged, (sender, para) =>
                            {
                                cdeP tP = para as cdeP;
                                if (tP != null && tP.Name == "RoundTripTime")
                                {
                                    TSM tTSM2 = new TSM(eEngineName.ContentService, "UNITY:HEART", para.ToString());
                                    TheCommCore.PublishCentral(tTSM2);
                                }
                            });
                        }
                    }
                    if (GoogleDNS != null && tTimer != null && ThingBar != null)
                    {
                        break;
                    }
                }
            });
        }
示例#5
0
        private void CreateConfigurationSection(int writeEnableFlag, TheFormInfo tMyForm, int pStartFld, int pParentFld)
        {
            UseTree = TheCommonUtils.CBool(TheBaseAssets.MySettings.GetSetting("UseTreeView"));

            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.CollapsibleGroup, pStartFld, 2, 0xc0, "Tag Management...", null, ThePropertyBag.Create(new nmiCtrlCollapsibleGroup()
            {
                DoClose = !UseTree, IsSmall = true, ParentFld = pParentFld, TileWidth = UseTree ? 18 : 6
            }));

            if (!UseTree)
            {
                TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.SingleEnded, pStartFld + 1, writeEnableFlag, 0xC0, "Browse Branch", "BrowseBranch", new nmiCtrlSingleEnded()
                {
                    ParentFld = pStartFld
                });
            }
#if USE_WEBIX
            else
            {
                var stringCols = TheCommonUtils.SerializeObjectToJSONString(new List <TheWXColumn> {
                    { new TheWXColumn()
                      {
                          TileWidth = 6, Header = "Node Name", ID = "DisplayName", FilterType = "textFilter", Template = "{common.treetable()}{common.treecheckbox()}&nbsp;<strong>#DisplayName#</strong>"
                      } },
                    //{ new TheWXColumn() { TileWidth = 2, Header = "Host Property", ID = "HostPropertyNameOverride", SortType = "string", Flags=2 } },
                    { new TheWXColumn()
                      {
                          TileWidth = 1, Header = "Sample-Rate", ID = "SampleRate", SortType = "int", Flags = 2
                      } },
                    { new TheWXColumn()
                      {
                          TileWidth = 1, Header = "Deadband-Filter", ID = "DeadbandFilterValue", SortType = "int", Flags = 2
                      } },
                    { new TheWXColumn()
                      {
                          TileWidth = 1, Header = "Trigger", ID = "ChangeTrigger", SortType = "int", Flags = 2
                      } },
                    { new TheWXColumn()
                      {
                          TileWidth = 6, Header = "Node ID", ID = "NodeIdName", FilterType = "textFilter", SortType = "int"
                      } }
                });

                OpcTagTree = TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.UserControl, pStartFld + 6, 2, 0, "Sample Tree", "SelectedIs", new nmiCtrlWXTreeTable()
                {
                    ParentFld       = pStartFld,
                    TileWidth       = 12,
                    TileHeight      = 12,
                    NoTE            = true,
                    RootNode        = "Objects",
                    TreeNode        = "Parent",
                    NameNode        = "DisplayName",
                    SelectNode      = "HasActiveHostThing",
                    LeftSplit       = 1,
                    OpenAllBranches = false,
                    SplitCharacter  = ".",
                    Columns         = stringCols
                });
                OpcTagTree.RegisterEvent2("NMI_FIELD_EVENT", (pMSG, para) => {
                    var tUpdate = TheCommonUtils.DeserializeJSONStringToObject <TheWXFieldEvent>(pMSG.Message.PLS);
                    if (tUpdate != null)
                    {
                        var MyTag = MyTags.MyMirrorCache.GetEntryByID(tUpdate.cdeMID);
                        if (MyTag != null)
                        {
                            switch (tUpdate.Name)
                            {
                            case "SampleRate":
                                MyTag.SampleRate = TheCommonUtils.CInt(tUpdate.Value);
                                break;

                            case "DeadbandFilterValue":
                                MyTag.DeadbandFilterValue = TheCommonUtils.CDbl(tUpdate.Value);
                                break;

                            case "ChangeTrigger":
                                MyTag.ChangeTrigger = TheCommonUtils.CInt(tUpdate.Value);
                                break;
                            }
                        }
                    }
                });
            }
#endif

            // BROWSE Button
            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.TileButton, pStartFld + 2, writeEnableFlag, 0xC0, "Browse", null, new nmiCtrlTileButton()
            {
                ParentFld = pStartFld, ClassName = "cdeGoodActionButton", TileWidth = 3, NoTE = true
            })
            .RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "BROWSE", (pThing, pObj) =>
            {
                TheProcessMessage pMsg = pObj as TheProcessMessage;
                if (pMsg == null || pMsg.Message == null)
                {
                    return;
                }
                if (ConnectionState != ConnectionStateEnum.Connected)
                {
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Server not connected - please connect first"));
                }
                else
                {
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Browsing..."));
                    LastMessage   = "Browsing Started at " + DateTimeOffset.Now.ToString();
                    BrowsedTagCnt = 0;
                    Browser(currentRoot, currentRoot.ToString(), true, false, null);


                    var dataModelJson = TheCommonUtils.SerializeObjectToJSONString(
                        MyTags.MyMirrorCache.TheValues
                        .Where(t => t.HostPropertyNameOverride?.Contains("].[") != true)     // Filter out any DataValue sub-properties (i.e. engineering units), as the tree view doesn't seem to handle nodes under leaf-nodes (or inner nodes with data) yet
                        .ToList());
                    OpcTagTree?.SetUXProperty(pMsg.Message.GetOriginator(), $"DataModel={dataModelJson}", true);
                    LastMessage += " - Browsing done at " + DateTimeOffset.Now.ToString();
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", LastMessage));
                }
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.Number, pStartFld + 3, 0, 0x0, "Browsed Tags:", "BrowsedTagCnt", new nmiCtrlNumber()
            {
                ParentFld = pStartFld, TileWidth = 3
            });


            ///Browsed TAGS Form
            {
                var tDataSource = "TheOPCTags";
                if (MyTags != null)
                {
                    tDataSource = MyTags.StoreMID.ToString();
                }
                var tOPCTagForm = new TheFormInfo(TheThing.GetSafeThingGuid(MyBaseThing, "TAGLIST_ID"), eEngineName.NMIService, "OPC-UA Server Tags", $"{tDataSource};:;1000")
                {
                    IsNotAutoLoading = true, AddButtonText = "Add new Tag", PropertyBag = new nmiCtrlTableView {
                        ShowFilterField = true
                    }
                };
                TheNMIEngine.AddFormToThingUX(MyBaseThing, tOPCTagForm, "CMyTable", "Tag List", 1, 3, 0xF0, null, null, new ThePropertyBag()
                {
                    "Visibility=false"
                });
                TheNMIEngine.AddFields(tOPCTagForm, new List <TheFieldInfo> {
                    // 1: Thing subscription
                    { new TheFieldInfo()
                      {
                          FldOrder = 3, DataItem = "IsSubscribedAsThing", Flags = 0, Type = eFieldType.SingleCheck, Header = "Has Tag Thing", FldWidth = 1
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 11, DataItem = "Parent", Flags = 0, Type = eFieldType.SingleEnded, Header = "Parent", FldWidth = 4
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 12, DataItem = "DisplayName", Flags = 0, Type = eFieldType.SingleEnded, Header = "Name", FldWidth = 3
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 13, DataItem = nameof(TheOPCTag.HostPropertyNameOverride), Flags = writeEnableFlag, Type = eFieldType.SingleEnded, Header = "Host Property Name", FldWidth = 3
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 14, DataItem = "HostThingMID", Flags = writeEnableFlag, Type = eFieldType.ThingPicker, Header = "Host Thing", FldWidth = 3
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 15, DataItem = nameof(TheOPCTag.ChangeTrigger), Flags = writeEnableFlag, Type = eFieldType.ComboBox, Header = "Change Trigger", FldWidth = 1, PropertyBag = new nmiCtrlComboBox {
                              Options = "Status:0;Value:1;Value & Timestamp:2"
                          }
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 16, DataItem = nameof(TheOPCTag.SampleRate), Flags = writeEnableFlag, Type = eFieldType.Number, Header = "Sample Rate (ms)", FldWidth = 1
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 17, DataItem = nameof(TheOPCTag.DeadbandFilterValue), Flags = writeEnableFlag, Type = eFieldType.Number, Header = "Deadband", FldWidth = 1
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 18, DataItem = "NodeIdName", Flags = 2, Type = eFieldType.SingleEnded, Header = "NodeId", FldWidth = 6
                      } },
                    // 30: Property subscription
                    { new TheFieldInfo()
                      {
                          FldOrder = 19, DataItem = nameof(TheOPCTag.HistoryStartTime), Flags = writeEnableFlag, Type = eFieldType.SingleEnded, Header = "History Start", FldWidth = 3
                      } },
                    //{  new TheFieldInfo() { FldOrder=13,DataItem="PropAttr.7.Value.Value",Flags=0,Type=eFieldType.SingleEnded,Header="Value",FldWidth=5 }},
                    //{  new TheFieldInfo() { FldOrder=14,DataItem="PropAttr.7.DataType",Flags=0,Type=eFieldType.SingleEnded,Header="Type",FldWidth=5 }},
                });
                TheNMIEngine.AddTableButtons(tOPCTagForm, false, 100, 0);

                // Button Subscribe as Thing
                TheNMIEngine.AddSmartControl(MyBaseThing, tOPCTagForm, eFieldType.TileButton, 1, writeEnableFlag, 0xC0, "Create Tag Thing", null, new nmiCtrlTileButton()
                {
                    ClassName = "cdeGoodActionButton", TileHeight = 1
                })
                .RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "SUBSCRIBE", (tThing, pMsg) => SubscribeAsThing(tThing, pMsg, MyTags));

                // Button: Subscribe property into host thing
                TheNMIEngine.AddSmartControl(MyBaseThing, tOPCTagForm, eFieldType.TileButton, 5, writeEnableFlag, 0xC0, "Monitor as Property", null, new nmiCtrlTileButton()
                {
                    ClassName = "cdeGoodActionButton", TileHeight = 1
                })
                .RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "SUBSCRIBEPROP", (tThing, pMsg) => SubscribeAsProperty(tThing, pMsg, MyTags));

                TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.TileButton, pStartFld + 4, writeEnableFlag, 0xF0, "Show Tag List", null, new nmiCtrlTileButton()
                {
                    OnClick = $"TTS:{tOPCTagForm.cdeMID}", ParentFld = pStartFld, ClassName = "cdeTransitButton", TileWidth = 3, NoTE = true
                });
            }

            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.Number, pStartFld + 5, writeEnableFlag, 0xC0, "Default Sample Rate", nameof(DefSampleRate), new nmiCtrlNumber()
            {
                ParentFld = pStartFld, TileWidth = 3
            });


            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.ThingPicker, pStartFld + 6, writeEnableFlag, 0xC0, "Thing for Property Subs", "TagHostThingForSubscribeAll", new nmiCtrlThingPicker()
            {
                NoTE = true, ParentFld = pStartFld, TileWidth = 4
            });

            // SUBSCRIBE all tags as Properties
            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.TileButton, pStartFld + 7, writeEnableFlag, 0xC0, $"Subscribe {(UseTree ? "selected" : "all")} in properties", null, new nmiCtrlTileButton()
            {
                ParentFld = pStartFld, ClassName = "cdeGoodActionButton", TileWidth = 2, NoTE = true
            })
            .RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "ALLTAGS", (pThing, pObj) =>
            {
                TheProcessMessage pMsg = pObj as TheProcessMessage;
                if (pMsg == null || pMsg.Message == null)
                {
                    return;
                }
                if (ConnectionState != ConnectionStateEnum.Connected)
                {
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Server not connected - please connect first"));
                }
                else
                {
                    var tHostThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(this.TagHostThingForSubscribeAll));
                    if (tHostThing == null)
                    {
                        TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Host Thing not specified or invalid"));
                        return;
                    }
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Subscribing..."));

                    if (MyTags.MyMirrorCache.Count == 0 && !UseTree)
                    {
                        // Clear all previous subscription in either MyTags (tag as thing) oder HostThing (tag as property)
                        MyTags.MyMirrorCache.Reset();

                        // TODO Figure out how to clean up subscribed things in properties.
                        // - Can't just delete as a customer may have hand picked certain properties via browse paths etc.
                        // - Allow customer to use multiple host things?
                        //var tThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(TagHostThing));
                        //if (tThing != null)
                        //{
                        //    foreach (var prop in tThing.GetPropertiesMetaStartingWith("OPCUA:"))
                        //    {
                        //        tThing.RemoveProperty(prop.Name);
                        //    }
                        //}

                        LastMessage = "Subscribing started at " + DateTimeOffset.Now.ToString();

                        BrowsedTagCnt = 0;

                        Browser(currentRoot, currentRoot.ToString(), true, true, tHostThing, CreateIDFilter());

                        LastMessage += " - Subscribing done at " + DateTimeOffset.Now.ToString();
                        TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", LastMessage));
                    }
                    else
                    {
                        // Previously browsed: use those tags to do the subscriptions
                        LastMessage = "Subscribing started at " + DateTimeOffset.Now.ToString();

                        var subscription = GetOrCreateSubscription(0);
                        var pFilterIDs   = CreateIDFilter();
                        int count        = 0;
                        //var results = new List<Opc.Ua.Client.MonitoredItem>();//CM: removed as Nothing is done with "results"

                        foreach (var tag in MyTags.TheValues)
                        {
                            string tagNameForFilter;
                            if (tag.DisplayName == "EngineeringUnits" || tag.DisplayName == "EURange")
                            {
                                tagNameForFilter = tag.Parent;
                            }
                            else
                            {
                                tagNameForFilter = $"{tag.Parent}.{tag.DisplayName}";
                            }

                            if (pFilterIDs != null && pFilterIDs.Contains(tagNameForFilter))
                            {
                                tag.HostThingMID = TheCommonUtils.cdeGuidToString(tHostThing.cdeMID);
                                var childTags    = tag.GetChildTags();
                                if (childTags?.Any() == true)
                                {
                                    foreach (var childTag in childTags)
                                    {
                                        childTag.HostThingMID = tag.HostThingMID;
                                    }
                                }
                                if (!RegisterAndMonitorTagInHostThing(subscription, tag, out string error, false, true, false) || !string.IsNullOrEmpty(error))
                                {
                                    // error
                                }
        private void ReadHttpPage(TheRequestData pRequest, Guid MyAppGuid, string tMagixc, Action <TheRequestData> pSinkProcessResponse) //TheRelayAppInfo MyApp,
        {
            TheRelayAppInfo MyApp = TheThingRegistry.GetThingObjectByMID(MyBaseEngine.GetEngineName(), MyAppGuid) as TheRelayAppInfo;    // MyRelayApps.MyMirrorCache.GetEntryByFunc(s => s.cdeMID.Equals(MyAppGuid));

            if (MyApp == null)
            {
                if (pRequest.cdeN.Equals(TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID))
                {
                    TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), "WEBRELAY_REQUEST")
                    {
                        PLB = pRequest.PostData
                    };
                    pRequest.PostData       = null;
                    pRequest.ResponseBuffer = null;
                    if (!string.IsNullOrEmpty(pRequest.CookieString))
                    {
                        pRequest.CookieString += ";";
                    }
                    else
                    {
                        pRequest.CookieString = "";
                    }
                    pRequest.CookieString += tMagixc;
                    if (string.IsNullOrEmpty(TheBaseAssets.MyServiceHostInfo.RootDir))
                    {
                        pRequest.RequestUriString = pRequest.RequestUri.ToString();
                    }
                    else
                    {
                        pRequest.RequestUriString = pRequest.RequestUri.Scheme + "://" + pRequest.RequestUri.Host + ":" + pRequest.RequestUri.Port + pRequest.cdeRealPage;
                        if (!string.IsNullOrEmpty(pRequest.RequestUri.Query))
                        {
                            pRequest.RequestUriString += "?" + pRequest.RequestUri.Query;
                        }
                    }
                    TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Requesting Page:{0}", pRequest.RequestUriString), eMsgLevel.l6_Debug));

                    tTSM.PLS = TheCommonUtils.SerializeObjectToJSONString(pRequest);
                    tTSM.SID = pRequest.SessionState.GetSID();
                    TheCommCore.PublishCentral(tTSM); //  .PublishToNode(MyApp.HostUrl, pRequest.SessionState.SScopeID, tTSM);
                }
                return;
            }
            if (TheCommonUtils.IsUrlLocalhost(MyApp.GetBaseThing().Address))
            {
                TheCommonUtils.GetAnyFile(pRequest);
                if (tMagixc != null)
                {
                    pRequest.CookieString = tMagixc;
                }
                pSinkProcessResponse(pRequest);
            }
            else
            {
                int    relPathIndex = pRequest.RequestUri.AbsolutePath.IndexOf('/', 1);
                string relPath      = relPathIndex == -1 ? "" : pRequest.RequestUri.AbsolutePath.Substring(relPathIndex + 1) + pRequest.RequestUri.Query;
                var    tUri         = pRequest.RequestUri.AbsolutePath.StartsWith("/CDEWRA") ? new Uri(MyApp.GetBaseThing().Address + MyApp.HomePage + relPath) : new Uri(MyApp.GetBaseThing().Address.TrimEnd('/') + pRequest.RequestUri.AbsolutePath + pRequest.RequestUri.Query);
                if (!string.IsNullOrEmpty(tMagixc))
                {
                    if (!string.IsNullOrEmpty(pRequest.CookieString))
                    {
                        pRequest.CookieString += ";";
                    }
                    else
                    {
                        pRequest.CookieString = "";
                    }
                    pRequest.CookieString += tMagixc;
                }
                pRequest.RequestUri       = tUri;
                pRequest.ErrorDescription = "";
                pRequest.RequestCookies   = pRequest.SessionState.StateCookies;
                if (!string.IsNullOrEmpty(MyApp.SUID) && !string.IsNullOrEmpty(MyApp.SPWD))
                {
                    pRequest.UID = MyApp.SUID;
                    pRequest.PWD = MyApp.SPWD;
                }
                if (MyApp.IsHTTP10)
                {
                    pRequest.HttpVersion = 1.0;
                }
                if (string.IsNullOrEmpty(MyApp.CloudUrl))
                {
                    MyApp.CloudUrl = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false);
                }
                pRequest.Header = null;
                if (pRequest.PostData != null && pRequest.PostData.Length > 0)      //MONO Relay might not work right!
                {
                    TheREST MyRest = new TheREST();
                    MyRest.PostRESTAsync(pRequest, pSinkProcessResponse, pSinkProcessResponse);
                }
                else
                {
                    TheREST.GetRESTAsync(pRequest, pSinkProcessResponse, pSinkProcessResponse);
                }
                TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Requesting Page:{0} Sent", pRequest.RequestUri), eMsgLevel.l3_ImportantMessage));
            }
        }
示例#7
0
        public override void HandleMessage(ICDEThing sender, object pIncoming)
        {
            TheProcessMessage pMsg = pIncoming as TheProcessMessage;

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

            var cmd = pMsg.Message.TXT.Split(':');

            switch (cmd[0])
            {
            case "CALL_METHOD":
            case nameof(MsgOPCUAMethodCall):
                string error         = "Unexpected";
                string exceptionText = "";

                MsgOPCUAMethodCall callInfo        = null;
                byte[]             largeOutput     = null;
                string             outParamsAsJson = null;
                IList <object>     outputArguments = null;
                if (m_Method == null)
                {
                    error = "Method meta data not initialized";
                }
                else if (m_Method.MyOPCServer == null)
                {
                    error = "Method not inititialized";
                }
                else if (m_Method.MyOPCServer.m_session == null)
                {
                    error = "OPC UA session not created";
                }
                else
                {
                    try
                    {
                        if (TheCommonUtils.cdeIsLocked(m_Method))
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(78401, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM(MyBaseThing.EngineName, String.Format("[{0}] Method called concurrently", m_Method.MyOPCServer.GetLogAddress()), eMsgLevel.l4_Message, String.Format("{0}", MyBaseThing.Address)));
                        }
                        lock (m_Method)
                        {
                            if (m_Method.Args == null)
                            {
                                var browseError = m_Method.MyOPCServer.MethodBrowser(m_Method.TagRef, m_Method.DisplayName, m_Method);
                                if (!string.IsNullOrEmpty(browseError))
                                {
                                    error = "Unable to retrieve method metadata from server: " + browseError;
                                }
                            }
                            if (m_Method.Args == null)
                            {
                                error = "Unable to retrieve method metadata from server";
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(pMsg.Message.PLS))
                                {
                                    if (cmd[0] == nameof(MsgOPCUAMethodCall))
                                    {
                                        callInfo = TheCommRequestResponse.ParseRequestMessageJSON <MsgOPCUAMethodCall>(pMsg.Message);
                                        foreach (var argument in callInfo.Arguments)
                                        {
                                            TheThing.SetSafeProperty(this, argument.Key, argument.Value, ePropertyTypes.NOCHANGE);
                                        }
                                    }
                                    else
                                    {
                                        var tLst = TheCommonUtils.cdeSplit(pMsg.Message.PLS, ":;:", true, true).ToList();
                                        foreach (string t in tLst)
                                        {
                                            TheThing.SetPropertyFromBagItem(this, t);
                                        }
                                    }
                                }
                                object[] tArgs = new object[InputArgCnt];
                                for (int i = 0; i < InputArgCnt; i++)
                                {
                                    tArgs[i] = TheOPCTag.GetOPCValueFromCDEValue(InputArgs[i].cdeProperty == null ? null : InputArgs[i].cdeProperty.Value, InputArgs[i].OPCType);
                                }
#if OLD_UA
                                outputArguments = m_Method.MyOPCServer.m_session.CallWithTimeout(m_Method.ParentId, m_Method.TagRef, MethodCallTimeout, tArgs);
#else
                                outputArguments = m_Method.MyOPCServer.m_session.Call(m_Method.ParentId, m_Method.TagRef, tArgs);     //CM: C-labs extension: .CallWithTimeout(m_Method.ParentId, m_Method.TagRef, MethodCallTimeout, tArgs);
#endif
                                if (cmd[0] != nameof(MsgOPCUAMethodCall))
                                {
                                    if (TheThing.GetSafePropertyBool(this, "ReturnOutputAsJson"))
                                    {
                                        outParamsAsJson = TheCommonUtils.SerializeObjectToJSONString(outputArguments);
                                        //TheThing.SetSafePropertyString(this, "OutputAsJson", outParamsAsJson);
                                    }
                                    else
                                    {
                                        if (outputArguments != null && outputArguments.Count > 0)
                                        {
                                            for (int i = 0; i < outputArguments.Count; i++)
                                            {
                                                if (i < OutputArgs.Count)
                                                {
                                                    object value;
                                                    if (outputArguments[i] is byte[] && (outputArguments[i] as byte[]).Length > 4096 && largeOutput == null)
                                                    {
                                                        largeOutput = outputArguments[i] as byte[];
                                                        value       = "";
                                                    }
                                                    else
                                                    {
                                                        value = outputArguments[i];
                                                    }

                                                    cdeP tP = OutputArgs[i].cdeProperty;
                                                    if (tP != null)
                                                    {
                                                        //TheOPCTag.UpdateValueProperty(outputArguments[i] as DataValue, tP, outputArguments[i] as DataValue);
                                                        tP.Value = value;
                                                        // tP.SetValue(outputArguments[i], pMsg.Message.GetOriginator().ToString()); // CODE REVIEW: Why did we set the originator here? It's only really needed for remote things to break update cycles...
                                                    }
                                                }
                                                else
                                                {
                                                    TheBaseAssets.MySYSLOG.WriteToLog(78402, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM(MyBaseThing.EngineName, String.Format("[{0}] Error processing method response for OPC Server", m_Method.MyOPCServer.GetLogAddress()), eMsgLevel.l2_Warning, String.Format("{0}: too many out parameters in method", MyBaseThing.Address)));
                                                }
                                            }
                                        }
                                    }
                                    MyBaseThing.LastUpdate = DateTimeOffset.Now;
                                    LastMessage            = string.Format("Success at {0}", MyBaseThing.LastUpdate);
                                }
                                error = "";
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        error         = "Method Call failed: " + e.Message;
                        exceptionText = e.ToString();
                        LastMessage   = error;
                        TheBaseAssets.MySYSLOG.WriteToLog(78403, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(MyBaseThing.EngineName, String.Format("[{0}] Method Call failed", m_Method.MyOPCServer.GetLogAddress()), eMsgLevel.l1_Error, String.Format("{0}:{1}", MyBaseThing.Address, e.ToString())));
                    }
                }
                if (cmd[0] == nameof(MsgOPCUAMethodCall))
                {
                    if (callInfo?.ReturnRawJSON == true)
                    {
                        TheCommRequestResponse.PublishResponseMessageJson(pMsg.Message, new MsgOPCUAMethodCallResponse {
                            OutputArguments = new List <object> {
                                TheCommonUtils.SerializeObjectToJSONString(outputArguments)
                            }, Error = error
                        });
                    }
                    else
                    {
                        TheCommRequestResponse.PublishResponseMessageJson(pMsg.Message, new MsgOPCUAMethodCallResponse {
                            OutputArguments = (List <object>)outputArguments, Error = error
                        });
                    }
                }
                else
                {
                    TSM tTSN = new TSM(MyBaseThing.EngineName, string.Format(String.IsNullOrEmpty(error) ? "CALL_METHOD_RESPONSE:{0}:{1}" : "CALL_METHOD_RESPONSE:{0}:{1}:{2}:{3}", MyBaseThing.ID, cmd[1], error.Replace(":", " "), exceptionText.Replace(":", " ")));
                    if (largeOutput != null && String.IsNullOrEmpty(error))
                    {
                        tTSN.PLB = largeOutput;
                    }
                    if (outParamsAsJson != null && String.IsNullOrEmpty(error))
                    {
                        tTSN.PLS = outParamsAsJson;
                    }
                    if (pMsg.LocalCallback != null)
                    {
                        pMsg.LocalCallback(tTSN);
                    }
                    else
                    {
                        TheCommCore.PublishToOriginator(pMsg.Message, tTSN);
                    }
                }
                break;
            }

            base.HandleMessage(this, pMsg);
        }
示例#8
0
        private void sinkHeartBeatTimer(long NOTUSED)
        {
            try
            {
                TheDiagnostics.SetThreadName("HeartbeatTimer", true);
                mHeartBeatTicker++;
                TheBaseAssets.MySYSLOG.WriteToLog(2803, TSM.L(eDEBUG_LEVELS.EVERYTHING) ? null : new TSM("QSender", $"Enter HearbeatTimer for ORG:{MyTargetNodeChannel}", eMsgLevel.l7_HostDebugMessage));
                TheTimeouts tTO = TheBaseAssets.MyServiceHostInfo.TO;

                if (!IsHeartBeatAlive(tTO.DeviceCleanSweepTimeout * 2) && TheCommonUtils.IsDeviceSenderType(MyTargetNodeChannel?.SenderType ?? cdeSenderType.NOTSET) && MyTargetNodeChannel?.IsWebSocket == false)  //IDST-OK: Remove dead devices that might have hard disconnected (no correct disconnect) i.e. http browsers were just closed
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(2820, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("QSender", $"Forced Removal of QSender {MyTargetNodeChannel.ToMLString()} due to DeviceCleanSweep", eMsgLevel.l4_Message));
                    Guid?tTarget = MyTargetNodeChannel?.cdeMID;
                    DisposeSender(true);
                    if (tTarget.HasValue)
                    {
                        TheQueuedSenderRegistry.RemoveOrphan(tTarget.Value);
                        TheCommCore.PublishCentral(new TSM(eEngineName.ContentService, "CDE_DELETEORPHAN", tTarget.ToString()));
                    }
                    return;
                }
                if (!IsAlive && !MyTargetNodeChannel?.IsWebSocket == true)
                {
                    return;                                                        //NEW:V3 2013/12/13 allow for cloud reconnect if WebSockets
                }
                if ((mHeartBeatTicker % (tTO.HeartBeatRate * 2)) == 0)
                {
                    if (MyTargetNodeChannel?.SenderType != cdeSenderType.CDE_LOCALHOST)
                    {
                        timerMyHeartbeatTimer();
                    }
                    if (MyTargetNodeChannel?.SenderType == cdeSenderType.CDE_CLOUDROUTE && ((!IsConnected && !IsConnecting) || !IsAlive) && (mHeartBeatTicker % (tTO.HeartBeatRate * 10)) == 0) //tQ.MyTargetNodeChannel.IsWebSocket &&  NOW ALWAYS RECONNECT
                    {
                        TheCommonUtils.cdeRunAsync("ReconnectCloud", true, (o) => ReconnectCloud());
                    }
                    if (MyTargetNodeChannel?.SenderType != cdeSenderType.CDE_LOCALHOST && IsAlive && IsConnected) //!TheBaseAssets.MyServiceHostInfo.IsCloudService && !tQ.MyTargetNodeChannel.IsWebSocket &&
                    {
                        if (MyTargetNodeChannel?.IsWebSocket != true)
                        {
                            if (GetQueLength() == 0)
                            {
                                TheBaseAssets.MyServiceHostInfo.TO.MakeHeartPump(); // CODE REVIEW Markus: Isn't this backwards: we should pump faster while we have more work to do?
                                SendPickupMessage();                                //Pickup
                            }
                            else
                            {
                                TheBaseAssets.MyServiceHostInfo.TO.MakeHeartNormal();
                            }
                        }
                        else
                        {
                            SendPickupMessage(); //Pickup
                        }
                    }
                }
            }
            catch (Exception e)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(2821, new TSM("QSRegistry", $"Fatal Error in HealthTimer for QS:{this.cdeMID} and MTNC:{MyTargetNodeChannel?.ToMLString()}", eMsgLevel.l1_Error, e.ToString()));
            }
        }
示例#9
0
        private bool ProcessMessage(string correlationToken, string eventConverterName, DateTimeOffset messageTime, string messagePayload, string originator, bool bIsTargetedMessage, out string error, out bool bSendAck)
        {
            bool bSuccess = false;

            bSendAck = true;

            if (bIsTargetedMessage)
            {
                if (_nodeOwnerManager.RegisterOwnerCandidate(correlationToken, originator, TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString(), true))
                {
                    var notification = new TSM(MyBaseEngine.GetEngineName(), $"MESHRECEIVER_ACK_NOTIFY:;:{correlationToken}:;:{originator}:;:{bIsTargetedMessage}");
                    TheCommCore.PublishCentral(notification, false);
                }
            }
            else
            {
                if (_nodeOwnerManager.CheckOwner(originator, TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString()) != true)
                {
                    _nodeOwnerManager.RequestOwnership(correlationToken, originator, TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString());
                }
            }

            IEventConverter eventConverter = null;

            if (!string.IsNullOrEmpty(eventConverterName))
            {
                eventConverter = TheEventConverters.GetEventConverter(eventConverterName);
                if (eventConverter == null)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(180001, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("Mesh Receiver", $"Unknown event converter in incoming MESHSENDER_DATA {this.MyBaseThing.FriendlyName}: {eventConverterName}", eMsgLevel.l1_Error, TSM.L(eDEBUG_LEVELS.OFF) ? null : messagePayload));
                }
            }
            else
            {
                eventConverter = TheEventConverters.GetEventConverter(ReceiverEventConverter);
                if (eventConverter == null)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(180002, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("Mesh Receiver", $"Unknown default event converter {this.MyBaseThing.FriendlyName}: {ReceiverEventConverter}", eMsgLevel.l1_Error));
                }
            }

            //if (EnableDataLogging)
            //{
            //    try
            //    {
            //        lock (dataLoggerLock)
            //        {
            //            System.IO.File.AppendAllText("meshreceiverdata.log", $"{{\"TimeReceived\":\"{DateTimeOffset.Now:O}\", \"PLS\": {pMsg.Message.PLS},\"TXT\":{pMsg.Message.TXT}}},\r\n");
            //        }
            //    }
            //    catch (Exception e)
            //    {
            //        TheBaseAssets.MySYSLOG.WriteToLog(180003, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("Mongo Writer", $"Unable to log data to file: {this.MyBaseThing.FriendlyName}", eMsgLevel.l3_ImportantMessage, e.ToString()));
            //    }
            //}

            if (eventConverter == null)
            {
                error = "Unknown event converter";
            }
            else
            {
                if (IsConnected)
                {
                    try
                    {
                        var now = DateTimeOffset.Now;
                        if (!string.IsNullOrEmpty(TimeDriftPropertyName))
                        {
                            // Calculate time difference (in minutes) between the sender and this node
                            var timeDrift = now - messageTime;
                            timeDrift = TimeSpan.FromMinutes(timeDrift.TotalMinutes > 0 ? Math.Floor(timeDrift.TotalMinutes) : Math.Ceiling(timeDrift.TotalMinutes));
                            if (eventConverter.StaticPropsToAdd == null)
                            {
                                eventConverter.StaticPropsToAdd = new Dictionary <string, object>();
                            }
                            eventConverter.StaticPropsToAdd[TimeDriftPropertyName] = System.Xml.XmlConvert.ToString(timeDrift);
                        }
                        if (!string.IsNullOrEmpty(SenderTimePropertyName))
                        {
                            if (eventConverter.StaticPropsToAdd == null)
                            {
                                eventConverter.StaticPropsToAdd = new Dictionary <string, object>();
                            }
                            eventConverter.StaticPropsToAdd[SenderTimePropertyName] = messageTime;
                        }
                        bool bDetectedOtherOwner = false;
                        // TODO Support picking a thing for formats that don't carry a thing id
                        eventConverter.NewThingCallback = async(t) =>
                        {
                            if (await _nodeOwnerManager.CheckOwnerAsync(correlationToken, originator, TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString()).ConfigureAwait(false) == false)
                            {
                                bDetectedOtherOwner = true;
                                return(false);
                            }
                            return(true);
                        };
                        error = eventConverter.ProcessEventData(null, messagePayload, now);
                        if (bDetectedOtherOwner)
                        {
                            error    = "Detected other receiver";
                            bSendAck = false;
                            bSuccess = false;
                        }
                        else
                        {
                            if (String.IsNullOrEmpty(error))
                            {
                                ReceiveCount++;
                                bSuccess = true;
                            }
                            else
                            {
                                TheBaseAssets.MySYSLOG.WriteToLog(180004, new TSM("Mesh Receiver", "Error processing data", eMsgLevel.l1_Error, error));
                                ReceiveErrorCount++;
                            }
                            LastReceiveTime = now;
                        }
                    }
                    catch (Exception e)
                    {
                        error = "Error parsing data: " + e.Message;
                        TheBaseAssets.MySYSLOG.WriteToLog(180005, new TSM("Mesh Receiver", "Error processing data", eMsgLevel.l1_Error, e.ToString()));
                        bSuccess = false;
                        ReceiveErrorCount++;
                    }

                    if (bSuccess)
                    {
                        MyBaseThing.StatusLevel = 1;
                    }
                }
                else
                {
                    error = "Not connected";
                }
            }

            return(bSuccess);
        }
示例#10
0
        virtual void HandleMessage(ICDEThing sender, object pIncoming)
        {
            TheProcessMessage pMsg = pIncoming as TheProcessMessage;

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

            var cmd = TheCommonUtils.cdeSplit(pMsg.Message.TXT, ":", false, false);

            switch (cmd[0])
            {
            case "RUREADY":
                if (cmd.Length > 1 && cmd[1] == TheCommonUtils.cdeGuidToString(MyBaseThing.cdeMID))
                {
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(pMsg.Message.ENG, "IS_READY:" + TheCommonUtils.cdeGuidToString(MyBaseThing.cdeMID), mIsInitialized.ToString())
                    {
                        FLG = 8
                    }, true);
                }
                break;

            case "CONNECT_SERVER":
                Connect();
                break;

            case nameof(MsgConnectDisconnect):
            {
                var request     = TheCommRequestResponse.ParseRequestMessageJSON <MsgConnectDisconnect>(pMsg.Message);
                var responseMsg = new MsgConnectDisconnectResponse();
                if (request == null)
                {
                    responseMsg.Error = "Error parsing request message";
                }
                else
                {
                    try
                    {
                        if (request.Connect.HasValue && request.Reconnect.HasValue)
                        {
                            responseMsg.Error = "Can specify at most one of Connect Reconnect";
                        }
                        else if (!request.Connect.HasValue && !request.Reconnect.HasValue && !request.AutoConnect.HasValue)
                        {
                            responseMsg.Error = "Must specify at least one of Connect Reconnect AutoConnect";
                        }
                        else
                        {
                            if (request.Connect.HasValue)
                            {
                                if (request.Connect == true)
                                {
                                    Connect();
                                }
                                else
                                {
                                    Disconnect(true);
                                }
                            }
                            if (request.Reconnect.HasValue)
                            {
                                Disconnect(true);
                                if (request.WaitTimeBeforeReconnect.HasValue)
                                {
                                    try
                                    {
#if !NET40
                                        await TheCommonUtils.TaskDelayOneEye(request.WaitTimeBeforeReconnect.Value, 100).ConfigureAwait(false);
#else
                                        TheCommonUtils.TaskDelayOneEye(request.WaitTimeBeforeReconnect.Value, 100).Wait();
#endif
                                    }
                                    catch (System.Threading.Tasks.TaskCanceledException) { }
                                }
                                Connect();
                            }
                            if (request.AutoConnect.HasValue)
                            {
                                AutoConnect = request.AutoConnect.Value;
                            }
                            responseMsg.Connected = IsConnected;
                        }
                    }
                    catch (Exception e)
                    {
                        responseMsg.Error = e.Message;
                    }
                }
                TheCommRequestResponse.PublishResponseMessageJson(pMsg.Message, responseMsg);
            }
            break;
            }
        }
示例#11
0
        public override bool CreateUX()
        {
            if (mIsUXInitCalled)
            {
                return(false);
            }
            mIsUXInitCalled = true;

            //NUI Definition for All clients
            mMyDashboard = TheNMIEngine.AddDashboard(MyBaseThing, new TheDashboardInfo(MyBaseEngine, "OPC UA Client")
            {
                PropertyBag = new nmiDashboardTile()
                {
                    Category = " Connectivity", Thumbnail = "opcLarge.png;1;cdeLargeIcon", TileWidth = 3, TileHeight = 4, ClassName = "cdeLiveTile cdeLargeTile"
                }
            });

            var tFlds = TheNMIEngine.AddStandardForm(MyBaseThing, "OPC General Settings", "OPCD", 0, new nmiStandardForm {
                MaxTileWidth = 12, UseMargin = true, Category = TheNMIEngine.GetNodeForCategory()
            });
            TheFormInfo tMyForm = tFlds["Form"] as TheFormInfo;

            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.CollapsibleGroup, 5, 2, 0xc0, "GLS Discovery Service", null, ThePropertyBag.Create(new nmiCtrlCollapsibleGroup()
            {
                DoClose = false, IsSmall = true, TileWidth = 6, ParentFld = 1
            }));
            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.SingleEnded, 10, 2, 0, "GLS Address", "Address", new nmiCtrlSingleEnded()
            {
                ParentFld = 5
            });
            TheFieldInfo tBut = TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.TileButton, 11, 2, 0, "Scan for Servers", null, new nmiCtrlTileButton()
            {
                ParentFld = 5, ClassName = "cdeGoodActionButton"
            });

            tBut.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "SCAN", (pThing, pObj) =>
            {
                TheProcessMessage pMsg = pObj as TheProcessMessage;
                if (pMsg != null)
                {
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Scanning..."));
                    GetEndpoints();
                    mMyDashboard.Reload(pMsg, false);
                }
            });

            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.CollapsibleGroup, 15, 2, 0xc0, "Tracing (all clients)...", null, ThePropertyBag.Create(new nmiCtrlCollapsibleGroup()
            {
                DoClose = false, TileWidth = 6, IsSmall = true, ParentFld = 1
            }));

            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.SingleCheck, 16, 2, 0, "OPC Client File Tracing", nameof(EnableTracing), new nmiCtrlSingleCheck {
                TileWidth = 3, ParentFld = 15
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.SingleCheck, 17, 2, 0, "OPC Client Trace to Log", nameof(EnableTracingToLog), new nmiCtrlSingleCheck {
                TileWidth = 3, ParentFld = 15
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.Number, 18, 2, 0, "OPC Client Trace Mask", nameof(OPCTraceMask), new nmiCtrlNumber {
                TileWidth = 6, ParentFld = 15, HelpText = "1=Err,2=Info,4=Stk,8=Svc,16=SvcDtl,32=Op,64=OpDtl,128=Start,256=Ext,512=Sec"
            });



            TheFormInfo tAllOPCUASrvs = new TheFormInfo(MyBaseEngine)
            {
                cdeMID = TheThing.GetSafeThingGuid(MyBaseThing, "OPCS"), defDataSource = string.Format("TheThing;:;0;:;True;:;DeviceType={1};EngineName={0}", MyBaseEngine.GetEngineName(), eOPCDeviceTypes.OPCRemoteServer), FormTitle = "Discovered OPC-UA Servers", AddButtonText = "Add a Server"
            };

            TheNMIEngine.AddFormToThingUX(MyBaseThing, tAllOPCUASrvs, "CMyTable", "All OPC-UA Remote Servers", 1, 0x0F, 0xC0, TheNMIEngine.GetNodeForCategory(), null, new ThePropertyBag()
            {
                "Thumbnail=OPCLogo.png;1.0"
            });
            var tOpcs = TheNMIEngine.AddCommonTableColumns(MyBaseThing, tAllOPCUASrvs);

            tOpcs["Address"].Header      = "Server URL";
            tOpcs["Address"].PropertyBag = new nmiCtrlSingleEnded {
                TileWidth = 4, FldWidth = 4
            };

            TheNMIEngine.AddField(tAllOPCUASrvs, new TheFieldInfo()
            {
                FldOrder = 5, cdeA = 0xC0, Flags = 2, Type = eFieldType.SingleCheck, Header = "Auto-Connect", DataItem = "MyPropertyBag.AutoConnect.Value"
            });
            TheNMIEngine.AddField(tAllOPCUASrvs, new TheFieldInfo()
            {
                FldOrder = 6, cdeA = 0xC0, Flags = 2, Type = eFieldType.SingleCheck, Header = "Connected", DataItem = "MyPropertyBag.IsConnected.Value", PropertyBag = new nmiCtrlSingleCheck {
                    AreYouSure = "Are you sure you want to connect/disconnect?"
                }
            });
            //            TheNMIEngine.AddField(tAllOPCUASrvs, new TheFieldInfo() { FldOrder = 13, Flags = 2, cdeA = 0xFF, Type = eFieldType.SingleEnded, Header = "Friendly Name", DataItem = "MyPropertyBag.FriendlyName.Value", PropertyBag = new ThePropertyBag() { "FldWidth=3" } });
            //TheNMIEngine.AddField(tAllOPCUASrvs, new TheFieldInfo() { FldOrder = 14, Flags = 2, cdeA = 0xC0, Type = eFieldType.SingleEnded, Header = "Server URL", DataItem = "MyPropertyBag.Address.Value", PropertyBag = new ThePropertyBag() { "FldWidth=5" } });
            TheNMIEngine.AddField(tAllOPCUASrvs, new TheFieldInfo()
            {
                FldOrder = 50, cdeA = 0xFF, Type = eFieldType.DateTime, Header = "Last Update", DataItem = "MyPropertyBag.LastUpdate.Value", PropertyBag = new ThePropertyBag()
                {
                    "FldWidth=3"
                }
            });
            TheNMIEngine.AddField(tAllOPCUASrvs, new TheFieldInfo()
            {
                FldOrder = 55, cdeA = 0xFF, Type = eFieldType.DateTime, Header = "Last Receive", DataItem = "MyPropertyBag.LastDataReceivedTime.Value", PropertyBag = new ThePropertyBag()
                {
                    "FldWidth=3"
                }
            });
            //TheNMIEngine.AddTableButtons(tAllOPCUASrvs);

            TheThingRegistry.UpdateEngineUX(MyBaseEngine.GetEngineName());

            TheNMIEngine.AddLiveTagTable(MyBaseThing, eOPCDeviceTypes.OPCLiveTag, "UA Live Tags", TheNMIEngine.GetNodeForCategory());
            TheNMIEngine.AddLiveTagTable(MyBaseThing, eOPCDeviceTypes.OPCMethod, "UA Methods", TheNMIEngine.GetNodeForCategory());

            TheNMIEngine.AddTileBreak(MyBaseThing, mMyDashboard, "..A");

            TheNMIEngine.AddAboutButton(MyBaseThing, true, "REFRESH_DASH", 0xc0);
            TheNMIEngine.RegisterEngine(MyBaseEngine);

            CreateOPCWizard();

            mIsUXInitialized = true;
            return(true);
        }
示例#12
0
        public void CreateOPCWizard()
        {
            TheFieldInfo tTargetButton = null;
            var          flds          = TheNMIEngine.AddNewWizard <TheOPCSetClass>(new Guid("{56565656-6AD1-45AE-BE61-96AF02329614}"), Guid.Empty, TheNMIEngine.GetEngineDashBoardByThing(MyBaseThing).cdeMID, "Welcome to the OPC Wizard",
                                                                                    new nmiCtrlWizard {
                PanelTitle = "<i class='fa faIcon fa-3x'>&#xf0d0;</i></br>New OPC Client", SideBarTitle = "New OPC Client Wizard", SideBarIconFA = "&#xf545;", TileThumbnail = "FA5:f545"
            },
                                                                                    (myClass, pClientInfo) =>
            {
                myClass.cdeMID   = Guid.Empty;
                TheThing tMemTag = null;
                if (myClass.CreateMemoryTag)
                {
                    var tReq = new TheThingRegistry.MsgCreateThingRequestV1()
                    {
                        EngineName       = "CDMyVThings.TheVThings",
                        DeviceType       = "Memory Tag",
                        FriendlyName     = myClass.ClientName,
                        OwnerAddress     = MyBaseThing,
                        InstanceId       = Guid.NewGuid().ToString(),
                        CreateIfNotExist = true
                    };
                    tMemTag = TheThingRegistry.CreateOwnedThingAsync(tReq).Result;
                }

                var tOPCReq = new TheThingRegistry.MsgCreateThingRequestV1()
                {
                    EngineName       = "CDMyOPCUAClient.cdeOPCUaClient",
                    DeviceType       = "OPC-UA Remote Server",
                    FriendlyName     = myClass.ClientName,
                    Address          = myClass.OPCAddress,
                    OwnerAddress     = MyBaseThing,
                    InstanceId       = Guid.NewGuid().ToString(),
                    CreateIfNotExist = true
                };
                tOPCReq.Properties = new Dictionary <string, object>();
                //tOPCReq.Properties["ID"] = Guid.NewGuid().ToString();
                tOPCReq.Properties["AutoConnect"]     = myClass.AutoConnect;
                tOPCReq.Properties["SendOpcDataType"] = true;
                if (!myClass.DisableSecurity)
                {
                    tOPCReq.Properties["DisableSecurity"]            = true;
                    tOPCReq.Properties["AcceptUntrustedCertificate"] = true;
                    tOPCReq.Properties["DisableDomainCheck"]         = true;
                    tOPCReq.Properties["AcceptInvalidCertificate"]   = true;
                    tOPCReq.Properties["Anonymous"] = true;
                }
                if (tMemTag != null)
                {
                    tOPCReq.Properties["TagHostThingForSubscribeAll"] = tMemTag.cdeMID;
                }
                var tOPCServer = TheThingRegistry.CreateOwnedThingAsync(tOPCReq).Result;
                try
                {
                    if (tOPCServer != null && myClass.Prop2Tag && myClass.AutoConnect)
                    {
                        var response = TheCommRequestResponse.PublishRequestJSonAsync <MsgOPCUAConnect, MsgOPCUAConnectResponse>(MyBaseThing, tOPCServer, new MsgOPCUAConnect {
                            LogEssentialOnly = true, WaitUntilConnected = true
                        }).Result;
                        if (response != null && string.IsNullOrEmpty(response.Error))
                        {
                            var tBrowseResponse = TheCommRequestResponse.PublishRequestJSonAsync <MsgOPCUABrowse, MsgOPCUABrowseResponse>(MyBaseThing, tOPCServer, new MsgOPCUABrowse()).Result;
                            if (string.IsNullOrEmpty(tBrowseResponse.Error))
                            {
                                TheCommCore.PublishToNode(pClientInfo.NodeID, new TSM(eEngineName.NMIService, "NMI_TOAST", $"OPC UA Client browse error: {tBrowseResponse.Error}"));
                                return;
                            }
                            else
                            {
                                List <MsgOPCUACreateTags.TagInfo> tTagList = tBrowseResponse.Tags;
                                if (tTagList != null && tTagList.Count > 0)
                                {
                                    var tres = TheCommRequestResponse.PublishRequestJSonAsync <MsgOPCUACreateTags, MsgOPCUACreateTagsResponse>(MyBaseThing, tOPCServer, new MsgOPCUACreateTags {
                                        Tags = tTagList, BulkApply = true
                                    }).Result;
                                    if (tres != null && string.IsNullOrEmpty(tres.Error))
                                    {
                                        TheCommCore.PublishToNode(pClientInfo.NodeID, new TSM(eEngineName.NMIService, "NMI_TOAST", "OPC UA Client Created and memory tag ready"));
                                    }
                                }
                            }
                        }
                    }
                    TheCommCore.PublishToNode(pClientInfo.NodeID, new TSM(eEngineName.NMIService, "NMI_TOAST", "OPC UA Client Created and ready"));
                }
                catch (Exception)
                {
                    TheCommCore.PublishToNode(pClientInfo.NodeID, new TSM(eEngineName.NMIService, "NMI_TOAST", "Something went wrong! Check the OPC and Memory Tag settings"));
                }
                tTargetButton.SetUXProperty(pClientInfo.NodeID, $"OnClick=TTS:{tOPCServer.GetBaseThing().cdeMID}");
                TheCommonUtils.SleepOneEye(2000, 100);
            });

            var tMyForm2 = flds["Form"] as TheFormInfo;

            var tFlds = TheNMIEngine.AddNewWizardPage(MyBaseThing, tMyForm2, 0, 1, 2, null /*"Name and Address"*/);

            TheNMIEngine.AddWizardControl(MyBaseThing, tMyForm2, eFieldType.SingleEnded, 1, 1, 2, 0, "Connection Name", "ClientName", new TheNMIBaseControl {
                Explainer = "1. Enter name for the new OPC connection.",
            });
            TheNMIEngine.AddWizardControl(MyBaseThing, tMyForm2, eFieldType.SingleEnded, 1, 2, 2, 0, "OPC Server Address", "OPCAddress", new TheNMIBaseControl {
                Explainer = "1. Enter address of the OPC server.",
            });

            tFlds = TheNMIEngine.AddNewWizardPage(MyBaseThing, tMyForm2, 1, 2, 3, null /* "Settings"*/);
            TheNMIEngine.AddWizardControl(MyBaseThing, tMyForm2, eFieldType.SingleCheck, 2, 1, 2, 0, "OPC Server requires Security", "DisableSecurity", new nmiCtrlSingleCheck {
                Explainer = "Check if the OPC Server requires security"
            });
            TheNMIEngine.AddWizardControl(MyBaseThing, tMyForm2, eFieldType.SingleCheck, 2, 2, 2, 0, "Create a Memory Tag", "CreateMemoryTag", new nmiCtrlSingleCheck {
                TileWidth = 3, Explainer = "Check to create a Memory Tag and check to subscribes all Tags into it"
            });
            TheNMIEngine.AddWizardControl(MyBaseThing, tMyForm2, eFieldType.SingleCheck, 2, 3, 2, 0, "All Tags in Memory Tag", "Prop2Tag", new nmiCtrlSingleCheck {
                TileWidth = 3
            });
            TheNMIEngine.AddWizardControl(MyBaseThing, tMyForm2, eFieldType.SingleCheck, 2, 4, 2, 0, "Auto Connect to Server", "AutoConnect", new nmiCtrlSingleCheck {
                TileWidth = 3, Explainer = "Don't select this if your server requires security settings"
            });

            tFlds = TheNMIEngine.AddNewWizardPage(MyBaseThing, tMyForm2, 2, 3, 0, null /*"Final Settings"*/);
            TheNMIEngine.AddWizardControl(MyBaseThing, tMyForm2, eFieldType.SmartLabel, 3, 2, 0, 0, null, null, new nmiCtrlSmartLabel {
                Text = "Once you click finish, the Wizard will create the items you requested. It will notify you with a toast when its done", TileHeight = 5, TileWidth = 7, NoTE = true
            });
            //HELP SECTION final step help section

            TheNMIEngine.AddWizardProcessPage(MyBaseThing, tMyForm2, 4);
            TheNMIEngine.AddWizardControl(MyBaseThing, tMyForm2, eFieldType.SmartLabel, 4, 1, 0, 0, null, null, new nmiCtrlSmartLabel {
                NoTE = true, TileWidth = 7, Text = "Creating the new instance..please wait", TileHeight = 2
            });

            TheNMIEngine.AddWizardFinishPage(MyBaseThing, tMyForm2, 5);
            TheNMIEngine.AddWizardControl(MyBaseThing, tMyForm2, eFieldType.SmartLabel, 5, 1, 0, 0, null, null, new nmiCtrlSmartLabel {
                NoTE = true, TileWidth = 7, Text = "Done...what do you want to do next?", TileHeight = 2
            });

            TheNMIEngine.AddWizardControl(MyBaseThing, tMyForm2, eFieldType.TileGroup, 5, 2, 0, 0, null, null, new nmiCtrlTileGroup {
                TileWidth = 1, TileHeight = 2, TileFactorX = 2
            });
            TheNMIEngine.AddWizardControl(MyBaseThing, tMyForm2, eFieldType.TileButton, 5, 3, 2, 0, "Go to Dashboard", null, new nmiCtrlTileButton {
                NoTE = true, TileHeight = 2, TileWidth = 3, OnClick = $"TTS:{mMyDashboard.cdeMID}", ClassName = "cdeTransitButton"
            });
            TheNMIEngine.AddWizardControl(MyBaseThing, tMyForm2, eFieldType.TileGroup, 5, 4, 0, 0, null, null, new nmiCtrlTileGroup {
                TileWidth = 1, TileHeight = 2
            });
            tTargetButton = TheNMIEngine.AddWizardControl(MyBaseThing, tMyForm2, eFieldType.TileButton, 5, 5, 2, 0, "Go to New OPC Client", null, new nmiCtrlTileButton {
                NoTE = true, TileHeight = 2, TileWidth = 3, ClassName = "cdeTransitButton"
            });
        }
示例#13
0
        /// <summary>
        /// Shutsdown the C-DEngine and all plugins
        /// Applications can override this function to add custom shutdown code
        /// </summary>
        /// <param name="ForceExit">If True and the C-DEngine will Stop or restart the hosting application. If it is hosted in IIS, the Application Pool hosting the app will be Stopped or Restarted depending on the next parameter</param>
        /// <param name="waitIfPending">Waits in case The shutdown is already initiated</param>
        public virtual void Shutdown(bool ForceExit, bool waitIfPending = false)
        {
            if (!waitIfPending)
            {
                if (!TheBaseAssets.MasterSwitch || TheCommonUtils.cdeIsLocked(ShutdownLock))
                {
                    return;                                                                                                            //Make sure we dont do this twice
                }
            }
            lock (ShutdownLock)
            {
                if (TheBaseAssets.MasterSwitch)
                {
                    if (TheBaseAssets.IsStarting)
                    {
                        TheBaseAssets.MySYSLOG?.WriteToLog(3, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(TheBaseAssets.MyServiceHostInfo.ApplicationName, "Shutdown was requested, but startup has not finished. Waiting for startup to finish.", eMsgLevel.l3_ImportantMessage));
                        // Ensure we wait for user manager so CUOFS first-run-only settings are applied
                        var sw = System.Diagnostics.Stopwatch.StartNew();
                        while (TheBaseAssets.IsStarting && sw.ElapsedMilliseconds < 60000)
                        {
                            Thread.Sleep(100);
                        }
                        if (TheBaseAssets.IsStarting)
                        {
                            TheBaseAssets.MySYSLOG?.WriteToLog(3, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(TheBaseAssets.MyServiceHostInfo.ApplicationName, "Shutdown was requested, but startup has not finished after wait time (60 seconds). Shutting down regardless. Some first-run-only settings may not have been applied.", eMsgLevel.l1_Error));
                        }
                    }
                    if (TheBaseAssets.MyServiceHostInfo.PreShutDownDelay > 0)
                    {
                        var tcsPreHandlers = new TaskCompletionSource <bool>();
                        TheCommonUtils.cdeRunAsync("PreShutdownHandlers", true, (o) =>
                        {
                            TheCDEngines.MyContentEngine?.FireEvent(eEngineEvents.PreShutdown, null, TheBaseAssets.MyServiceHostInfo.PreShutDownDelay, false);
                            tcsPreHandlers.TrySetResult(true);
                        });
                        tcsPreHandlers.Task.Wait(TheBaseAssets.MyServiceHostInfo.PreShutDownDelay);
                    }
                    while (Interlocked.Read(ref TheBaseAssets.DelayShutDownCount) > 0)
                    {
                        TheCommonUtils.SleepOneEye(100, 100);
                    }
                    TheBaseAssets.MySYSLOG?.WriteToLog(3, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(TheBaseAssets.MyServiceHostInfo.ApplicationName, TheBaseAssets.MyServiceHostInfo.ApplicationTitle + " Initiating shutdown at : " + TheCommonUtils.GetDateTimeString(DateTimeOffset.Now), eMsgLevel.l6_Debug));
                    TheBaseAssets.MasterSwitch  = false;
                    TheBaseAssets.ForceShutdown = ForceExit;
                    TheCDEngines.StopAllEngines();
                    TheBaseAssets.MySYSLOG?.WriteToLog(3, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(TheBaseAssets.MyServiceHostInfo.ApplicationName, TheBaseAssets.MyServiceHostInfo.ApplicationTitle + " Shutdown: Engines stopped at: " + TheCommonUtils.GetDateTimeString(DateTimeOffset.Now), eMsgLevel.l6_Debug));

                    TheCommCore.StopCommunication();
                    TheBaseAssets.MySYSLOG?.WriteToLog(3, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(TheBaseAssets.MyServiceHostInfo.ApplicationName, TheBaseAssets.MyServiceHostInfo.ApplicationTitle + " Shutdown: Communications stopped at: " + TheCommonUtils.GetDateTimeString(DateTimeOffset.Now), eMsgLevel.l6_Debug));
                    if (MyCommonDisco != null)
                    {
                        MyCommonDisco.ShutdownDiscoService();
                        TheBaseAssets.MySYSLOG?.WriteToLog(3, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(TheBaseAssets.MyServiceHostInfo.ApplicationName, TheBaseAssets.MyServiceHostInfo.ApplicationTitle + " Shutdown: Discovery Service stopped at: " + TheCommonUtils.GetDateTimeString(DateTimeOffset.Now), eMsgLevel.l6_Debug));
                    }
                    if (TheBaseAssets.MySYSLOG != null)
                    {
                        string iis = "";
                        switch (TheBaseAssets.MyServiceHostInfo.cdeHostingType)
                        {
                        case cdeHostType.IIS: iis = " (Hosted in IIS)"; break;

                        case cdeHostType.ASPCore: iis = " (Hosted in ASP.NET Core)"; break;
                        }
                        TheBaseAssets.MySYSLOG.WriteToLog(3, new TSM(TheBaseAssets.MyServiceHostInfo.ApplicationName, TheBaseAssets.MyServiceHostInfo.ApplicationTitle + iis + " Stopped at : " + TheCommonUtils.GetDateTimeString(DateTimeOffset.Now), eMsgLevel.l4_Message)); //Log Entry that service has been started
                        TheBaseAssets.MySYSLOG.Shutdown();
                    }
                }
            }
        }
示例#14
0
        public virtual bool CreateUX()
        {
            if (mIsUXInitCalled)
            {
                return(false);
            }
            mIsUXInitCalled = true;

            var tFlds = TheNMIEngine.AddStandardForm(MyBaseThing, null, 12, null, "Value");

            MyStatusForm            = tFlds["Form"] as TheFormInfo;
            SummaryForm             = tFlds["DashIcon"] as TheDashPanelInfo;
            SummaryForm.PropertyBag = new ThePropertyBag()
            {
                string.Format("Format={0}<br>{{0}} Properties", MyBaseThing.FriendlyName)
            };
            SummaryForm.RegisterPropertyChanged(sinkStatChanged);

            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.Number, 21, 0, 0x0, "###CDMyVThings.TheVThings#CountOfProperties598472#Count of Properties###", "Value", new nmiCtrlNumber()
            {
                ParentFld = 1
            });
            TheFieldInfo mSendbutton = TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.TileButton, 22, 2, 0, "###CDMyVThings.TheVThings#Reload598472#Reload###", false, "", null, new nmiCtrlTileButton()
            {
                ParentFld = 1, NoTE = true, ClassName = "cdeGoodActionButton"
            });

            mSendbutton.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "", (pThing, pPara) =>
            {
                TheProcessMessage pMsg = pPara as TheProcessMessage;
                if (pMsg?.Message == null)
                {
                    return;
                }
                sinkStatChanged(null, null);
                MyStatusForm.Reload(pMsg, true);
            });
            PropTable = TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.Table, 40, 0xA0, 0x80, "All Properties", "mypropertybag;0", new TheNMIBaseControl()
            {
                NoTE = true, ParentFld = 1, TileWidth = 12, TileHeight = 16
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.SingleEnded, 30, 0x0A, 0, "New Property Name", "ScratchName", new nmiCtrlSingleEnded()
            {
                ParentFld = 1
            });
            TheFieldInfo tBut = TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.TileButton, 35, 0x0A, 0, "Add Property", false, null, null, new nmiCtrlTileButton()
            {
                ParentFld = 1, NoTE = true
            });

            tBut.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "AddProp", (pThing, pObj) =>
            {
                TheProcessMessage pMsg = pObj as TheProcessMessage;
                if (pMsg?.Message == null)
                {
                    return;
                }
                string[] parts = pMsg.Message.PLS.Split(':');
                TheThing tOrg  = TheThingRegistry.GetThingByMID(MyBaseEngine.GetEngineName(), TheCommonUtils.CGuid(parts[2]));
                if (tOrg == null)
                {
                    return;
                }

                string tNewPropName = TheThing.GetSafePropertyString(tOrg, "ScratchName");
                if (string.IsNullOrEmpty(tNewPropName))
                {
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Please specify a new property name"));
                }
                else
                {
                    if (tOrg.GetProperty(tNewPropName) != null)
                    {
                        TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Property already exists"));
                    }
                    else
                    {
                        tOrg.DeclareNMIProperty(tNewPropName, ePropertyTypes.TString);
                        TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Property Added"));
                        MyStatusForm.Reload(pMsg, false);
                    }
                }
                tOrg.RemoveProperty("ScratchName");
            });
            mIsUXInitialized = true;
            return(true);
        }
示例#15
0
        public async Task ProcessWS()
        {
            TheDiagnostics.SetThreadName("WSProcessWS");
            if (MyQSender == null)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(4366, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSProcessor", "ProcessWS - no QSender Specified! ", eMsgLevel.l1_Error));
                return;
            }
            int tMaxMsgSize = 0;
            ArraySegment <byte> buffer;

            byte[] receiveBuffer;
            try
            {
                if (IsClient)
                {
                    tMaxMsgSize = TheCommonUtils.GetMaxMessageSize(MyQSender.MyTargetNodeChannel.SenderType);
                }
                else
                {
                    tMaxMsgSize = TheCommonUtils.GetMaxMessageSize(TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.SenderType);
                }
                receiveBuffer = new byte[tMaxMsgSize];
                buffer        = new ArraySegment <byte>(receiveBuffer);
                TheBaseAssets.MySYSLOG.WriteToLog(4367, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSProcessor", "New ProcessWS thread started ", eMsgLevel.l4_Message));
            }
            catch (Exception e)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(4367, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSProcessor", "Failure while starting new ProcessWS thread", eMsgLevel.l4_Message, e.ToString()));
                return;
            }

            CloseFired = false;
            bool   HasFaulted = false;
            string tCause     = "1604:Thread ended";

            try
            {
                if (IsSocketReady(websocket))
                {
                    if (IsClient)
                    {
                        //MyQSender.IsConnected = true;
                        byte[] tSendBuffer = TheCommCore.SetConnectingBuffer(MyQSender);
                        PostToSocket(null, tSendBuffer, false, true);
                    }
                }

                while (TheBaseAssets.MasterSwitch && IsActive && IsSocketReady(websocket))
                {
                    WebSocketReceiveResult receiveResult = await websocket.ReceiveAsync(buffer, CancellationToken.None);

                    if (receiveResult.MessageType == WebSocketMessageType.Close)
                    {
                        tCause = "1605:WebSocket Closed";
                        break;
                    }
                    //LogBufferToFile("wsinputlog.dat", buffer.Array, buffer.Offset, receiveResult.Count);
                    if (MyQSender == null || !MyQSender.IsAlive)
                    {
                        tCause = "1606:QSender No longer alive";
                        break;
                    }

                    int    offset          = receiveResult.Count;
                    bool   IsUsingTArray   = false;
                    byte[] tPostData       = null;
                    int    tPostDataLength = 0;
                    if (receiveResult.EndOfMessage == false)
                    {
                        List <byte[]> tTelList = new List <byte[]>();
                        byte[]        tArray   = null;
                        while (receiveResult.EndOfMessage == false)
                        {
                            if (IsUsingTArray)
                            {
                                var arraySeg = new ArraySegment <byte>(tArray, offset, tMaxMsgSize - offset);
                                receiveResult = await websocket.ReceiveAsync(arraySeg, CancellationToken.None);

                                //LogBufferToFile("wsinputlog.dat", arraySeg.Array, arraySeg.Offset, receiveResult.Count);
                            }
                            else
                            {
                                var arraySeg = new ArraySegment <byte>(receiveBuffer, offset, tMaxMsgSize - offset);
                                receiveResult = await websocket.ReceiveAsync(arraySeg, CancellationToken.None);

                                //LogBufferToFile("wsinputlog.dat", arraySeg.Array, arraySeg.Offset, receiveResult.Count);
                            }
                            if (receiveResult.Count == 0)
                            {
                                if (receiveResult.Count + offset != tMaxMsgSize)
                                {
                                    TheBaseAssets.MySYSLOG.WriteToLog(4369, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("ProcessWS", string.Format("WS Buffer count wrong: Max={0} Offset={1} Count={2}", tMaxMsgSize, offset, receiveResult.Count), eMsgLevel.l1_Error));
                                }
                                tArray = new byte[tMaxMsgSize];
                                if (!IsUsingTArray)
                                {
                                    tTelList.Add(receiveBuffer);
                                }
                                tTelList.Add(tArray);
                                IsUsingTArray = true;
                                offset        = 0;
                            }
                            else
                            {
                                offset += receiveResult.Count;
                            }
                        }
                        if (tTelList.Count > 0)
                        {
                            tPostData = new byte[((tTelList.Count - 1) * tMaxMsgSize) + offset];
                        }
                        tPostDataLength = 0;
                        for (int i = 0; i < tTelList.Count - 1; i++)
                        {
                            byte[] tb = tTelList[i];
                            TheCommonUtils.cdeBlockCopy(tb, 0, tPostData, i * tMaxMsgSize, tMaxMsgSize);
                            tb = null;
                        }
                        if (IsUsingTArray && offset > 0 && tTelList.Count > 0 && tPostData != null)
                        {
                            TheCommonUtils.cdeBlockCopy(tTelList[tTelList.Count - 1], 0, tPostData, (tTelList.Count - 1) * tMaxMsgSize, offset);
                            tPostDataLength = tPostData.Length;
                        }
                        //tTelList.Clear();
                    }
                    if (!IsUsingTArray)
                    {
                        tPostData = new byte[offset];
                        TheCommonUtils.cdeBlockCopy(receiveBuffer, 0, tPostData, 0, offset);
                        tPostDataLength = offset;
                    }
                    //LogBufferToFile("wsinputbactchedlog.dat", tPostData, 0, tPostData.Length);
                    TheCommonUtils.cdeRunAsync("ProcessFromWS", true, (o) => ProcessIncomingData(null, (byte [])o, ((byte[])o).Length), tPostData);
                }
            }
            catch (Exception eee)
            {
                HasFaulted = true;
                if (eee.Source == "System")
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(4369, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("ProcessWS", "ProcessWS Loop has failed because WebSocket was closed during ReceiveAsync.", eMsgLevel.l1_Error));
                }
                else
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(4369, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("ProcessWS", "ProcessWS Loop has failed.", eMsgLevel.l1_Error, eee.ToString()));
                }
            }
            TheBaseAssets.MySYSLOG.WriteToLog(4369, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("ProcessWS", $"ProcessWS Loop for {OwnerNodeID} has ended. Faulted:{HasFaulted} HasWS:{websocket != null}", eMsgLevel.l3_ImportantMessage));
            ConnectSuccess = false;
            if (HasFaulted || (websocket != null && websocket.State != WebSocketState.Closed))
            {
                tCause = string.Format("1607:WebSocket Faulted:{0} WS State:{1}", HasFaulted, websocket != null?websocket.State.ToString():"is null");
            }
            Shutdown(true, tCause);
        }
        static readonly TimeSpan defaultRequestTimeout = new TimeSpan(0, 1, 0); // TODO make this configurable?

        /// <summary>
        /// Sends a TSM message to the targetThing and return the matching response message
        /// </summary>
        /// <param name="originator">Thing or engine to use for response messages. If NULL defaults to ContentService.</param>
        /// <param name="target">Thing or engine to which the message is to be sent.</param>
        /// <param name="messageName">Name of the message, as defined by the target thing. The response message will be messageName_RESPONSE.</param>
        /// <param name="txtParameters">Array of simple string parameters, to be attached to the message's TXT field, as defined by the target thing. txtParameters must not contain ":" characters.</param>
        /// <param name="PLS">String payload to be set as the message's PLS field, as defined by the target thing.</param>
        /// <param name="PLB">Binary pauload to be set as the message's PLB field, as defined by the target thing.</param>
        /// <param name="timeout">Time to wait for the response message. Can not exceed TheBaseAsset.MaxMessageResponseTimeout (default: 1 hour).</param>
        /// <returns>The response message as defined by the target thing. The response parameters and correlation token can be parsed using ParseRequestOrResponseMessage, if the target thing used the PublishResponseMessage or an equivalent message format.
        /// If the message times out or an error occured while sending the message, the return value will be null.
        /// </returns>
        public static Task <TSM> PublishRequestAsync(TheMessageAddress originator, TheMessageAddress target, string messageName, TimeSpan timeout, string[] txtParameters = null, string PLS = null, byte[] PLB = null)
        {
            Guid correlationToken = Guid.NewGuid();

            if (originator == null)
            {
                originator = TheThingRegistry.GetBaseEngineAsThing(eEngineName.ContentService);
            }
            var msg = PrepareRequestMessage(originator, target, messageName, correlationToken, txtParameters, PLS, PLB);

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

            if (timeout > MaxTimeOut)
            {
                timeout = MaxTimeOut;
            }
            if (timeout == TimeSpan.Zero)
            {
                timeout = defaultRequestTimeout;
            }

            var tcsResponse = new TaskCompletionSource <TSM>();

            var callback = new Action <ICDEThing, object>((tSenderThing, responseMsgObj) =>
            {
                var responseMsg = CheckResponseMessage(messageName, correlationToken, responseMsgObj);
                if (responseMsg != null)
                {
                    var bReceived = tcsResponse.TrySetResult(responseMsg);
                    if (bReceived)
                    {
                        TheSystemMessageLog.WriteLog(1000, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("Thing Registry", $"Processed response message for {messageName}", eMsgLevel.l2_Warning, $"{correlationToken}: {responseMsg?.TXT}"), false);
                    }
                    else
                    {
                        TheSystemMessageLog.WriteLog(1000, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("Thing Registry", $"Failed to process response message for {messageName}: timed out or double response", eMsgLevel.l2_Warning, $"{correlationToken}: {responseMsg?.TXT}"), false);
                    }
                }
                else
                {
                    responseMsg = (responseMsgObj as TheProcessMessage)?.Message;
                    TheSystemMessageLog.WriteLog(1000, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("Thing Registry", $"Ignoring response message for {messageName}", eMsgLevel.l2_Warning, $"{correlationToken}: {responseMsg?.TXT}"), false);
                }
            });

            var originatorThingOrEngine = RegisterRequestCallback(originator, callback);

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

            if (target.SendToProvisioningService)
            {
                TheISMManager.SendToProvisioningService(msg);
            }
            else if (target.Node != Guid.Empty)
            {
                TheCommCore.PublishToNode(target.Node, msg);
            }
            else
            {
                TheCommCore.PublishCentral(msg, true);
            }

            TheCommonUtils.TaskWaitTimeout(tcsResponse.Task, timeout).ContinueWith((t) =>
            {
                UnregisterRequestCallback(originatorThingOrEngine, callback);
                var timedOut = tcsResponse.TrySetResult(null); // Will preserve value if actual result has already been set
                if (timedOut)
                {
                    TheSystemMessageLog.WriteLog(1000, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("Thing Registry", $"Timeout waiting for response message for {messageName}", eMsgLevel.l2_Warning, $"{correlationToken}"), false);
                }
            });
            return(tcsResponse.Task);
        }
示例#17
0
        // KPIs in UI

        //public long PropertiesSent
        //{
        //    get { return (long) TheThing.GetSafePropertyNumber(MyBaseThing, "PropertiesSent"); }
        //    set { TheThing.SetSafePropertyNumber(MyBaseThing, "PropertiesSent", value); }
        //}
        //public long PropertiesSentSinceStart
        //{
        //    get { return (long)TheThing.GetSafePropertyNumber(MyBaseThing, "PropertiesSentSinceStart"); }
        //    set { TheThing.SetSafePropertyNumber(MyBaseThing, "PropertiesSentSinceStart", value); }
        //}

        //public double PropertiesPerSecond
        //{
        //    get { return TheThing.GetSafePropertyNumber(MyBaseThing, "PropertiesPerSecond"); }
        //    set { TheThing.SetSafePropertyNumber(MyBaseThing, "PropertiesPerSecond", value); }
        //}

        //public double DataSentKBytesPerSecond
        //{
        //    get { return TheThing.GetSafePropertyNumber(MyBaseThing, "DataSentKBytesPerSecond"); }
        //    set { TheThing.SetSafePropertyNumber(MyBaseThing, "DataSentKBytesPerSecond", value); }
        //}
        //public double DataSentKBytesSinceStart
        //{
        //    get { return TheThing.GetSafePropertyNumber(MyBaseThing, "DataSentKBytesSinceStart"); }
        //    set { TheThing.SetSafePropertyNumber(MyBaseThing, "DataSentKBytesSinceStart", value); }
        //}
        //public double EventsPerSecond
        //{
        //    get { return TheThing.GetSafePropertyNumber(MyBaseThing, "EventsPerSecond"); }
        //    set { TheThing.SetSafePropertyNumber(MyBaseThing, "EventsPerSecond", value); }
        //}
        //public long EventsSent
        //{
        //    get { return (long)TheThing.GetSafePropertyNumber(MyBaseThing, "EventsSent"); }
        //    set { TheThing.SetSafePropertyNumber(MyBaseThing, "EventsSent", value); }
        //}
        //public long EventsSentSinceStart
        //{
        //    get { return (long)TheThing.GetSafePropertyNumber(MyBaseThing, "EventsSentSinceStart"); }
        //    set { TheThing.SetSafePropertyNumber(MyBaseThing, "EventsSentSinceStart", value); }
        //}
        //public long PendingEvents
        //{
        //    get { return (long) TheThing.GetSafePropertyNumber(MyBaseThing, "PendingEvents"); }
        //    set { TheThing.SetSafePropertyNumber(MyBaseThing, "PendingEvents", value); }
        //}
        //public DateTimeOffset KPITime
        //{
        //    get { return TheThing.GetSafePropertyDate(MyBaseThing, "KPITime"); }
        //    set { TheThing.SetSafePropertyDate(MyBaseThing, "KPITime", value); }
        //}

        //public DateTimeOffset LastReceiveTime
        //{
        //    get { return TheThing.GetSafePropertyDate(MyBaseThing, nameof(LastReceiveTime)); }
        //    set { TheThing.SetSafePropertyDate(MyBaseThing, nameof(LastReceiveTime), value); }
        //}

        #endregion

        public override void HandleMessage(ICDEThing sender, object pIncoming)
        {
            TheProcessMessage pMsg = pIncoming as TheProcessMessage;

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

            var cmd = pMsg.Message.TXT.Split(':');

            switch (cmd[0])
            {
            case "MESHSENDER_DATA":
                if (IsConnected || AutoConnect)
                {
                    //TheBaseAssets.MySYSLOG.WriteToLog(180001, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("Mesh Receiver", $"Received TSM with TXT MESHSENDER_DATA {this.MyBaseThing.FriendlyName}: {pMsg.Message.ToString()}", eMsgLevel.l6_Debug));
                    bool bSuccess = false;
                    //bool bSendAck = true;
                    string error = "";

                    bool bIsTargeted = pMsg.Topic.StartsWith("CDE_SYSTEMWIDE");

                    string correlationToken = null;
                    if (cmd.Length >= 2)
                    {
                        correlationToken = cmd[1];
                    }
                    string eventConverterName = null;
                    if (cmd.Length >= 3)
                    {
                        eventConverterName = cmd[2];
                    }

                    //if (EnableDataLogging)
                    //{
                    //    try
                    //    {
                    //        lock (dataLoggerLock)
                    //        {
                    //            System.IO.File.AppendAllText("meshreceiverdata.log", $"{{\"TimeReceived\":\"{DateTimeOffset.Now:O}\", \"PLS\": {pMsg.Message.PLS},\"TXT\":{pMsg.Message.TXT}}},\r\n");
                    //        }
                    //    }
                    //    catch (Exception e)
                    //    {
                    //        TheBaseAssets.MySYSLOG.WriteToLog(180003, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("Mongo Writer", $"Unable to log data to file: {this.MyBaseThing.FriendlyName}", eMsgLevel.l3_ImportantMessage, e.ToString()));
                    //    }
                    //}

                    bSuccess = ProcessMessage(correlationToken, eventConverterName, pMsg.Message.TIM, pMsg.Message.PLS, pMsg.Message.ORG, bIsTargeted, out error, out var bSendAck);

                    if (bSendAck)
                    {
                        TSM response = new TSM(MyBaseEngine.GetEngineName(), $"MESHSENDER_DATA_ACK:{correlationToken}:{bSuccess}:{error}");
                        response.QDX = pMsg.Message.QDX;
                        TheBaseAssets.MySYSLOG.WriteToLog(180001, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("Mesh Receiver", $"Sending ACK for {this.MyBaseThing.FriendlyName} to ORG '{pMsg.Message.ORG}'", eMsgLevel.l1_Error, response.TXT));
                        TheCommCore.PublishToOriginator(pMsg.Message, response, true);

                        if (!bIsTargeted)
                        {
                            var notification = new TSM(MyBaseEngine.GetEngineName(), $"MESHRECEIVER_ACK_NOTIFY:;:{correlationToken}:;:{pMsg.Message.ORG}:;:{bIsTargeted}");
                            TheCommCore.PublishCentral(notification, false);
                        }
                    }
                }

                break;

            case "MESHRECEIVER_ACK_NOTIFY":
            {
                var ackNotifyParts = TheCommonUtils.cdeSplit(pMsg.Message.TXT, ":;:", false, false);
                if (ackNotifyParts.Length >= 4)
                {
                    string correlationToken = ackNotifyParts[1];
                    string sourceORG        = ackNotifyParts[2];
                    bool   bIsTargeted      = TheCommonUtils.CBool(ackNotifyParts[3]);
                    _nodeOwnerManager.RegisterOwnerCandidate(correlationToken, sourceORG, pMsg.Message.ORG, bIsTargeted);
                }
                break;
            }

            case "MESHSENDER_PING":
            case "MESHSENDER_PING_ALL":
            {
                string correlationToken = "nocorrelationtoken";
                if (cmd.Length > 1)
                {
                    correlationToken = cmd[1];
                }

                // MyBaseThing.LastMessage = DateTimeOffset.Now + String.Format(": {0} from {1}. Token {2}", cmd[0], TheCommonUtils.cdeGuidToString(pMsg.Message.GetOriginator()), correlationToken);
                MyBaseThing.LastMessage = $"{DateTimeOffset.Now}: {cmd[0]} from {TheCommonUtils.cdeGuidToString(pMsg.Message.GetOriginator())}. Token {correlationToken}";

                //TSM response = new TSM(MyBaseEngine.GetEngineName(), String.Format("{0}_ACK:{1}", cmd[0], correlationToken),
                //    String.Format("{0}:{1}:{2}:{3}", TheCommonUtils.cdeGuidToString(MyBaseThing.cdeMID), ++PingCounter, MyBaseThing.FriendlyName, IsConnected));
                TSM response = new TSM(MyBaseEngine.GetEngineName(), $"{cmd[0]}_ACK:{correlationToken}",
                                       $"{TheCommonUtils.cdeGuidToString(MyBaseThing.cdeMID)}:{++PingCounter}:{MyBaseThing.FriendlyName}:{IsConnected}");
                TheCommCore.PublishToOriginator(pMsg.Message, response, true);
            }
            break;

            default:
                base.HandleMessage(sender, pIncoming);
                break;
            }
        }
示例#18
0
        public void TheRESTSenderThread()
        {
            if (IsSenderThreadRunning)
            {
                return;
            }
            try
            {
                TheDiagnostics.SetThreadName($"QSender:{MyTargetNodeChannel} SenderThread", true);
                MyREST = new TheREST();
                IsSenderThreadRunning = true;
                StringBuilder tSendBufferStr = new StringBuilder(TheBaseAssets.MyServiceHostInfo?.IsMemoryOptimized == true ? 1024 : TheBaseAssets.MAX_MessageSize[(int)MyTargetNodeChannel.SenderType] * 2);
                TargetUri     = TheCommonUtils.CUri(MyTargetNodeChannel.TargetUrl, true);
                TargetUriPath = TargetUri.AbsolutePath;

                int QDelay = TheCommonUtils.CInt(TheBaseAssets.MySettings.GetSetting("ThrottleWS"));
                if (QDelay < 2)
                {
                    QDelay = 2;
                }
                if (MyTargetNodeChannel.SenderType == cdeSenderType.CDE_JAVAJASON && TheBaseAssets.MyServiceHostInfo.WsJsThrottle > QDelay)
                {
                    QDelay = TheBaseAssets.MyServiceHostInfo.WsJsThrottle;
                }
                mre = new ManualResetEvent(false);
                if (eventSenderThreadRunning != null)
                {
                    TheCommonUtils.cdeRunAsync("EventSenderThreadRunning", true, (p) => { eventSenderThreadRunning(this); });
                }
                MyISBlock?.FireEvent("SenderThreadCreated");
                while (TheBaseAssets.MasterSwitch && IsAlive && IsSenderThreadRunning)
                {
                    if (QDelay > 2)
                    {
                        mre.WaitOne(QDelay);    //Throtteling should be here not in the wait loop
                    }
                    int WaitCounter = 0;
                    while (TheBaseAssets.MasterSwitch && IsAlive && IsSenderThreadRunning && ((MyCoreQueue.Count == 0 && IsConnected) || IsConnecting || IsInPost || MyREST.IsPosting > (IsConnected?TheBaseAssets.MyServiceHostInfo.ParallelPosts:0)))
                    {
                        // CODE REVIEW: This was seen looping after service route to local node was closed (due to node shutdown): IsCOnnecting/IsConnected/IsInPost were false; ISAlive true. MyREST.IsPosting was 8. Queue count ~345
                        //              This should be fixed now with IsSenderThreadRunning in the loop (I was wrong :) this happens only with cloud connections where POST fails and the IsPosting was not reset properly).
                        // Update: If found the same problem. Sometime IsPosting is not reduced properly when a Timeout or other error occured during Posting
                        if (IsInPost && MyCoreQueue.Count > 100)
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(235, new TSM("QueuedSender", $"IsInPost was still on and has been reset for {MyTargetNodeChannel?.ToMLString()}", eMsgLevel.l2_Warning));
                            IsInPost = false;
                        }
                        if (!IsConnected)
                        {
                            if (IsConnecting && MyREST.IsPosting == 0)
                            {
                                TheBaseAssets.MySYSLOG.WriteToLog(235, new TSM("QueuedSender", $"IsConnecting is set but no Pending Post {MyTargetNodeChannel?.ToMLString()} - resetting IsConnecting", eMsgLevel.l2_Warning));
                                IsConnecting = false;
                            }
                            if (!IsConnecting && MyREST.IsPosting > (IsConnected ? 10 : 0))
                            {
                                WaitCounter++;
                                if (WaitCounter > (10000 / QDelay))
                                {
                                    TheBaseAssets.MySYSLOG.WriteToLog(235, new TSM("QueuedSender", $"MyREST.IsPosting ({MyREST.IsPosting}) was higher then expected...possible POST problem. Resetting POST Counter for {MyTargetNodeChannel?.ToMLString()}", eMsgLevel.l2_Warning));
                                    MyREST.IsPosting = 0;
                                }
                            }
                        }

                        mre.WaitOne(QDelay);
                    }
                    if (!TheBaseAssets.MasterSwitch || !IsAlive || !IsSenderThreadRunning)
                    {
                        IsInPost = false;
                        break;
                    }
                    IsInPost = true;
                    if (MyTargetNodeChannel.SenderType == cdeSenderType.CDE_BACKCHANNEL ||
                        MyTargetNodeChannel.SenderType == cdeSenderType.CDE_PHONE ||
                        MyTargetNodeChannel.SenderType == cdeSenderType.CDE_DEVICE ||
                        MyTargetNodeChannel.SenderType == cdeSenderType.CDE_JAVAJASON)
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(235, new TSM("QueuedSender", $"QSender Should NEVER GO HERE because SenderType is {MyTargetNodeChannel?.ToMLString()}", eMsgLevel.l1_Error));
                        IsInPost = false;
                        IsSenderThreadRunning = false;
                        return;
                    }
                    //NEW3.124: Sender Loop has to terminate if Cloud was Disabled.
                    if (MyTargetNodeChannel.SenderType == cdeSenderType.CDE_CLOUDROUTE && (TheBaseAssets.MyServiceHostInfo.IsCloudDisabled || string.IsNullOrEmpty(TheBaseAssets.MyServiceHostInfo.ServiceRoute) || !TheBaseAssets.MyServiceHostInfo.HasServiceRoute(TargetUri)))  //ServiceRoute can contain multiple routes...
                    {
                        break;
                    }
                    TheCoreQueueContent tQueued = null;
                    int MCQCount  = 0;
                    int IsBatchOn = 0;
#if CDE_NET35
                    tSendBufferStr = new StringBuilder(TheBaseAssets.MAX_MessageSize[(int)MyTargetNodeChannel.SenderType] * 2);
#else
                    tSendBufferStr.Clear();
#endif
                    tSendBufferStr.Append("[");
                    byte[] BinSendBuffer = null;
                    do
                    {
                        if (!IsConnected)
                        {
                            tQueued        = new TheCoreQueueContent();
                            IsConnecting   = true;
                            ConnectRetries = 0;
                            if (CloudInRetry)
                            {
                                var count = Interlocked.Increment(ref CloudRetryCount);
                                if (count > 10)
                                {
                                    int delaySeconds = TheBaseAssets.MyServiceHostInfo.HeartbeatDelay * TheBaseAssets.MyServiceHostInfo.TO.HeartBeatRate;
                                    TheBaseAssets.MySYSLOG.WriteToLog(235, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("QueuedSender", $"Too many retries for {MyTargetNodeChannel?.ToMLString()}: {count}. Waiting {delaySeconds} seconds.", eMsgLevel.l2_Warning));
                                    TheCommonUtils.SleepOneEye((uint)delaySeconds * 1000, 100);
                                    Interlocked.Exchange(ref CloudRetryCount, 0);
                                }
                                if (!TheBaseAssets.MasterSwitch || !IsAlive || !IsSenderThreadRunning || (MyTargetNodeChannel.SenderType == cdeSenderType.CDE_CLOUDROUTE &&
                                                                                                          (TheBaseAssets.MyServiceHostInfo.IsCloudDisabled || string.IsNullOrEmpty(TheBaseAssets.MyServiceHostInfo.ServiceRoute) || !TheBaseAssets.MyServiceHostInfo.HasServiceRoute(TargetUri))))
                                {
                                    //Very rare but required after Sleep
                                    throw new Exception("QSender had to be terminated in Cloud Retry due to disabling of ServiceRoute or C-DEngine Shutdown");
                                }
                            }//NEW3.124: Sender Loop has to terminate if Cloud was Disabled.
                            if (MyTargetNodeChannel.SenderType == cdeSenderType.CDE_CLOUDROUTE && (TheBaseAssets.MyServiceHostInfo.IsCloudDisabled || string.IsNullOrEmpty(TheBaseAssets.MyServiceHostInfo.ServiceRoute) || !TheBaseAssets.MyServiceHostInfo.HasServiceRoute(TargetUri)))
                            {
                                break;
                            }
                        }
                        else
                        {
                            if (CloudInRetry)
                            {
                                CloudInRetry = false;
                                IsInPost     = false;
                                continue;
                            }
                            tQueued = GetNextMessage(out MCQCount);
                        }
                        if (tQueued != null)
                        {
                            TheCDEKPIs.IncrementKPI(eKPINames.QSSent);

                            if (tQueued.OrgMessage == null && !IsConnecting)
                            {
                                if (MySubscriptions.Count == 0)
                                {
                                    if (IsBatchOn == 0) //Only jump out if no telegrams are in batch..
                                    {
                                        IsInPost = false;
                                        continue;
                                    }
                                }
                                if (IsBatchOn == 0) //If telegrams are in the batch dont send short message
                                {
                                    BinSendBuffer    = new byte[1];
                                    BinSendBuffer[0] = (byte)((int)(TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.SenderType)).ToString()[0];
                                    break;
                                }
                            }
                            if (tQueued.OrgMessage != null && tQueued.OrgMessage.ToCloudOnly() && MyTargetNodeChannel.SenderType == cdeSenderType.CDE_CLOUDROUTE)
                            {
                                tQueued.OrgMessage.SetToCloudOnly(false);
                            }

                            TheDeviceMessage tDev = new TheDeviceMessage
                            {
                                DID = TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString() // MyTargetNodeChannel.cdeMID.ToString();
                            };

                            if (MyTargetNodeChannel.MySessionState != null)
                            {
                                //BUGFIX: After fast Cloud Disconnect/reconnect-Relay lost Scopeing because it Scope was not properly stored in SessionState
                                if (string.IsNullOrEmpty(MyTargetNodeChannel.MySessionState.SScopeID) && TheBaseAssets.MyScopeManager.IsScopingEnabled)
                                {
                                    MyTargetNodeChannel.MySessionState.SScopeID = TheBaseAssets.MyScopeManager.GetScrambledScopeID();       //GRSI: rare
                                }
                                if (TheBaseAssets.MyServiceHostInfo.EnableFastSecurity)
                                {
                                    tDev.SID = MyTargetNodeChannel.MySessionState.SScopeID;
                                }
                                else
                                {
                                    tDev.SID = TheBaseAssets.MyScopeManager.GetScrambledScopeID(MyTargetNodeChannel.MySessionState.SScopeID, false); //GRSI: high frequency!
                                }
                            }
                            else
                            {
                                tDev.SID = TheBaseAssets.MyScopeManager.GetScrambledScopeID();      //GRSI: rare
                            }
                            tDev.MSG = tQueued.OrgMessage;
                            tDev.FID = "1";
                            if (IsConnecting)
                            {
                                tDev.TOP = TheCommCore.SetConnectingBufferStr(MyTargetNodeChannel, null);
                            }
                            else
                            {
                                tDev.TOP = tQueued.Topic;
                                tQueued.OrgMessage?.GetNextSerial(tQueued.SubMsgCnt);
                                if (MyTargetNodeChannel.MySessionState != null)
                                {
                                    tDev.FID = MyTargetNodeChannel.MySessionState.GetNextSerial().ToString(); //(SendCounter + 1).ToString();    //V3B3: New was empty //V4.1010: Same as WS now
                                }
                            }

                            #region Batch Serialization
                            IsBatchOn++;
                            if (MCQCount == 0 || IsBatchOn > TheBaseAssets.MyServiceHostInfo.MaxBatchedTelegrams || tQueued.IsChunked)
                            {
                                if (MCQCount != 0)
                                {
                                    tDev.CNT = MCQCount;
                                }
                                IsBatchOn = 0;
                            }
                            else
                            {
                                if (tSendBufferStr.Length > TheBaseAssets.MAX_MessageSize[(int)MyTargetNodeChannel.SenderType])
                                {
                                    tDev.CNT  = MCQCount;
                                    IsBatchOn = 0;
                                }
                            }
                            if (tSendBufferStr.Length > 1)
                            {
                                tSendBufferStr.Append(",");
                            }
                            tSendBufferStr.Append(TheCommonUtils.SerializeObjectToJSONString(tDev));
                            #endregion
                        }
                        else
                        {
                            IsBatchOn = 0;
                        }
                    } while (IsBatchOn > 0 && IsInPost && TheBaseAssets.MasterSwitch);
                    if ((!IsInPost || tSendBufferStr.Length < 2) && BinSendBuffer == null)
                    {
                        IsInPost = false;
                        continue;
                    }

                    string tMimeType = "application/octet-stream";
                    if (BinSendBuffer == null)
                    {
                        tSendBufferStr.Append("]");
                        if (MyTargetNodeChannel.SenderType == cdeSenderType.CDE_MINI || TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.SenderType == cdeSenderType.CDE_MINI)
                        {
                            tMimeType     = "application/json";
                            BinSendBuffer = TheCommonUtils.CUTF8String2Array(tSendBufferStr.ToString());
                        }
                        else
                        {
                            tMimeType     = "application/x-gzip";
                            BinSendBuffer = TheCommonUtils.cdeCompressString(tSendBufferStr.ToString());
                        }
                    }
                    if (MyTargetNodeChannel == null)
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(235, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("QueuedSender", $"Channel was deleted - exiting SenderThread", eMsgLevel.l2_Warning));
                        IsInPost = false;
                        break;
                    }
                    string         ISBPath = new Uri(TargetUri, TheBaseAssets.MyScopeManager.GetISBPath(TargetUriPath, TheCommonUtils.GetOriginST(MyTargetNodeChannel), MyTargetNodeChannel.SenderType, MyTargetNodeChannel.MySessionState == null? 1: MyTargetNodeChannel.MySessionState.FID /*Interlocked.Increment(ref SendCounter)*/, (MyTargetNodeChannel.MySessionState == null || !IsConnected) ?Guid.Empty: MyTargetNodeChannel.MySessionState.cdeMID, MyTargetNodeChannel.IsWebSocket)).ToString(); //V3B4: changed from TheBaseAssets.MyServiceHostInfo.MyDeviceInfo
                    TheRequestData pData   = new TheRequestData
                    {
                        RemoteAddress    = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false),
                        RequestUri       = new Uri(ISBPath),
                        PostData         = BinSendBuffer,
                        ResponseMimeType = tMimeType,
                        DeviceID         = TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID,
                        HttpMethod       = "POST"
                    };
                    if (!TheCertificates.SetClientCert(pData, MyTargetNodeChannel?.ClientCertificateThumb))
                    {
                        throw new Exception("Client Certificate could not be added");
                    }
                    MyREST.PostRESTAsync(pData, sinkUploadDataCompleted, FireSenderProblem);
                    if (BinSendBuffer != null)
                    {
                        TheCDEKPIs.IncrementKPI(eKPINames.QKBSent, BinSendBuffer.Length);
                    }

                    IsInPost = false;
                }
                FlushQueue();
                TheBaseAssets.MySYSLOG.WriteToLog(235, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("QueuedSender", $"QSenderThread was closed for {MyTargetNodeChannel?.ToMLString()}", eMsgLevel.l6_Debug));
            }
            catch (Exception e)
            {
                IsInPost = false;
                TheBaseAssets.MySYSLOG.WriteToLog(235, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("QueuedSender", "Exception in jcSenderThread.", eMsgLevel.l1_Error, "Error:" + e));
                if (MyTargetNodeChannel?.SenderType != cdeSenderType.CDE_BACKCHANNEL)
                {
                    FireSenderProblem(new TheRequestData()
                    {
                        ErrorDescription = $"1308:{e}"
                    });
                }
            }
            finally
            {
                IsSenderThreadRunning = false;
                IsAlive      = false;
                IsInPost     = false;
                CloudInRetry = false;
                StopHeartBeat();
            }
        }
示例#19
0
        void SendEmail(string pText)
        {
            try
            {
                MailMessage mail       = new MailMessage();
                SmtpClient  SmtpServer = new SmtpClient(MyBaseThing.Address);

                mail.From = new MailAddress(FromAddress);
                string receipt     = Recipient;
                string credentials = Credentials;
                if (TheCommonUtils.IsNullOrWhiteSpace(receipt))
                {
                    receipt = "*****@*****.**";
                }
                mail.To.Add(receipt);
                if (string.IsNullOrEmpty(SubjectText))
                {
                    mail.Subject = TheBaseAssets.MyServiceHostInfo.ApplicationName + " Message";
                }
                else
                {
                    mail.Subject = SubjectText;
                }
                if (!TheCommonUtils.IsNullOrWhiteSpace(pText))
                {
                    mail.Body = pText;
                }
                else
                {
                    mail.Body = MessageText;
                }
                if (credentials.Equals("Admin"))
                {
                    string AdminUsername = MyBaseEngine.GetBaseThing().GetProperty("AdminUsername", false).ToString();
                    string AdminServer   = MyBaseEngine.GetBaseThing().GetProperty("AdminServer", false).ToString();
                    string AdminPassword = MyBaseEngine.GetBaseThing().GetProperty("AdminPassword", false).GetValue().ToString();
                    int    AdminPort     = int.Parse(MyBaseEngine.GetBaseThing().GetProperty("AdminPort", false).ToString());
                    SmtpServer.Credentials = new System.Net.NetworkCredential(AdminUsername, AdminPassword);
                    SmtpServer.Host        = AdminServer;
                    SmtpServer.Port        = AdminPort;
                    string AdminSsl = MyBaseEngine.GetBaseThing().GetProperty("AdminSsl", false).ToString();
                    if (AdminSsl.Equals("True"))
                    {
                        SmtpServer.EnableSsl = true;
                    }
                }
                else
                {
                    SmtpServer.Port        = Port;
                    SmtpServer.Credentials = new System.Net.NetworkCredential(UserName, Password);
                    if (UseSsl)
                    {
                        SmtpServer.EnableSsl = true;
                    }
                }

                SmtpServer.Send(mail);
                ResultText = "Mail Sent to " + Recipient;

                TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), "SET_LAST_MSG", string.Format("eMail: Subject:{2} Body:{3} From {0} at {1}", TheBaseAssets.MyServiceHostInfo.MyStationName, DateTimeOffset.Now, SubjectText, mail.Body));
                MyBaseEngine.ProcessMessage(new TheProcessMessage(tTSM));
                TheCommCore.PublishCentral(tTSM);
            }
            catch (Exception ex)
            {
                ResultText = ex.ToString();
            }
        }
示例#20
0
        private void CreateLogTable(int StartFld, int pParentFld)
        {
            TheFormInfo tBackup = TheNMIEngine.AddForm(new TheFormInfo(TheThing.GetSafeThingGuid(MyBaseThing, "BKUPFORM"), eEngineName.NMIService, "Log Files", MyLogFilesTableName)
            {
                GetFromServiceOnly = true, TileWidth = -1, OrderBy = "BackupTime desc", TileHeight = 4
            });

            TheNMIEngine.AddFields(tBackup, new List <TheFieldInfo>
            {
                { new TheFieldInfo()
                  {
                      FldOrder = 11, DataItem = "BackupTime", Flags = 0, Type = eFieldType.DateTime, Header = "Log Create Date", FldWidth = 2
                  } },
                { new TheFieldInfo()
                  {
                      FldOrder = 12, DataItem = "Title", Flags = 0, Type = eFieldType.SingleEnded, Header = "Log Name", FldWidth = 7
                  } },
                { new TheFieldInfo()
                  {
                      FldOrder = 13, DataItem = "BackupSize", Flags = 0, Type = eFieldType.SingleEnded, Header = "Log Size", FldWidth = 2
                  } },
                { new TheFieldInfo()
                  {
                      FldOrder = 100, DataItem = "CDE_DELETE", Flags = 2, cdeA = 0x80, Type = eFieldType.TileButton, TileWidth = 1, TileHeight = 1
                  } },
            });
            TheFieldInfo btnDownload = TheNMIEngine.AddSmartControl(MyBaseThing, tBackup, eFieldType.TileButton, 1, 2, 0x0, "<i class='fa fa-3x'>&#xf019;</i>", "", new nmiCtrlTileButton()
            {
                ClassName = "cdeTableButton", TileHeight = 1, TileWidth = 1
            });

            btnDownload.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "DOWNLOAD", (pThing, pObj) =>
            {
                TheProcessMessage pMsg = pObj as TheProcessMessage;
                if (pMsg?.Message == null)
                {
                    return;
                }

                string[] pCmds = pMsg.Message.PLS.Split(':');
                if (pCmds.Length > 2)
                {
                    TheBackupDefinition tFile = MyLogFiles.GetEntryByID(TheCommonUtils.CGuid(pCmds[2]));
                    if (tFile != null)
                    {
                        TSM tFilePush = new TSM(eEngineName.ContentService, string.Format("CDE_FILE:{0}.txt:text/text", tFile.Title));
                        try
                        {
                            using (FileStream fr = new FileStream(tFile.FileName, FileMode.Open))
                            {
                                using (BinaryReader br = new BinaryReader(fr))
                                {
                                    tFilePush.PLB = br.ReadBytes((int)fr.Length);
                                }
                            }
                        }
                        catch (Exception)
                        { }
                        if (tFilePush.PLB == null)
                        {
                            TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Log cannot be downloaded..."));
                        }
                        else
                        {
                            TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Log is downloading. Please wait"));
                            tFilePush.SID = pMsg.Message.SID;
                            tFilePush.PLS = "bin";
                            TheCommCore.PublishToOriginator(pMsg.Message, tFilePush);
                        }
                    }
                }
            });

            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.CollapsibleGroup, StartFld, 2, 0x0, "Logs on Node...", null, new nmiCtrlCollapsibleGroup {
                TileWidth = 12, IsSmall = true, DoClose = true, ParentFld = pParentFld, AllowHorizontalExpand = true, MaxTileWidth = 12
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.Table, StartFld + 1, 0, 0, null, tBackup.cdeMID.ToString(), new nmiCtrlTableView {
                TileWidth = -1, IsDivOnly = true, ParentFld = StartFld, NoTE = true, TileHeight = -1, MID = TheThing.GetSafeThingGuid(MyBaseThing, "LOGMID"), MainClassName = "cdeInFormTable"
            });
        }
示例#21
0
        internal static void DoExecuteCommand(string pInTopicBatch, TheQueuedSender pQSender, bool DoSendBackBuffer, TheRequestData pRequestData, List <TheDeviceMessage> pDevMessageList)
        {
            bool SendPulse = false;

            if (pDevMessageList != null && pDevMessageList.Count > 0)
            {
                foreach (TheDeviceMessage pDevMessage in pDevMessageList)
                {
                    TSM    recvMessage = null;
                    string tTopic      = "";
                    try
                    {
                        var    tTargetNodeChannel = pQSender?.MyTargetNodeChannel;
                        string pInTopic           = pInTopicBatch;
                        if (string.IsNullOrEmpty(pInTopic))
                        {
                            pInTopic = pDevMessage.TOP;
                        }
                        recvMessage = pDevMessage.MSG;
                        if (pQSender != null && tTargetNodeChannel != null && tTargetNodeChannel.SenderType == cdeSenderType.CDE_JAVAJASON && recvMessage != null && string.IsNullOrEmpty(recvMessage.ORG))
                        {
                            recvMessage.ORG = tTargetNodeChannel.cdeMID.ToString();
                        }

                        #region ChunkResassembly
                        string[] CommandParts = null;
                        if (!string.IsNullOrEmpty(pInTopic))
                        {
                            CommandParts = TheCommonUtils.cdeSplit(pInTopic, ":,:", false, false);
                            tTopic       = CommandParts[0];
                        }
                        TheCDEKPIs.IncrementKPI(eKPINames.CCTSMsReceived);
                        if (CommandParts != null && CommandParts.Length == 4 && !CommandParts[2].Equals("1"))
                        {
                            if (!TheCommonUtils.ProcessChunkedMessage(CommandParts, recvMessage))
                            {
                                SendPulse = true;
                                continue;
                            }
                        }
                        #endregion

                        if (recvMessage != null)
                        {
                            if (((TheBaseAssets.MyServiceHostInfo.RejectIncomingSETP && recvMessage.TXT?.StartsWith("SETP:") == true) || TheBaseAssets.MyServiceHostInfo.DisableNMIMessages) && recvMessage.ENG?.StartsWith(eEngineName.NMIService) == true)
                            {
                                TheCDEKPIs.IncrementKPI(eKPINames.QSSETPRejected);
                                continue;
                            }
                            var tTopicSens  = tTopic.Split('@')[0]; //only topic - no ScopeID
                            var tTopicParts = tTopic.Split(';');
                            if (tTargetNodeChannel.SenderType == cdeSenderType.CDE_JAVAJASON)
                            {
                                //4.209: JavaJason does no longer get the scope ID - hence telegrams coming from the browser have to be ammmended with SID here
                                if (string.IsNullOrEmpty(recvMessage.SID) && !string.IsNullOrEmpty(pRequestData?.SessionState?.SScopeID))
                                {
                                    recvMessage.SID = pRequestData?.SessionState?.SScopeID; //Set the ScopeID in the SID of the message
                                    if (tTopic.StartsWith("CDE_SYSTEMWIDE"))
                                    {
                                        tTopic = $"{tTopicParts[0]}@{recvMessage.SID}";
                                        if (tTopicParts.Length > 1)
                                        {
                                            tTopic += $";{tTopicParts[1]}"; //if a direct address is added use this too
                                        }
                                    }
                                    else if (!tTopic.Contains('@'))
                                    {
                                        tTopic += $"@{recvMessage.SID}";
                                    }
                                    if (recvMessage.TXT == "CDE_SUBSCRIBE" || recvMessage.TXT == "CDE_INITIALIZE")
                                    {
                                        string MsgNoSID = null;
                                        recvMessage.PLS = TheBaseAssets.MyScopeManager.AddScopeID(recvMessage.PLS, recvMessage.SID, ref MsgNoSID, false, false);
                                    }
                                }
                            }
                            if (tTopicParts.Length > 1)
                            {
                                tTopicSens += $";{tTopicParts[1]}";                                                                                                                                                                                                               //if a direct address is added use this too
                            }
                            if (TheQueuedSenderRegistry.WasTSMSeenBefore(recvMessage, pRequestData.SessionState.cdeMID, tTopicSens, tTargetNodeChannel?.RealScopeID))                                                                                                             //ATTENTION: RScope should come from pDevMessage
                            {
                                TheBaseAssets.MySYSLOG.WriteToLog(285, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("CoreComm", $"EnterExecuteCommand: Message was seen before ORG:{TheCommonUtils.GetDeviceIDML(recvMessage?.ORG)} Topic:{tTopicSens}", eMsgLevel.l2_Warning)); //ORG-OK
                                TheCDEKPIs.IncrementKPI(eKPINames.QSRejected);
                                continue;
                            }
                            if (tTargetNodeChannel.cdeMID == Guid.Empty)
                            {
                                tTargetNodeChannel.cdeMID = recvMessage.GetLastRelay();
                            }
                            if (tTargetNodeChannel.SenderType == cdeSenderType.NOTSET)
                            {
                                TheBaseAssets.MySYSLOG.WriteToLog(285, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("CoreComm", "Sender Type for the QSender is not set! WE SHOULD NEVER GET HERE", eMsgLevel.l1_Error));//ORG-OK
                                //3.218: Processing no longer allowed!!!
                                return;
                            }
                            // Enable upper layers to do RSA decryption. Force overwrite for Browser even if SEID already set (may have been initialized to some other value)
                            if (tTargetNodeChannel.SenderType == cdeSenderType.CDE_JAVAJASON || String.IsNullOrEmpty(recvMessage.SEID))
                            {
                                recvMessage.SEID = pRequestData.SessionState.cdeMID.ToString();
                            }

                            if (pRequestData.SessionState != null && string.IsNullOrEmpty(pRequestData.SessionState.RemoteAddress))
                            {
                                pRequestData.SessionState.RemoteAddress = tTargetNodeChannel.cdeMID.ToString();
                            }

                            //NEW: User ID Management in Message after first node
                            if (string.IsNullOrEmpty(recvMessage.UID) && pRequestData.SessionState != null && pRequestData.SessionState.CID != Guid.Empty)
                            {
                                recvMessage.UID = TheCommonUtils.cdeEncrypt(pRequestData.SessionState.CID.ToByteArray(), TheBaseAssets.MySecrets.GetAI());     //3.083: Must be cdeAI
                            }
                        }
                    }
                    catch (Exception ee)
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(319, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("CoreComm", "Execute Command Pre-Parsing Error", eMsgLevel.l1_Error, ee.ToString()));
                    }

                    if (recvMessage == null)
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(286, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("CoreComm", $"No Message for Parsing: Topic:{tTopic} - {pRequestData.ResponseBufferStr}", eMsgLevel.l7_HostDebugMessage));
                    }
                    else
                    {
                        if (recvMessage.PLB != null && recvMessage.PLB.Length > 0 && string.IsNullOrEmpty(recvMessage.PLS))
                        {
                            try
                            {
                                recvMessage.PLS = TheCommonUtils.cdeDecompressToString(recvMessage.PLB);
                                recvMessage.PLB = null;
                            }
                            catch (Exception)
                            {
                                TheBaseAssets.MySYSLOG.WriteToLog(286, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("CoreComm", $"PLB to PLS decompress failed - Topic:{tTopic} Node:{pQSender?.MyTargetNodeChannel?.ToMLString()} ORG:{TheCommonUtils.GetDeviceIDML(recvMessage?.ORG)}", eMsgLevel.l7_HostDebugMessage, $"TXT:{recvMessage.TXT}"));//ORG-OK
                            }
                        }

                        TheBaseAssets.MySYSLOG.WriteToLog(286, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("CoreComm", $"PLB to PLS parsing done - Topic:{tTopic} Node:{pQSender?.MyTargetNodeChannel?.ToMLString()} ORG:{TheCommonUtils.GetDeviceIDML(recvMessage?.ORG)}", eMsgLevel.l7_HostDebugMessage, $"TXT:{recvMessage.TXT}"));//ORG-OK
                        if (!SendPulse)
                        {
                            SendPulse = recvMessage.SendPulse();
                        }
                        TheCDEKPIs.IncrementKPI(eKPINames.CCTSMsEvaluated);
                    }

                    try
                    {
                        if (recvMessage != null && !string.IsNullOrEmpty(tTopic)) // tTopic != null)
                        {
                            if (!ParseSimplex(tTopic, recvMessage, pQSender))     //NEW:2.06 - No More Local Host processing here
                            {
                                if (TheBaseAssets.MyServiceHostInfo.MaximumHops == 0 || recvMessage.HobCount() < TheBaseAssets.MyServiceHostInfo.MaximumHops)
                                {
                                    if (!tTopic.StartsWith("CDE_CONNECT") || !TheBaseAssets.MyServiceHostInfo.AllowMessagesInConnect) // Should never get here if AllowMessagesInConnect is false, but avoid global publish just in case...
                                    {
                                        TheCDEKPIs.IncrementKPI(eKPINames.CCTSMsRelayed);
                                        TheCommCore.PublishCentral(tTopic, recvMessage, false, null, false, pQSender?.MyTargetNodeChannel?.IsTrustedSender ?? false);
                                    }
                                    else
                                    {
                                        // Message is part of a CDE_CONNECT: Republish it to enable single-post message sending (i.e. MSB/Service Gateway scenario)
                                        TheCDEKPIs.IncrementKPI(eKPINames.CCTSMsRelayed); // TODO SHould we have a separate KPI for this
                                        TheCommCore.PublishCentral(recvMessage, true, pQSender.MyTargetNodeChannel.IsTrustedSender);
                                    }
                                }
                            }
                            else
                            {
                                if (pQSender?.MyTargetNodeChannel != null && pQSender?.MyTargetNodeChannel?.SenderType != cdeSenderType.CDE_JAVAJASON)
                                {
                                    SendPulse = true;
                                }
                            }
                        }
                    }
                    catch (Exception ee)
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(319, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("CoreComm", "Execute Command Parsing Error", eMsgLevel.l1_Error, ee.ToString()));
                    }
                    TheBaseAssets.MySYSLOG.WriteToLog(286, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("CoreComm", $"Done with Do Execute Command for Topic:{tTopic}", eMsgLevel.l7_HostDebugMessage));
                }
            }
            if (pRequestData.WebSocket == null)
            {
                if (DoSendBackBuffer)
                {
                    SetResponseBuffer(pRequestData, pQSender.MyTargetNodeChannel, SendPulse, "");
                }
                else if (SendPulse)
                {
                    pQSender.SendPickupMessage(); //Pickup next message right away if pulse mode is on
                }
            }
            TheBaseAssets.MySYSLOG.WriteToLog(286, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("CoreComm", "Leave Do Execute Command", eMsgLevel.l7_HostDebugMessage));
        }
示例#22
0
        internal static void SetResponseBuffer(TheRequestData pRequestData, TheChannelInfo pChannelInfo, bool pSendPulse, string NopTopic, Guid owner, string pRefreshToken)
        {
            if (string.IsNullOrEmpty(NopTopic))
            {
                TheQueuedSender tQ = null;
                if (pChannelInfo != null && pChannelInfo.cdeMID != Guid.Empty)    //Send to Device First
                {
                    tQ = TheQueuedSenderRegistry.GetSenderByGuid(pChannelInfo.cdeMID);
                }
                if (tQ != null)
                {
                    if (pRequestData.WebSocket != null)
                    {
                        if (tQ.GetQueLength() == 0)
                        {
                            tQ.SendPickupMessage();
                        }
                        return;
                    }
                    tQ.GetNextBackChannelBuffer(pRequestData);
                }
            }
            if (string.IsNullOrEmpty(NopTopic) && pRequestData.WebSocket != null)
            {
                return;                                                                   //NEW:3.084  && !pSendPulse removed          NEW:V3B3:2014-7-22 removed && pRequestData.ResponseBuffer != null
            }
            if (pRequestData.ResponseBuffer == null && pChannelInfo != null && (pSendPulse || (pChannelInfo.cdeMID != Guid.Empty || TheQueuedSenderRegistry.IsNodeIdInSenderList(pChannelInfo.cdeMID))))
            {
                TheDeviceMessage tDev = new TheDeviceMessage {
                    CNT = 0
                };
                //tDev.MET = 0;
                if (!string.IsNullOrEmpty(NopTopic))
                {
                    tDev.MSG = new TSM();   //Can be set without ORG and SID
                    if (owner != Guid.Empty)
                    {
                        tDev.MSG.OWN = owner.ToString();
                    }
                    if (NopTopic == "CDE_WSINIT")
                    {
                        NopTopic = TheCommCore.SetConnectingBufferStr(pChannelInfo, null);
                    }
                }
                if (pChannelInfo.SenderType != cdeSenderType.CDE_JAVAJASON) //4.209: No longer sending SID to Browser;
                {
                    if (TheBaseAssets.MyServiceHostInfo.EnableFastSecurity)
                    {
                        tDev.SID = pRequestData.SessionState.SScopeID;  //SECURITY: All responses will have same Scrambled ScopeID - but ok because this is init telegram or HB
                    }
                    else
                    {
                        tDev.SID = TheBaseAssets.MyScopeManager.GetScrambledScopeID(pRequestData.SessionState.SScopeID, false); //GRSI: high frequency
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(pRefreshToken))
                    {
                        tDev.SID = pRefreshToken;
                    }
                }
                tDev.FID = pRequestData.SessionState.GetNextSerial().ToString();
                if (TheCommonUtils.IsDeviceSenderType(pChannelInfo.SenderType)) //IDST-OK: Must create RSA for Devices
                {
                    TheCommonUtils.CreateRSAKeys(pRequestData.SessionState);
                    tDev.RSA = pRequestData.SessionState.RSAPublic;
                }
                tDev.NPA = TheBaseAssets.MyScopeManager.GetISBPath(TheBaseAssets.MyServiceHostInfo.RootDir, pChannelInfo.SenderType, TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.SenderType, pRequestData.SessionState.FID, pRequestData.SessionState.cdeMID, pRequestData.WebSocket != null);
                tDev.CNT = pSendPulse ? 1 : 0;
                tDev.TOP = NopTopic;
                tDev.DID = pChannelInfo.SenderType == cdeSenderType.CDE_JAVAJASON ? pChannelInfo.cdeMID.ToString() : TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString();

                //There will be only one Message here - single poke or Mini Command or NOP Pickup
                List <TheDeviceMessage> tDevList = new List <TheDeviceMessage> {
                    tDev
                };
                if (pChannelInfo.SenderType == cdeSenderType.CDE_JAVAJASON || TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.SenderType == cdeSenderType.CDE_MINI || pChannelInfo.SenderType == cdeSenderType.CDE_MINI || pRequestData.WebSocket != null)
                {
                    pRequestData.ResponseBuffer   = TheCommonUtils.CUTF8String2Array(TheCommonUtils.SerializeObjectToJSONString(tDevList));
                    pRequestData.ResponseMimeType = "application/json";
                }
                else
                {
                    pRequestData.ResponseBuffer   = TheCommonUtils.cdeCompressString(TheCommonUtils.SerializeObjectToJSONString(tDevList));
                    pRequestData.ResponseMimeType = "application/x-gzip";
                }
            }
            if (pRequestData.ResponseBuffer == null && pChannelInfo != null && pChannelInfo.cdeMID != Guid.Empty)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(290, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("CoreComm", $"Nothing to Send Back to {pChannelInfo?.ToMLString()}", eMsgLevel.l7_HostDebugMessage));
            }
        }
示例#23
0
        void SendSMS(string pText)
        {
            try
            {
                MailMessage mail       = new MailMessage();
                SmtpClient  SmtpServer = new SmtpClient(MyBaseThing.Address);

                mail.From = new MailAddress(FromAddress);
                string receipt     = Recipient;
                string credentials = Credentials;
                if (TheCommonUtils.IsNullOrWhiteSpace(receipt))
                {
                    receipt = "*****@*****.**";
                }
                string carrier = Carrier;

                // Code to handle carrier
                //TODO: Set Server name and SSL/Server and Port per Carrier
                #region Handle Carrier
                switch (carrier.ToLower())
                {
                case "t-mobile":
                    receipt += "@tmomail.net";
                    break;

                case "at&t":
                    receipt += "@txt.att.net";
                    break;

                case "sprint":
                    receipt += "@messaging.sprintpcs.com";
                    break;

                case "verizon":
                    receipt += "@vtext.com";
                    break;

                case "virgin mobile":
                    receipt += "@vmobl.com";
                    break;

                case "metro pcs":
                    receipt += "@MyMetroPcs";
                    break;

                case "alltel":
                    receipt += "@message.alltel.com";
                    break;

                case "powertel":
                    receipt += "@ptel.net";
                    break;

                case "suncom":
                    receipt += "@tms.suncom.com";
                    break;

                case "nextel":
                    receipt += "@messaging.nextel.com";
                    break;

                case "us cellular":
                    receipt += "@email.uscc.net";
                    break;

                case "boost mobile":
                    receipt += "@myboostmobile.com";
                    break;

                case "cingular":
                    receipt += "@cingularme.com";
                    break;
                }
                #endregion

                mail.To.Add(receipt);
                if (string.IsNullOrEmpty(SubjectText))
                {
                    mail.Subject = TheBaseAssets.MyServiceHostInfo.ApplicationName + " Message";
                }
                else
                {
                    mail.Subject = SubjectText;
                }
                if (!TheCommonUtils.IsNullOrWhiteSpace(pText))
                {
                    mail.Body = pText;
                }
                else
                {
                    mail.Body = MessageText;
                }

                if (credentials.Equals("Admin"))
                {
                    string AdminUsername = MyBaseEngine.GetBaseThing().GetProperty("AdminUsername", false).ToString();
                    string AdminServer   = MyBaseEngine.GetBaseThing().GetProperty("AdminServer", false).ToString();
                    string AdminPassword = MyBaseEngine.GetBaseThing().GetProperty("AdminPassword", false).GetValue().ToString();
                    int    AdminPort     = int.Parse(MyBaseEngine.GetBaseThing().GetProperty("AdminPort", false).ToString());
                    SmtpServer.Credentials = new System.Net.NetworkCredential(AdminUsername, AdminPassword);
                    SmtpServer.Host        = AdminServer;
                    SmtpServer.Port        = AdminPort;
                    string AdminSsl = MyBaseEngine.GetBaseThing().GetProperty("AdminSsl", false).ToString();
                    if (AdminSsl.Equals("True"))
                    {
                        SmtpServer.EnableSsl = true;
                    }
                }
                else
                {
                    SmtpServer.Credentials = new System.Net.NetworkCredential(UserName, Password);
                    SmtpServer.Port        = Port;
                    if (UseSsl)
                    {
                        SmtpServer.EnableSsl = true;
                    }
                }
                SmtpServer.Send(mail);
                ResultText = "SMS Sent to " + Recipient;

                TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), "SET_LAST_MSG", string.Format("SMS: Subject:{2} Body:{3} From {0} at {1}", TheBaseAssets.MyServiceHostInfo.MyStationName, DateTimeOffset.Now, SubjectText, mail.Body));
                MyBaseEngine.ProcessMessage(new TheProcessMessage(tTSM));
                TheCommCore.PublishCentral(tTSM);
            }
            catch (Exception ex)
            {
                ResultText = ex.ToString();
            }
        }
示例#24
0
        public override bool CreateUX()
        {
            if (TheBaseAssets.MyServiceHostInfo.IsCloudService)
            {
                mIsUXInitialized = true;
                return(true);
            }
            if (!TheNMIEngine.IsInitialized())
            {
                return(false);
            }
            if (mIsUXInitCalled)
            {
                return(false);
            }
            mIsUXInitCalled = true;

            MyDash = TheNMIEngine.AddDashboard(MyBaseThing, new TheDashboardInfo(MyBaseEngine, "Rules Engine")
            {
                FldOrder = 5000, cdeA = 0xC0, PropertyBag = new ThePropertyBag {
                    "Caption=Rules Engine", "Thumbnail=FA5:f546", "Category=Services"
                }
            });

            TheFormInfo tFormGuid = new TheFormInfo(new Guid("{6C34871C-D49B-4D7A-84E0-35E25B1F18B0}") /*TheThing.GetSafeThingGuid(MyBaseThing, "RULESREG")*/, eEngineName.NMIService, "The Rules Registry", $"TheThing;:;0;:;True;:;DeviceType={eKnownDeviceTypes.TheThingRule};EngineName={MyBaseEngine.GetEngineName()}")
            {
                GetFromFirstNodeOnly = true, IsNotAutoLoading = true, AddButtonText = "Add Rule", AddTemplateType = "44444444-6AD1-45AE-BE61-96AF02329613"
            };

            //TheNMIEngine.AddForm(tFormGuid);
            TheNMIEngine.AddFormToThingUX(MyDash, MyBaseThing, tFormGuid, "CMyTable", "Rules Registry", 5, 9, 128, TheNMIEngine.GetNodeForCategory(), null, new ThePropertyBag {
                "Thumbnail=FA5:f07b"
            });
            TheNMIEngine.AddFields(tFormGuid, new List <TheFieldInfo>
            {
                { new TheFieldInfo()
                  {
                      FldOrder = 10, DataItem = "MyPropertyBag.IsRuleActive.Value", Flags = 2, Type = eFieldType.SingleCheck, Header = "Active", FldWidth = 1, TileLeft = 2, TileTop = 6, TileWidth = 4, TileHeight = 1
                  } },
                { new TheFieldInfo()
                  {
                      FldOrder = 20, DataItem = "MyPropertyBag.IsRuleLogged.Value", Flags = 2, Type = eFieldType.SingleCheck, Header = "Logged", FldWidth = 1, TileLeft = 6, TileTop = 6, TileWidth = 4, TileHeight = 1
                  } },

                { new TheFieldInfo()
                  {
                      FldOrder = 30, DataItem = "MyPropertyBag.FriendlyName.Value", Flags = 2, Type = eFieldType.SingleEnded, Header = "Rule Name", FldWidth = 3, TileLeft = 0, TileTop = 1, TileWidth = 11, TileHeight = 1, PropertyBag = new nmiCtrlSingleEnded()
                      {
                          HelpText = "Give this rule a friendly name"
                      }
                  } },
                { new TheFieldInfo()
                  {
                      FldOrder = 137, DataItem = "cdeO", Flags = 16, Type = eFieldType.SingleEnded, Header = "Status", FldWidth = 3, Format = "<span style='font-size:xx-small'>Running:%MyPropertyBag.IsRuleRunning.Value%<br>TrigerAlive:%MyPropertyBag.IsTriggerObjectAlive.Value%</span>"
                  } },
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, tFormGuid, eFieldType.StatusLight, 35, 0x40, 0x0, "Status", "StatusLevel", new TheNMIBaseControl()
            {
                FldWidth = 1
            });


            TheNMIEngine.AddTableButtons(tFormGuid, true, 1000, 0xA2);

            TheFieldInfo tTriggerBut = TheNMIEngine.AddSmartControl(MyBaseThing, tFormGuid, eFieldType.TileButton, 5, 2, 0xC0, "Trigger Now", null, new nmiCtrlTileButton {
                ClassName = "cdeGoodActionButton", TileLeft = 1, TileTop = 6, TileWidth = 1, TileHeight = 1, NoTE = true
            });

            tTriggerBut.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "TriggerNow", (psender, 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]));
                    if (tThing == null)
                    {
                        return;
                    }
                    TheRule tRule = tThing.GetObject() as TheRule;
                    if (tRule != null)
                    {
                        tRule.FireAction(true);
                        TheCommCore.PublishToOriginator(pMSG.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", string.Format("Rule {0} triggered", tRule.FriendlyName)));
                    }
                }
            });

            TheNMIEngine.AddAboutButton4(MyBaseThing, MyDash, null, true, false, "REFRESH_DASH");

            AddRulesWizard();

            mIsUXInitialized = true;
            return(true);
        }
示例#25
0
        public virtual bool DoCreateUX()
        {
            MyEditorForm = new TheFormInfo(MyBaseThing)
            {
                DefaultView = eDefaultView.Form, PropertyBag = new ThePropertyBag {
                    "MaxTileWidth=6", "HideCaption=true", "AllowDrag=true"
                }
            };
            MyEditorForm.ModelID = "NMIEditor";

            TheDashboardInfo tDash = TheNMIEngine.GetDashboardById(TheNMIHtml5RT.eNMIDashboard);

            MyEditorDashIcon = TheNMIEngine.AddFormToThingUX(tDash, MyBaseThing, MyEditorForm, "CMyForm", "NMI Control Editor", 1, 0x89, 0x80, "NMI", null, new ThePropertyBag()
            {
                "RenderTarget=cdeInSideBarRight", "NeverHide=true"
            });                                                                                                                                                                                                                           //"mAllowDrag=true", "nVisibility=false",

            MySampleControl = TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.SingleEnded, 3, 2, MyBaseThing.cdeA, "CurrentValue", "Value", null);


            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.TileGroup, 9, 0, 0, null, null, new nmiCtrlTileGroup {
                TileWidth = 7, TileHeight = 1, TileFactorY = 2
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.TileButton, 10, 2, 0, "Basic", null, new nmiCtrlTileButton {
                ParentFld = 9, OnClick = "GRP:NMIP:Basic", TileWidth = 1, TileHeight = 1, TileFactorY = 2, NoTE = true, ClassName = "cdeTransitButton"
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.TileButton, 20, 2, 0, "Screen", null, new nmiCtrlTileButton {
                ParentFld = 9, OnClick = "GRP:NMIP:Screen", TileWidth = 1, TileHeight = 1, TileFactorY = 2, NoTE = true, ClassName = "cdeTransitButton"
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.TileButton, 30, 2, 0, "All", null, new nmiCtrlTileButton {
                ParentFld = 9, OnClick = "GRP:NMIP:All", TileWidth = 1, TileHeight = 1, TileFactorY = 2, NoTE = true, ClassName = "cdeTransitButton"
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.TileButton, 40, 2, 0, "Source", null, new nmiCtrlTileButton {
                ParentFld = 9, OnClick = "GRP:NMIP:Source", TileWidth = 1, TileHeight = 1, TileFactorY = 2, NoTE = true, ClassName = "cdeTransitButton"
            });
            //TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.TileButton, 50, 2, 0, "Compounds", null, new nmiCtrlTileButton { OnClick = "GRP:Cate:5", TileWidth = 2, TileHeight = 1, TileFactorY = 2, NoTE = true, ClassName = "cdeTransitButton" });
            //TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.TileButton, 60, 2, 0, "Gauges", null, new nmiCtrlTileButton {  OnClick = "GRP:Cate:6", TileWidth = 2, TileHeight = 1, TileFactorY = 2, NoTE = true, ClassName = "cdeTransitButton" });
            TheFieldInfo mSendbutton = TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.TileButton, 70, 2, 0x80, "Reload", false, "", null, new nmiCtrlTileButton()
            {
                ParentFld = 9, TileWidth = 2, NoTE = true, TileFactorY = 2, ClassName = "cdeGoodActionButton"
            });

            mSendbutton.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "", (pThing, pPara) =>
            {
                TheProcessMessage pMsg = pPara as TheProcessMessage;
                if (pMsg?.Message == null)
                {
                    return;
                }
                UpdateUx(pThing.GetBaseThing());
                MyEditorForm.Reload(pMsg, tDash.cdeMID, true);
            });

            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.TileGroup, 1000, 2, 0x80, null, null, new nmiCtrlTileGroup()
            {
                Group = "NMIP:Basic"
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.ComboBox, 1010, 2, 0x80, "Control Type", "ControlType", new ThePropertyBag()
            {
                "Options=%RegisteredControlTypes%", "ParentFld=1000"
            });
            GetProperty("ControlType", true).RegisterEvent(eThingEvents.PropertyChanged, (p) =>
            {
                UpdateUx(MyBaseThing);
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.Number, 1020, 2, 0, "Tile Width", "TileWidth", new nmiCtrlNumber()
            {
                ParentFld = 1000, TileHeight = 1, TileFactorY = 1, DefaultValue = "6", TileWidth = 3
            });
            GetProperty("TileWidth", true).RegisterEvent(eThingEvents.PropertyChanged, (p) =>
            {
                MySampleControl.SetUXProperty(Guid.Empty, "TileWidth= " + p.ToString());
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.Number, 1030, 2, 0, "Tile Height", "TileHeight", new nmiCtrlNumber()
            {
                ParentFld = 1000, TileHeight = 1, TileFactorY = 1, DefaultValue = "1", TileWidth = 3
            });
            GetProperty("TileHeight", true).RegisterEvent(eThingEvents.PropertyChanged, (p) =>
            {
                MySampleControl.SetUXProperty(Guid.Empty, "TileHeight= " + p.ToString());
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.ComboBox, 1040, 2, 0, "Horizontal Alignment", "HorizontalAlignment", new nmiCtrlComboBox()
            {
                ParentFld = 1000, Options = ";left;center;right"
            });
            GetProperty("HorizontalAlignment", true).RegisterEvent(eThingEvents.PropertyChanged, (p) =>
            {
                MySampleControl.SetUXProperty(Guid.Empty, "HorizontalAlignment= " + p.ToString());
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.ComboBox, 1050, 2, 0, "Class Name", "ClassName", new nmiCtrlComboBox()
            {
                ParentFld = 1000, Options = ";BlueWhite;GreenYellow;RedWhite"
            });
            GetProperty("ClassName", true).RegisterEvent(eThingEvents.PropertyChanged, (p) =>
            {
                MySampleControl.SetUXProperty(Guid.Empty, "ClassName= " + p.ToString());
            });

            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.SingleEnded, 1060, 2, 0, "HelpText", "HelpText", new nmiCtrlSingleEnded()
            {
                ParentFld = 1000
            });
            GetProperty("HelpText", true).RegisterEvent(eThingEvents.PropertyChanged, (p) =>
            {
                MySampleControl.SetUXProperty(Guid.Empty, "HelpText= " + p.ToString());
            });

            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.ComboBox, 1070, 2, 0, "Opacity", "Opacity", new nmiCtrlComboBox()
            {
                ParentFld = 1000, Options = ";0.1;0.3;0.5;0.7;0.9;1.0"
            });
            GetProperty("Opacity", true).RegisterEvent(eThingEvents.PropertyChanged, (p) =>
            {
                MySampleControl.SetUXProperty(Guid.Empty, "Opacity= " + p.ToString());
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.SingleCheck, 1080, 2, 0, "No TE", "NoTE", new nmiCtrlSingleCheck()
            {
                ParentFld = 1000
            });
            GetProperty("NoTE", true).RegisterEvent(eThingEvents.PropertyChanged, (p) =>
            {
                MySampleControl.SetUXProperty(Guid.Empty, "NoTE= " + p.ToString());
            });


            //Screen Properties
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.TileGroup, 3000, 2, 0x80, null, null, new nmiCtrlTileGroup()
            {
                Group = "NMIP:Screen", Visibility = false
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.ComboOption, 3010, 2, 0x80, "NMI Screen", "FormName", new ThePropertyBag()
            {
                "Options=%GetLiveScreens%", "TileWidth=6", "TileHeight=1", "ParentFld=3000"
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.CheckField, 3020, 2, 0x80, "Flags", "Flags", new ThePropertyBag()
            {
                "Bits=6", "TileHeight=6", "TileFactorY=2",
                "ImageList=<span class='fa-stack'><i class='fa fa-stack-1x'>&#xf21b;</i><i class='fa fa-stack-2x'>&#x2003;</i></span>," +
                "<span class='fa-stack'><i class='fa fa-stack-1x'>&#xf044;</i><i class='fa fa-stack-2x'>&#x2003;</i></span>," +
                "<span class='fa-stack'><i class='fa fa-stack-1x'>&#xf10b;</i><i class='fa fa-stack-2x text-danger' style='opacity:0.5'>&#xf05e;</i></span>," +
                "<span class='fa-stack'><i class='fa fa-stack-1x'>&#xf0ce;</i><i class='fa fa-stack-2x text-danger' style='opacity:0.5'>&#xf05e;</i></span>," +
                "<span class='fa-stack'><i class='fa fa-stack-1x'>&#xf0f6;</i><i class='fa fa-stack-2x text-danger' style='opacity:0.5'>&#xf05e;</i></span>," +
                "<span class='fa-stack'><i class='fa fa-stack-1x'>&#xf15c;</i><i class='fa fa-stack-2x text-danger' style='opacity:0.5'>&#xf05e;</i></span>", "ParentFld=3000"
            }).FldWidth = 1;

            //ALL Properties
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.TileGroup, 2000, 2, 0x80, null, null, new nmiCtrlTileGroup()
            {
                TileWidth = 6, Group = "NMIP:All", Visibility = false
            });

            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.Table, 2010, 0xA2, 0x80, "All Properties", "mypropertybag;1", new ThePropertyBag()
            {
                "NoTE=true", "TileHeight=4", "TileLeft=9", "TileTop=3", "TileWidth=6", "FldWidth=6", "ParentFld=2000"
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.SingleEnded, 2020, 0x0A, 0, "New Property Name", "ScratchName", new nmiCtrlSingleEnded()
            {
                ParentFld = 2000
            });
            TheFieldInfo tBut = TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.TileButton, 2040, 0x0A, 0, "Add Property", false, null, null, new nmiCtrlTileButton()
            {
                ParentFld = 2000, NoTE = true, ClassName = "cdeGoodActionButton"
            });

            tBut.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "AddProp", (pThing, pObj) =>
            {
                TheProcessMessage pMsg = pObj as TheProcessMessage;
                if (pMsg?.Message == null)
                {
                    return;
                }
                string[] parts = pMsg.Message.PLS.Split(':');
                TheThing tOrg  = pThing.GetBaseThing(); // TheThingRegistry.GetThingByMID(MyBaseEngine.GetEngineName(), TheCommonUtils.CGuid(parts[2]));
                //if (tOrg == null) return;

                string tNewPropName = TheThing.GetSafePropertyString(tOrg, "ScratchName");
                if (string.IsNullOrEmpty(tNewPropName))
                {
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Please specify a new property name"));
                }
                else
                {
                    if (tOrg.GetProperty(tNewPropName) != null)
                    {
                        TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Property already exists"));
                    }
                    else
                    {
                        tOrg.DeclareNMIProperty(tNewPropName, ePropertyTypes.TString);
                        TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Property Added"));
                        MyEditorForm.Reload(pMsg, false);
                    }
                    tOrg.SetProperty("ScratchName", "");
                }
            });

            //THING Connector
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.TileGroup, 5000, 2, 0x80, null, null, new nmiCtrlTileGroup()
            {
                TileWidth = 6, Group = "NMIP:Source", Visibility = false
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.ThingPicker, 5010, 2, 0x80, "Source Thing", "Address", new nmiCtrlThingPicker()
            {
                ParentFld = 5000, IncludeEngines = true
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.PropertyPicker, 5020, 2, 0x80, "Source Property", "SourceProp", new nmiCtrlPropertyPicker()
            {
                ParentFld = 5000, ThingFld = 5010
            });

            TheFieldInfo mSendbutton2 = TheNMIEngine.AddSmartControl(MyBaseThing, MyEditorForm, eFieldType.TileButton, 5050, 2, 0x80, "Engage", false, "", null, new nmiCtrlTileButton()
            {
                NoTE = true, TileWidth = 6, ClassName = "cdeGoodActionButton", ParentFld = 5000
            });

            mSendbutton2.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "", (pThing, pPara) =>
            {
                TheProcessMessage pMsg = pPara as TheProcessMessage;
                if (pMsg?.Message == null)
                {
                    return;
                }
                UpdateUx(pThing.GetBaseThing());
            });
            UpdateUx(MyBaseThing);
            return(true);
        }
示例#26
0
        public override void HandleMessage(ICDEThing sender, object pIncoming)
        {
            TheProcessMessage pMsg = pIncoming as TheProcessMessage;

            if (pMsg == null || 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_REGISTERRULE":
                TheRule tRule = TheCommonUtils.DeserializeJSONStringToObject <TheRule>(pMsg.Message.PLS);
                if (tRule != null)
                {
                    RegisterRule(tRule);
                }
                break;

            case "CLAIM_RULES":
                List <TheThing> tList = TheThingRegistry.GetThingsByFunc(eEngineName.ThingService, s => TheThing.GetSafePropertyString(s, "DeviceType").Equals(eKnownDeviceTypes.TheThingRule));
                if (tList != null && tList.Count > 0)
                {
                    foreach (TheThing tThing in tList)
                    {
                        tThing.Parent     = MyBaseThing.ID;
                        tThing.EngineName = MyBaseEngine.GetEngineName();
                    }
                }
                ActivateRules();
                MyDash.Reload(null, false);
                TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", $"{tList.Count} New Rules claimed"));
                break;

            case "REFRESH_DASH":
                ActivateRules();
                MyDash.Reload(null, false);
                break;

            case "FIRE_RULE":
                var t = TheThingRegistry.GetThingByMID(MyBaseEngine.GetEngineName(), TheCommonUtils.CGuid(pMsg?.Message?.PLS));
                if (t != null)
                {
                    TheRule tR = t.GetObject() as TheRule;
                    if (tR != null)
                    {
                        tR.RuleTrigger(tR.TriggerOldValue, true);
                    }
                }
                break;
            }
        }
        private void InterceptHttpRequest(TheRequestData pRequest, Guid MyApp, IBaseEngine MyBaseEngine, int pRequestTimeout) // TheRelayAppInfo MyApp)
        {
            if (MyApp == Guid.Empty)
            {
                return;
            }
            TheRequestData tOutBuffer = null;
            //NEW BY CM
            string tMagixc = Guid.NewGuid().ToString();

            ReqBuffer.AddOrUpdateItem(TheCommonUtils.CGuid(tMagixc), null, null);
            if (!MyBaseEngine.GetEngineState().IsService) // || string.IsNullOrEmpty(MyApp.TargetUrl) || !TheCommonUtils.IsLocalhost(MyApp.HostUrl)) //  !MyApp.HostUrl.Equals(TheBaseAssets.MyServiceHostInfo.MyStation URL))
            {
                TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), "WEBRELAY_REQUEST")
                {
                    PLB = pRequest.PostData
                };
                pRequest.PostData       = null;
                pRequest.ResponseBuffer = null;
                if (!string.IsNullOrEmpty(pRequest.CookieString))
                {
                    pRequest.CookieString += ";";
                }
                else
                {
                    pRequest.CookieString = "";
                }
                pRequest.CookieString += tMagixc;
                //if (string.IsNullOrEmpty(MyApp.CloudUrl)) MyApp.CloudUrl = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false);
                if (string.IsNullOrEmpty(TheBaseAssets.MyServiceHostInfo.RootDir))
                {
                    pRequest.RequestUriString = pRequest.RequestUri.ToString();
                }
                else
                {
                    pRequest.RequestUriString = pRequest.RequestUri.Scheme + "://" + pRequest.RequestUri.Host + ":" + pRequest.RequestUri.Port + pRequest.cdeRealPage;
                    if (!string.IsNullOrEmpty(pRequest.RequestUri.Query))
                    {
                        pRequest.RequestUriString += "?" + pRequest.RequestUri.Query;
                    }
                }
                TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Requesting Page:{0}", pRequest.RequestUriString), eMsgLevel.l6_Debug));

                tTSM.PLS = TheCommonUtils.SerializeObjectToJSONString(pRequest);
                tTSM.SID = pRequest.SessionState.GetSID(); //.SScopeID;
                TheCommCore.PublishCentral(tTSM);          //  .PublishToNode(MyApp.HostUrl, pRequest.SessionState.SScopeID, tTSM);
            }
            else
            {
                TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("AppID:{1} Requesting Page:{0}", pRequest.cdeRealPage, MyApp)));
                ReadHttpPage(pRequest, MyApp, tMagixc, sinkResults);
            }
            int SyncFailCount      = 0;
            ManualResetEvent MyMRE = new ManualResetEvent(false);

            do
            {
                try
                {
                    tOutBuffer = ReqBuffer.GetEntryByID(TheCommonUtils.CGuid(tMagixc));
                    if (tOutBuffer != null)
                    {
                        pRequest.ResponseBuffer   = tOutBuffer.ResponseBuffer;
                        pRequest.ResponseMimeType = tOutBuffer.ResponseMimeType;
                        if (pRequest.SessionState.StateCookies == null)
                        {
                            pRequest.SessionState.StateCookies = new cdeConcurrentDictionary <string, string>();
                        }
                        if (tOutBuffer.SessionState != null && tOutBuffer.SessionState.StateCookies != null && tOutBuffer != pRequest)
                        {
                            foreach (KeyValuePair <String, String> kvp in tOutBuffer.SessionState.StateCookies.GetDynamicEnumerable())
                            {
                                string value;
                                if (!pRequest.SessionState.StateCookies.TryGetValue(kvp.Key, out value))
                                {
                                    pRequest.SessionState.StateCookies.TryAdd(kvp.Key, kvp.Value);
                                }
                                else
                                {
                                    pRequest.SessionState.StateCookies[kvp.Key] = kvp.Value;
                                }
                            }
                        }

                        if (!string.IsNullOrEmpty(tOutBuffer.ResponseBufferStr))
                        {
                            pRequest.ResponseBufferStr = tOutBuffer.ResponseBufferStr;
                        }
                        else
                        {
                            if (pRequest.ResponseMimeType.StartsWith("text/html") || pRequest.ResponseMimeType.Contains("javascript"))  //OK
                            {
                                pRequest.ResponseBufferStr = TheCommonUtils.CArray2UTF8String(tOutBuffer.ResponseBuffer);
                            }
                        }
                        string tReqUri = pRequest.RequestUri.Host;
                        if (pRequest.RequestUri.Port != 80)
                        {
                            tReqUri += ":" + pRequest.RequestUri.Port;
                        }
                        TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Got Response Page:{0}", tReqUri), eMsgLevel.l6_Debug));

                        if (!string.IsNullOrEmpty(pRequest.ResponseBufferStr) && (pRequest.ResponseMimeType.StartsWith("text/html") || pRequest.ResponseMimeType.Contains("javascript")) && pRequest.ResponseBufferStr.IndexOf(tReqUri, StringComparison.CurrentCultureIgnoreCase) >= 0)
                        {
                            if (pRequest.SessionState.ARApp != null && pRequest.SessionState.ARApp != Guid.Empty)
                            {
                                TheRelayAppInfo tMyApp = TheThingRegistry.GetThingObjectByMID(MyBaseEngine.GetEngineName(), pRequest.SessionState.ARApp) as TheRelayAppInfo;
                                //MyRelayApps.MyMirrorCache.GetEntryByFunc(s => s.cdeMID.Equals(pRequest.SessionState.ARApp));

                                if (tMyApp != null && tMyApp.CloudUrl != null)
                                {
                                    Uri tCloudUri = TheCommonUtils.CUri(tMyApp.CloudUrl, false);
                                    if (!string.IsNullOrEmpty(pRequest.NewLocation))
                                    {
                                        pRequest.NewLocation = pRequest.NewLocation.Replace(pRequest.RequestUri.Scheme + "://" + tReqUri, tCloudUri.Scheme + "://" + tCloudUri.Host + ":" + tCloudUri.Port);
                                    }
                                    TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Patching Uri from:{0} to:{1}", tReqUri, tCloudUri), eMsgLevel.l6_Debug));

                                    pRequest.ResponseBufferStr = pRequest.ResponseBufferStr.Replace(pRequest.RequestUri.Scheme + "://" + tReqUri, tCloudUri.Scheme + "://" + tCloudUri.Host + ":" + tCloudUri.Port);
                                    pRequest.ResponseBuffer    = TheCommonUtils.CUTF8String2Array(pRequest.ResponseBufferStr);
                                }
                            }
                        }
                        break;
                    }
                    MyMRE.WaitOne(50);
                    SyncFailCount++; if (SyncFailCount > (pRequestTimeout * 20))
                    {
                        if (TheCommonUtils.IsMono())
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(400, new TSM(MyBaseEngine.GetEngineName(), string.Format("Requesting Page:{0} FAILED", pRequest.cdeRealPage), eMsgLevel.l1_Error));
                        }
                        else
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Requesting Page:{0} FAILED", pRequest.cdeRealPage), eMsgLevel.l1_Error));
                        }
                        break;
                    }
                }
                catch (Exception ee)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Error during HttpIntercept for Page:{0}", pRequest.cdeRealPage), eMsgLevel.l1_Error, ee.ToString()));
                }
            } while (tOutBuffer == null);
            if (MyMRE != null)
            {
                MyMRE = null; //.Dispose();
            }
            if ((pRequest.ResponseBuffer == null && string.IsNullOrEmpty(pRequest.ResponseBufferStr)) || pRequest.StatusCode != 0)
            {
                if (pRequest.StatusCode == 0)
                {
                    pRequest.StatusCode = 404;
                }
            }
            else
            {
                pRequest.AllowStatePush = true;
                pRequest.StatusCode     = 200;
            }
            ReqBuffer.RemoveAnItemByID(TheCommonUtils.CGuid(tMagixc), null);
        }
示例#28
0
        public override bool CreateUX()
        {
            if (!mIsUXInitStarted)
            {
                mIsUXInitStarted = true;

                // Creates a "portal" for each rule. This is how we create
                // a tile for each rule on the rules engine's main page.
                mThisFormFields = TheNMIEngine.AddStandardForm(MyBaseThing, MyBaseThing.FriendlyName, 18);

                // Update our status.
                TheFormInfo tFormGuid = mThisFormFields["Form"] as TheFormInfo;
                tFormGuid.RegisterEvent2(eUXEvents.OnShow, (pMSG, para) => {
                    UpdateStatus();
                });

                // Create "Rule Status" settings group
                // Field Order = 10
                // Parent = 1 (main form)
                // Get standard Status Block.
                var tstFlds = TheNMIEngine.AddStatusBlock(MyBaseThing, tFormGuid, idGroupStatus);
                tstFlds["Group"].SetParent(idForm);
                tstFlds["Group"].Header = "Rule Status";
                // tstFlds["Group"].PropertyBag = new ThePropertyBag { "DoClose=true" };
                tstFlds["FriendlyName"].Header = "Rule Name";

                // When the Friendly Name changes, propogate to the other UI elements that use it.
                tstFlds["FriendlyName"].RegisterUXEvent(MyBaseThing, eUXEvents.OniValueChanged, null, (psender, pPara) =>
                {
                    (mThisFormFields["Header"] as TheFieldInfo).SetUXProperty(Guid.Empty, $"Title={MyBaseThing.FriendlyName}");
                    (mThisFormFields["DashIcon"] as TheDashPanelInfo).SetUXProperty(Guid.Empty, $"Caption={MyBaseThing.FriendlyName}");
                });

                // Add fields to Status Block that are specific to this plugin.
                TheNMIEngine.AddSmartControl(MyBaseThing, tFormGuid, eFieldType.SingleCheck, 60, 2, 0, "Activate Rule", "IsRuleActive", new nmiCtrlSingleCheck {
                    ParentFld = idGroupStatus, TileWidth = 3
                });
                TheNMIEngine.AddSmartControl(MyBaseThing, tFormGuid, eFieldType.SingleCheck, 70, 2, 0, "Log Action", "IsRuleLogged", new nmiCtrlSingleCheck {
                    ParentFld = idGroupStatus, TileWidth = 3
                });
                TheNMIEngine.AddSmartControl(MyBaseThing, tFormGuid, eFieldType.SingleCheck, 75, 2, 0, "Log Action to Eventlog", "IsEVTLogged", new nmiCtrlSingleCheck {
                    ParentFld = idGroupStatus, TileWidth = 3
                });
                TheFieldInfo tTriggerBut = TheNMIEngine.AddSmartControl(MyBaseThing, tFormGuid, eFieldType.TileButton, 65, 2, 0xC0, "Trigger Now", null, new nmiCtrlTileButton {
                    ParentFld = idGroupStatus, ClassName = "cdeGoodActionButton", NoTE = true, TileWidth = 3
                });
                tTriggerBut.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "TriggerNow", (psender, 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]));
                        if (tThing == null)
                        {
                            return;
                        }
                        TheRule tRule = tThing.GetObject() as TheRule;
                        if (tRule != null)
                        {
                            //FireAction(tRule, true);
                            tRule.FireAction(true);
                            MyBaseEngine.ProcessMessage(new TheProcessMessage(new TSM(MyBaseEngine.GetEngineName(), "FIRE_RULE", MyBaseThing.cdeMID.ToString())));
                            TheCommCore.PublishToOriginator(pMSG.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", string.Format("Rule {0} triggered", tRule.GetBaseThing().FriendlyName)));
                        }
                    }
                });

                // Create "Trigger Object" settings group (Field Order = idGroupTriggerObject (100), Parent = 1)
                TheNMIEngine.AddSmartControl(MyBaseThing, tFormGuid, eFieldType.CollapsibleGroup, idGroupTriggerObject, 2, 0, "Trigger Object", null, new nmiCtrlCollapsibleGroup {
                    ParentFld = idForm, TileWidth = 6, IsSmall = true
                });

                // Create "Action Settings" settings group (Field Order = idGroupActionSettings (500), Parent = 1)
                TheNMIEngine.AddSmartControl(MyBaseThing, tFormGuid, eFieldType.CollapsibleGroup, idGroupActionSettings, 2, 0, "Action Settings", null, new nmiCtrlCollapsibleGroup {
                    ParentFld = idForm, TileWidth = 6, IsSmall = true
                });

                // Create "Thing Property Action" settings group (Field Order = idGroupThingPropAction (550), Parent = 500)
                TheNMIEngine.AddSmartControl(MyBaseThing, tFormGuid, eFieldType.CollapsibleGroup, idGroupThingPropAction, 2, 0, "Thing/Property Action", null, new nmiCtrlCollapsibleGroup {
                    ParentFld = idGroupActionSettings, TileWidth = 6, IsSmall = true
                });

                // Create "TSM Action" settings group (Field Order = idGroupTSMAction (600), Parent = 500)
                TheNMIEngine.AddSmartControl(MyBaseThing, tFormGuid, eFieldType.CollapsibleGroup, idGroupTSMAction, 2, 0, "TSM Action", null, new nmiCtrlCollapsibleGroup {
                    ParentFld = idGroupActionSettings, TileWidth = 6, IsSmall = true, DoClose = true
                });

                // Create all other (non-group header) fields.
                TheNMIEngine.AddFields(tFormGuid, new List <TheFieldInfo>
                {
                    /* Trigger Object Group */
                    { new TheFieldInfo()
                      {
                          FldOrder = 140, DataItem = "MyPropertyBag.TriggerObject.Value", Flags = 2, Type = eFieldType.ThingPicker, Header = "Trigger Object", PropertyBag = new nmiCtrlThingPicker()
                          {
                              ParentFld = idGroupTriggerObject, HelpText = "If this objects...", IncludeEngines = true
                          }
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 150, DataItem = "MyPropertyBag.TriggerProperty.Value", Flags = 2, Type = eFieldType.PropertyPicker, Header = "Trigger Property", DefaultValue = "Value", PropertyBag = new nmiCtrlPropertyPicker()
                          {
                              ParentFld = idGroupTriggerObject, HelpText = "...property is...", ThingFld = 140
                          }
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 160, DataItem = "MyPropertyBag.TriggerCondition.Value", Flags = 2, Type = eFieldType.ComboBox, Header = "Trigger Condition", DefaultValue = "2", PropertyBag = new nmiCtrlComboBox()
                          {
                              ParentFld = idGroupTriggerObject, HelpText = "... then this value, this rule will fire...", DefaultValue = "2", Options = "Fire:0;State:1;Equals:2;Larger:3;Smaller:4;Not:5;Contains:6;Set:7;StartsWith:8;EndsWith:9;Flank:10"
                          }
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 170, DataItem = "MyPropertyBag.TriggerValue.Value", Flags = 2, Type = eFieldType.SingleEnded, Header = "Trigger Value", PropertyBag = new ThePropertyBag()
                          {
                              "ParentFld=100", "HelpText=...this objects..."
                          }
                      } },

                    /* Action Settings Group */
                    { new TheFieldInfo()
                      {
                          FldOrder = 505, DataItem = "MyPropertyBag.ActionObjectType.Value", Flags = 2, Type = eFieldType.ComboBox, Header = "Action Object Type", PropertyBag = new nmiCtrlComboBox()
                          {
                              ParentFld = idGroupActionSettings, Options = "Set Property on a Thing:CDE_THING;Publish Central:CDE_PUBLISHCENTRAL;Publish to Service:CDE_PUBLISH2SERVICE", DefaultValue = "CDE_THING"
                          }
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 506, DataItem = "MyPropertyBag.ActionDelay.Value", Flags = 2, Type = eFieldType.Number, Header = "Delay", DefaultValue = "0", PropertyBag = new ThePropertyBag()
                          {
                              "ParentFld=500", "HelpText=...after a delay of these seconds..."
                          }
                      } },

                    /* Thing / Property Action Sub-Group */
                    { new TheFieldInfo()
                      {
                          FldOrder = 560, DataItem = "MyPropertyBag.ActionObject.Value", Flags = 2, Type = eFieldType.ThingPicker, Header = "Action Object", PropertyBag = new nmiCtrlThingPicker()
                          {
                              ParentFld = 550, HelpText = "...this objects...", IncludeEngines = true
                          }
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 562, DataItem = "MyPropertyBag.ActionProperty.Value", Flags = 2, Type = eFieldType.PropertyPicker, Header = "Action Property", DefaultValue = "Value", PropertyBag = new nmiCtrlPropertyPicker()
                          {
                              ParentFld = idGroupThingPropAction, HelpText = "...property will change to...", ThingFld = 560
                          }
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 563, DataItem = "MyPropertyBag.ActionValue.Value", Flags = 2, Type = eFieldType.SingleEnded, Header = "Action Value", PropertyBag = new nmiCtrlSingleEnded {
                              ParentFld = idGroupThingPropAction, HelpText = "...this value", Style = "text-overflow:ellipsis;overflow:hidden; max-width:400px"
                          }
                      } },

                    /* TSM Action Sub-Group */
                    { new TheFieldInfo()
                      {
                          FldOrder = 630, DataItem = "MyPropertyBag.TSMEngine.Value", Flags = 2, Type = eFieldType.ThingPicker, Header = "TSM Engine", PropertyBag = new nmiCtrlThingPicker()
                          {
                              ParentFld = 600, ValueProperty = "EngineName", IncludeEngines = true, Filter = "DeviceType=IBaseEngine"
                          }
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 631, DataItem = "MyPropertyBag.TSMText.Value", Flags = 2, Type = eFieldType.SingleEnded, Header = "TSM Text", PropertyBag = new ThePropertyBag()
                          {
                              "ParentFld=600", "HelpText=Command of the TSM"
                          }
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 632, DataItem = "MyPropertyBag.TSMPayload.Value", Flags = 2, Type = eFieldType.TextArea, Header = "TSM Payload", PropertyBag = new nmiCtrlTextArea()
                          {
                              ParentFld = idGroupTSMAction, TileHeight = 2, HelpText = "Body of the TSM"
                          }
                      } },
                });

                mIsUXInitCompleted = true;
            }
            return(true);
        }
示例#29
0
        public override bool DoCreateUX()
        {
            MyBaseThing.RegisterProperty("ClickState");
            var tFlds = TheNMIEngine.AddStandardForm(MyBaseThing, null, 24, null, "Value");

            MyStatusForm = tFlds["Form"] as TheFormInfo;
            //MyStatusForm.PropertyBag = new ThePropertyBag { "TileWidth=6" };
            MyStatusForm.RegisterEvent2(eUXEvents.OnShow, (pmse, sen) => { UpdateUx(); });
            SummaryForm             = tFlds["DashIcon"] as TheDashPanelInfo;
            SummaryForm.PropertyBag = new nmiDashboardTile()
            {
                Format = $"{MyBaseThing.FriendlyName}<br>{{0}}", Caption = MyBaseThing.FriendlyName
            };

            CountBar             = TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.SingleEnded, 5, 2, MyBaseThing.cdeA, "CurrentValue", "Value", null);
            ChangeTimestampField = TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.DateTime, 6, 0, MyBaseThing.cdeA, "Last Change", nameof(ValueChangeTimestamp), new nmiCtrlDateTime {
                ParentFld = 1, Visibility = ShowChangeTimestamp
            });
            TimestampField = TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.DateTime, 7, 0, MyBaseThing.cdeA, "Timestamp", nameof(ValueTimestamp), new nmiCtrlDateTime {
                ParentFld = 1, Visibility = ShowChangeTimestamp
            });

            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.CollapsibleGroup, 800, 2, 0x80, "Configuration...", null, ThePropertyBag.Create(new nmiCtrlCollapsibleGroup()
            {
                ParentFld = 1, DoClose = true, IsSmall = true
            }));

            var ts = TheNMIEngine.AddStatusBlock(MyBaseThing, MyStatusForm, 810);

            ts["Group"].SetParent(800);
            ts["Group"].PropertyBag = new nmiCtrlCollapsibleGroup {
                DoClose = true
            };



            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.CollapsibleGroup, 1000, 2, 0x80, "NMI Settings...", null, ThePropertyBag.Create(new nmiCtrlCollapsibleGroup()
            {
                ParentFld = 800, DoClose = true, IsSmall = true, TileWidth = 6
            }));
            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.CollapsibleGroup, 3000, 2, 0x80, "Advanced NMI Settings...", null, ThePropertyBag.Create(new nmiCtrlCollapsibleGroup()
            {
                ParentFld = 1000, DoClose = true, IsSmall = true, TileWidth = 6
            }));
            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.ComboOption, 3010, 2, 0x80, "NMI Screen", "FormName", new ThePropertyBag()
            {
                "Options=%GetLiveScreens%", "TileWidth=6", "TileHeight=1", "ParentFld=3000"
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.CheckField, 3020, 2, 0x80, "Flags", "Flags", new ThePropertyBag()
            {
                "Bits=6", "TileHeight=6", "TileFactorY=2",
                "ImageList=<span class='fa-stack'><i class='fa fa-stack-1x'>&#xf21b;</i><i class='fa fa-stack-2x'>&#x2003;</i></span>," +
                "<span class='fa-stack'><i class='fa fa-stack-1x'>&#xf044;</i><i class='fa fa-stack-2x'>&#x2003;</i></span>," +
                "<span class='fa-stack'><i class='fa fa-stack-1x'>&#xf10b;</i><i class='fa fa-stack-2x text-danger' style='opacity:0.5'>&#xf05e;</i></span>," +
                "<span class='fa-stack'><i class='fa fa-stack-1x'>&#xf0ce;</i><i class='fa fa-stack-2x text-danger' style='opacity:0.5'>&#xf05e;</i></span>," +
                "<span class='fa-stack'><i class='fa fa-stack-1x'>&#xf0f6;</i><i class='fa fa-stack-2x text-danger' style='opacity:0.5'>&#xf05e;</i></span>," +
                "<span class='fa-stack'><i class='fa fa-stack-1x'>&#xf15c;</i><i class='fa fa-stack-2x text-danger' style='opacity:0.5'>&#xf05e;</i></span>", "ParentFld=3000"
            }).FldWidth = 1;

            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.ComboBox, 1500, 2, 0x80, "Control Type", "ControlType", new ThePropertyBag()
            {
                "Options=%RegisteredControlTypes%", "ParentFld=1000"
            });

            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.CollapsibleGroup, 2000, 2, 0x80, "All Properties...", null, ThePropertyBag.Create(new nmiCtrlCollapsibleGroup()
            {
                NoTE = true, ParentFld = 1000, DoClose = true, IsSmall = true, TileWidth = 6
            }));

            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.Table, 2010, 0xA2, 0x80, "All Properties", "mypropertybag;1", new ThePropertyBag()
            {
                "NoTE=true", "TileHeight=4", "TileLeft=9", "TileTop=3", "TileWidth=6", "FldWidth=6", "ParentFld=2000"
            });
            TheNMIEngine.AddFields(MyStatusForm, new List <TheFieldInfo> {
                { new TheFieldInfo()
                  {
                      FldOrder = 2020, DataItem = "MyPropertyBag.ScratchName.Value", Flags = 0x0A, Type = eFieldType.SingleEnded, Header = "New Property Name", TileWidth = 6, TileHeight = 1, PropertyBag = new ThePropertyBag()
                      {
                          "ParentFld=2000"
                      }
                  } },
            });

            TheFieldInfo tBut = TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.TileButton, 2040, 0x0A, 0, "Add Property", false, null, null, new nmiCtrlTileButton()
            {
                ParentFld = 2000, NoTE = true, ClassName = "cdeGoodActionButton"
            });

            tBut.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "AddProp", (pThing, pObj) =>
            {
                TheProcessMessage pMsg = pObj as TheProcessMessage;
                if (pMsg?.Message == null)
                {
                    return;
                }
                string[] parts = pMsg.Message.PLS.Split(':');
                TheThing tOrg  = TheThingRegistry.GetThingByMID(MyBaseEngine.GetEngineName(), TheCommonUtils.CGuid(parts[2]));
                if (tOrg == null)
                {
                    return;
                }

                string tNewPropName = TheThing.GetSafePropertyString(tOrg, "ScratchName");
                if (string.IsNullOrEmpty(tNewPropName))
                {
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Please specify a new property name"));
                }
                else
                {
                    if (tOrg.GetProperty(tNewPropName) != null)
                    {
                        TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Property already exists"));
                        tOrg.SetProperty("ScratchName", "");
                    }
                    else
                    {
                        tOrg.DeclareNMIProperty(tNewPropName, ePropertyTypes.TString);
                        TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Property Added"));
                        tOrg.SetProperty("ScratchName", "");
                        MyStatusForm.Reload(pMsg, false);
                    }
                }
            });
            TheFieldInfo mSendbutton = TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.TileButton, 1550, 2, 0x80, "Reload", false, "", null, new nmiCtrlTileButton()
            {
                TileWidth = 6, NoTE = true, ClassName = "cdeGoodActionButton", ParentFld = 1000
            });

            mSendbutton.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "", (pThing, pPara) =>
            {
                TheProcessMessage pMsg = pPara as TheProcessMessage;
                if (pMsg?.Message == null)
                {
                    return;
                }
                UpdateUx();
                MyStatusForm.Reload(pMsg, true);
                //TheNMIEngine.GetEngineDashBoardByThing(MyBaseEngine.GetBaseThing()).Reload(pMsg, true);
            });


            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.CollapsibleGroup, 5000, 2, 0x80, "Source...", null, ThePropertyBag.Create(new nmiCtrlCollapsibleGroup()
            {
                DoClose = true, IsSmall = true, ParentFld = 800, TileWidth = 6
            }));
            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.ThingPicker, 5010, 2, 0x80, "Source Thing", "Address", new nmiCtrlThingPicker()
            {
                ParentFld = 5000, IncludeEngines = true, IncludeRemotes = true
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.PropertyPicker, 5020, 2, 0x80, "Source Property", "SourceProp", new nmiCtrlPropertyPicker()
            {
                ParentFld = 5000, ThingFld = 5010
            });


            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.SingleCheck, 5030, 2, 0x80, "Show Timestamp", nameof(ShowTimestamp), new nmiCtrlSingleCheck {
                ParentFld = 5000, TileWidth = 3
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.SingleCheck, 5040, 2, 0x80, "Show Change Time", nameof(ShowChangeTimestamp), new nmiCtrlSingleCheck {
                ParentFld = 5000, TileWidth = 3
            });
            TheFieldInfo mSendbutton2 = TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.TileButton, 5050, 2, 0x80, "Engage", false, "", null, new nmiCtrlTileButton()
            {
                NoTE = true, TileWidth = 6, ClassName = "cdeGoodActionButton", ParentFld = 5000
            });

            mSendbutton2.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "", (pThing, pPara) =>
            {
                TheProcessMessage pMsg = pPara as TheProcessMessage;
                if (pMsg?.Message == null)
                {
                    return;
                }
                UpdateUx();
            });

            UpdateUx();
            return(true);
        }
示例#30
0
        /// <summary>
        /// Creates the basic NMI User Interface
        /// </summary>
        /// <returns></returns>
        public override bool CreateUX()
        {
            if (mIsUXInitCalled)
            {
                return(false);
            }

            mIsUXInitCalled = true;
            if (!MyBaseEngine.GetEngineState().IsService)
            {
                mIsUXInitialized = true;
                return(true);
            }

            UserPrefID = new Guid("{E15AE1F2-69F3-42DC-97E8-B0CC2A8526A6}").ToString().ToLower();
            UserManID  = TheThing.GetSafeThingGuid(MyBaseThing, "USEMAN").ToString().ToLower();
            AddDashboard(MyBaseThing, new TheDashboardInfo(eNMIPortalDashboard, "-HIDE")
            {
                FldOrder = 99999, PropertyBag = { "Category=NMI" }
            });                                                                                                                                   //Main Portal of Relay
            TheDashboardInfo tDash = AddDashboard(MyBaseThing, new TheDashboardInfo(eNMIDashboard, "NMI Admin Portal")
            {
                cdeA = 0x0, FldOrder = 9090, PropertyBag = new nmiDashboard()
                {
                    Category = "NMI", ForceLoad = true, Thumbnail = "FA5:f06c", Caption = "###NMI Admin###"
                }
            });

            if (!TheBaseAssets.MyServiceHostInfo.IsIsolated)
            {
                TheFormInfo tInf = new TheFormInfo(new Guid("{6EE8AC31-7395-4A80-B01C-D49BE174CFC0}"), eEngineName.NMIService, "###Service Overview###", "HostEngineStates")
                {
                    IsNotAutoLoading = true, PropertyBag = new nmiCtrlTableView {
                        ShowFilterField = true
                    }
                };
                AddFormToThingUX(tDash, MyBaseThing, tInf, "CMyTable", "###Service Overview###", 1, 0x0F, 128, "###NMI Administration###", null, new ThePropertyBag {
                    "TileThumbnail=FA5:f05a"
                });

                var tDisButName = "DISPLUG";
                var tDisBut     = AddSmartControl(MyBaseThing, tInf, eFieldType.TileButton, 1, 0x42, 0x80, null, "DisableText", new nmiCtrlTileButton()
                {
                    MID = new Guid("{7C67925E-7C2D-4460-9E61-6166494E9328}"), TableHeader = "###Is Enabled###", TileHeight = 1, TileWidth = 1, FldWidth = 1, ClassName = "cdeTableButton"
                });
                tDisBut.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, tDisButName, (sender, para) =>
                {
                    if (para is TheProcessMessage pMsg && pMsg.Message != null)
                    {
                        var tCmd = pMsg.Message.PLS?.Split(':');
                        if (tCmd != null && tCmd.Length > 2)
                        {
                            if (tCmd[1] != tDisButName)
                            {
                                return;
                            }
                            var estate = TheCDEngines.MyServiceStates.GetEntryByID(tCmd[2]);
                            if (estate != null)
                            {
                                var tBase = TheThingRegistry.GetBaseEngine(estate.ClassName);
                                if (tBase != null)
                                {
                                    if (tBase.HasCapability(eThingCaps.Internal))
                                    {
                                        TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", TheNMIEngine.LocNMI(pMsg, "###Not allowed on internal engines###")));
                                        return;
                                    }
                                    if (tBase.HasCapability(eThingCaps.MustBePresent))
                                    {
                                        TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", TheNMIEngine.LocNMI(pMsg, "###Not allowed on engines that must be present###")));
                                        return;
                                    }
                                }
                                estate.IsDisabled = !estate.IsDisabled;
                                estate.IsUnloaded = estate.IsDisabled;
                                SetUXProperty(Guid.Empty, tDisBut.cdeMID, $"Caption={estate.DisableText}", pMsg.Message.PLS.Split(':')[2]);
                                TheBaseAssets.RecordServices();
                            }
                        }
                    }
                });