void SetupModbusProperties(bool bReload, TheProcessMessage pMsg) { if (MyModConnectForm != null) { List <TheFieldInfo> tLst = TheNMIEngine.GetFieldsByFunc(s => s.FormID == MyModConnectForm.cdeMID); foreach (TheFieldInfo tInfo in tLst) { if (tInfo.FldOrder >= 600 && TheCommonUtils.CInt(tInfo.PropBagGetValue("ParentFld")) == 500) { TheNMIEngine.DeleteFieldById(tInfo.cdeMID); } } List <cdeP> props = MyBaseThing.GetPropertiesMetaStartingWith("MODPROP"); int fldCnt = 600; foreach (var p in props) { var field = MyModFieldStore.MyMirrorCache.GetEntryByFunc(s => s.PropertyName == p.Name); if (field != null) { TheNMIEngine.AddSmartControl(MyBaseThing, MyModConnectForm, eFieldType.SingleEnded, fldCnt++, field.AllowWrite ? 2 : 0, 0, p.Name, p.Name, new nmiCtrlSingleEnded() { TileWidth = 6, ParentFld = 500 }); } } MyModConnectForm.Reload(pMsg, bReload); } }
private void SetCtrlType() { if (MySampleControl == null) { return; } string tControl = ThePropertyBag.PropBagGetValue(MySampleControl.PropertyBag, "ControlType", "="); eFieldType tCtrlType = eFieldType.SingleEnded; if (!string.IsNullOrEmpty(tControl) && TheCommonUtils.CInt(tControl) == 0 && tControl.Length > 0) { TheControlType tType = TheNMIEngine.GetControlTypeByType(tControl); if (tType != null) { ThePropertyBag.PropBagUpdateValue(MySampleControl.PropertyBag, "EngineName", "=", tType.BaseEngineName); } tCtrlType = eFieldType.UserControl; } else { tCtrlType = (eFieldType)TheCommonUtils.CInt(tControl); } MySampleControl.Type = tCtrlType; MySampleControl.Flags = TheCommonUtils.CInt(ThePropertyBag.PropBagGetValue(MySampleControl.PropertyBag, "Flags", "=")); MySampleControl.UpdateUXProperties(Guid.Empty); }
void sinkTriggerTimeout(object state) { if (TheCommonUtils.cdeIsLocked(tLock)) { return; } if (!TheBaseAssets.MasterSwitch) { mTimer?.Dispose(); mTimer = null; return; } if (IsDisabled) { if (MyBaseThing.StatusLevel != 0) { MyBaseThing.StatusLevel = 0; MyBaseThing.LastMessage = "Timer disabled"; } return; } else if (MyBaseThing.StatusLevel == 0) { MyBaseThing.StatusLevel = 1; MyBaseThing.LastMessage = "Timer enabled"; } lock (tLock) { cdeP pV = MyBaseThing.SetProperty("Value", (TheCommonUtils.CInt(MyBaseThing.Value) + 1)); pV.cdeE = 2; } }
private void sinkTriggered(cdeP pProp) { if (TheCommonUtils.cdeIsLocked(TriggerLock) || IsDisabled) { return; } lock (TriggerLock) { if (pProp == null) { return; } int tTime = TheCommonUtils.CInt(pProp.ToString()); if (tTime <= 0 || mTimer != null) { return; } mTimer?.Dispose(); if (Frequency < 100) { Frequency = 100; } mTimer = new Timer(sinkTriggerTimeout, null, 0, Frequency); MyBaseThing.Value = tTime.ToString(); IsActive = true; CountBar?.SetUXProperty(Guid.Empty, $"MaxValue={tTime}"); tGauge?.SetUXProperty(Guid.Empty, $"MaxValue={tTime}"); MyBaseThing.LastMessage = "Countdown started: " + MyBaseThing.FriendlyName; MyBaseThing.StatusLevel = 1; } }
private void sinkLoopChanged(cdeP pProp) { int tTime = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(this, "MsToTrigger")); //if (tTime > 0) { int tPeriod = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(this, "LoopPeriod")); if (tPeriod == 0) { tPeriod = -1; } if (tPeriod > 0 && tPeriod < 10) { tPeriod = 10; } MyBaseThing.Value = "0"; if (mTimer != null) { mTimer.Change(tTime, tPeriod); } else { mTimer = new Timer(sinkTriggerTimeout, null, tTime, tPeriod); } IsActive = true; MyBaseThing.StatusLevel = 1; MyBaseThing.LastMessage = $"Timer started at {DateTimeOffset.Now}"; SummaryForm?.SetUXProperty(Guid.Empty, string.Format("Background=green")); } }
private void sinkValueReset(cdeP pProp) { if (mTimer == null && TheCommonUtils.CInt(pProp.ToString()) > 0) { this.SetProperty(nameof(StartValue), pProp.ToString()); } }
public override bool Init() { if (mIsInitCalled) { return(false); } mIsInitCalled = true; ReqBuffer = new TheMirrorCache <TheRequestData>(0); string t = TheCommonUtils.CStr(TheBaseAssets.MySettings.GetSetting("WRA_RequestTimeout")); if (!string.IsNullOrEmpty(t)) { RequestTimeout = TheCommonUtils.CInt(t); } if (RequestTimeout < 15) { RequestTimeout = 15; } InitServices(); TheCommCore.MyHttpService.RegisterHttpInterceptorB4("/", InterceptHttpRequest); TheScopeManager.RegisterScopeChanged(sinkScopeIDUpdate); MyBaseThing.RegisterEvent(eEngineEvents.IncomingMessage, HandleMessage); mIsInitialized = true; MyBaseEngine.ProcessInitialized(); return(true); }
private void SetCtrlType() { if (CountBar == null) { return; } string tControl = ThePropertyBag.PropBagGetValue(CountBar.PropertyBag, "ControlType", "="); eFieldType tCtrlType = eFieldType.SingleEnded; if (!string.IsNullOrEmpty(tControl) && TheCommonUtils.CInt(tControl) == 0 && tControl.Length > 0) { TheControlType tType = TheNMIEngine.GetControlTypeByType(tControl); if (tType != null) { ThePropertyBag.PropBagUpdateValue(CountBar.PropertyBag, "EngineName", "=", tType.BaseEngineName); } tCtrlType = eFieldType.UserControl; } else { tCtrlType = (eFieldType)TheCommonUtils.CInt(tControl); } CountBar.Type = tCtrlType; CountBar.Flags = TheCommonUtils.CInt(ThePropertyBag.PropBagGetValue(CountBar.PropertyBag, "Flags", "=")); CountBar.PropertyBag = new TheNMIBaseControl { ParentFld = 1 }; CountBar.UpdateUXProperties(Guid.Empty); CountBar.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "click", (sener, para) => { TheThing.SetSafePropertyBool(MyBaseThing, "ClickState", !TheThing.GetSafePropertyBool(MyBaseThing, "ClickState")); }); }
private void UpdateUx() { CountBar.PropertyBag = ThePropertyBag.CreateUXBagFromProperties(MyBaseThing); CountBar.Type = (eFieldType)TheCommonUtils.CInt(ThePropertyBag.PropBagGetValue(CountBar.PropertyBag, "ControlType", "=")); string t = TheCommonUtils.CListToString(CountBar.PropertyBag, ":;:"); CountBar.SetUXProperty(Guid.Empty, t); }
private static Image DrawStripHeader(DateTimeOffset now, TheFieldInfo pInfo) { bool drawRightToLeft = (TheCommonUtils.CBool(pInfo?.PropBagGetValue("DrawRightToLeft"))); int pixelWidth = 78 * TheCommonUtils.CInt(pInfo?.PropBagGetValue("TileWidth")); if (pixelWidth == 0) { pixelWidth = 78; } int Hours = TheCommonUtils.CInt(pInfo?.PropBagGetValue("Hours")); if (Hours == 0) { Hours = 1; } int pixelHeight = 39; Bitmap bmp = new Bitmap(pixelWidth, pixelHeight, PixelFormat.Format32bppArgb); DateTimeOffset start = now.Subtract(new TimeSpan(drawRightToLeft ? Hours : 0, now.Minute, now.Second)); TimeSpan step = new TimeSpan(0, Hours * 5, 0); double scaling = (float)pixelWidth / (Hours * 60 * 60); using (Graphics g = Graphics.FromImage(bmp)) { Font drawFont = new Font("Arial", 10); SolidBrush drawBrush = new SolidBrush(Color.Black); // Color.FromArgb(179, 255, 255, 255)); DateTimeOffset currentTime = start; g.TextRenderingHint = TextRenderingHint.AntiAlias; for (int i = 0; i <= 12; i++) { string pattern = CultureInfo.CurrentCulture.DateTimeFormat.MonthDayPattern; pattern = pattern.Replace("MMMM", "MMM"); string timeValue = currentTime.DateTime.ToString(pattern) + "\n"; timeValue += currentTime.DateTime.ToShortTimeString(); SizeF size = g.MeasureString(timeValue, drawFont); double x = now.Subtract(currentTime).TotalSeconds *scaling - size.Width / 2; if (drawRightToLeft) { x = pixelWidth - x; } if (x >= -3 && x <= pixelWidth - size.Width + 3) { g.DrawString(timeValue, drawFont, drawBrush, new PointF((float)x, pixelHeight - size.Height - 5)); } if (drawRightToLeft) { currentTime = currentTime.Add(step); } else { currentTime = currentTime.Subtract(step); } } } return(bmp); }
public override bool DoInit() { base.DoInit(); IsActive = false; TheThing.SetSafePropertyBool(MyBaseThing, "IsStateSensor", true); MyBaseThing.StatusLevel = 4; if (string.IsNullOrEmpty(MyBaseThing.ID)) { MyBaseThing.ID = Guid.NewGuid().ToString(); TheThing.SetSafePropertyString(MyBaseThing, "StateSensorType", "analog"); TheThing.SetSafePropertyString(MyBaseThing, "StateSensorUnit", "units"); TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorMaxValue", 100); TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorAverage", 50); TheThing.SetSafePropertyNumber(MyBaseThing, "StateSensorMinValue", 0); TheThing.SetSafePropertyNumber(MyBaseThing, "Interval", 500); } TheThing.SetSafePropertyString(MyBaseThing, "StateSensorIcon", "/P066/Images/iconVThingsRest.png"); GetProperty("FriendlyName", true).RegisterEvent(eThingEvents.PropertyChanged, sinkNameChanged); cdeP tRW = GetProperty("RawValue", true); tRW.RegisterEvent(eThingEvents.PropertyChanged, sinkPrePro); cdeP.SetSafePropertyBool(tRW, "IsStateSensor", true); cdeP.SetSafePropertyString(tRW, "StateSensorType", "analog"); cdeP.SetSafePropertyString(tRW, "StateSensorUnit", "°F"); cdeP.SetSafePropertyNumber(tRW, "StateSensorMaxValue", 100); cdeP.SetSafePropertyNumber(tRW, "StateSensorAverage", 50); cdeP.SetSafePropertyNumber(tRW, "StateSensorMinValue", 0); if (!string.IsNullOrEmpty(TheThing.GetSafePropertyString(MyBaseThing, "RealSensorThing")) && !string.IsNullOrEmpty(TheThing.GetSafePropertyString(MyBaseThing, "RealSensorProperty"))) { EngageMapper(); } GetProperty("IsGlobal", true).RegisterEvent(eThingEvents.PropertyChanged, (p) => { if (TheCommonUtils.CBool(p.ToString())) { TheThingRegistry.RegisterThingGlobally(MyBaseThing); } else { TheThingRegistry.UnregisterThingGlobally(MyBaseThing); } }); GetProperty("Interval", true).RegisterEvent(eThingEvents.PropertyChanged, (p) => { changeInterval(TheCommonUtils.CInt(p.ToString())); }); MyBaseThing.SetPublishThrottle((int)TheThing.GetSafePropertyNumber(MyBaseThing, "Interval")); //TheQueuedSenderRegistry.RegisterHealthTimer(checkMapperHealth); return(true); }
internal TheCommonDisco() { string temp = TheBaseAssets.MySettings.GetSetting("DISCO_ScanRate"); if (!string.IsNullOrEmpty(temp)) { TheBaseAssets.MyServiceHostInfo.DISCOScanRate = TheCommonUtils.CInt(temp); } temp = TheBaseAssets.MySettings.GetSetting("DISCO_ExpireTime"); if (!string.IsNullOrEmpty(temp)) { DISCOExpireTime = TheCommonUtils.CInt(temp); } }
public string ShowHeader() { string AllTopics = ""; foreach (var t in MySubscriptions.TheValues) { if (t == null) { continue; } string tColor = "black"; string tVer = ""; if (TheBaseAssets.MyServiceHostInfo.IsCloudService) { var tS = MyNodeInfo?.MyServices?.FirstOrDefault(s => s?.ClassName == t.Topic); if (tS != null) { tVer = $" V{tS.Version}"; if (tS.IsMiniRelay) { tColor = "purple"; } } } if (!t.ToServiceOnly) { tColor = "lightgray"; } string tt = $"<li style='color:{tColor}'>{t.Topic}{tVer}"; if (!string.IsNullOrEmpty(t.RScopeID)) { string tScop = t.RScopeID; if (tScop.Length < 4) { tt += $" <span style='color:red'>ILLEGAL-Scope: {tScop.ToUpper()}</span>"; } else { tt += $" {cdeStatus.GetScopeHashML(tScop.Substring(0, 4).ToUpper())}"; } } int tMinAlive = TheCommonUtils.CInt((DateTimeOffset.Now - t.cdeCTIM).TotalMinutes); tt += $" ({Math.Round(t.Hits>0 && tMinAlive>0?t.Hits/tMinAlive:0.0,2)} , {t.Hits})</li>"; AllTopics += tt; } return($"<li {(!IsTrusted? "style='color:red'" : "")}>{MyTargetNodeChannel.ToMLString()} ({GetNodeName()}) {(MyNodeInfo?.MyServiceInfo?.ClientCertificateThumb?.Length > 3 ? MyNodeInfo?.MyServiceInfo?.ClientCertificateThumb?.Substring(0, 4) : "No cert")}<ul>{AllTopics}</ul></li>"); }
private void handlePOST(TheRequestData pRequest) { if (pRequest.Header.ContainsKey("Content-Length")) { using (MemoryStream ms = new MemoryStream()) { var tContentLength = TheCommonUtils.CInt(pRequest.Header["Content-Length"]); if (tContentLength > MAX_POST_SIZE) { throw new Exception( String.Format("POST Content-Length({0}) too big. Max: {1}", tContentLength, MAX_POST_SIZE)); } byte[] buf = new byte[BUF_SIZE]; int to_read = tContentLength; while (to_read > 0 && mHServer.IsActive) { int numread = mRequestStream.Read(buf, 0, Math.Min(BUF_SIZE, to_read)); if (numread == 0) { if (to_read == 0) { break; } else { throw new Exception("client disconnected during post"); } } to_read -= numread; ms.Write(buf, 0, numread); } ms.Seek(0, SeekOrigin.Begin); pRequest.PostData = ms.ToArray(); pRequest.PostDataIdx = 0; pRequest.PostDataLength = pRequest.PostData.Length; } } else { TheBaseAssets.MySYSLOG.WriteToLog(4354, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("HttpMidiServer", "Post without Content-Length!", eMsgLevel.l2_Warning)); } TheCommCore.MyHttpService.cdeProcessPost(pRequest); }
public bool Init() { if (mIsInitCalled) { return(false); } mIsInitCalled = true; MyBaseThing.StatusLevel = 1; MyBaseThing.Version = TheBaseAssets.MyAppInfo.CurrentVersion.ToString(CultureInfo.InvariantCulture); MyBaseThing.Capabilities = TheBaseAssets.MyAppInfo.Capabilities; MyBaseThing.Address = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false); TheThing.SetSafePropertyString(MyBaseThing, "Description", TheBaseAssets.MyAppInfo.LongDescription); mIsInitialized = true; TheThing.SetSafePropertyBool(MyBaseThing, "EnableKPIs", TheCommonUtils.CBool(TheBaseAssets.MySettings.GetSetting("EnableKPIs"))); if (TheBaseAssets.MyServiceHostInfo.EnableTaskKPIs) { var taskKpiThread = new System.Threading.Thread(() => { TheSystemMessageLog.ToCo($"Tasks {DateTime.Now}: NodeHost starting Task KPI thread"); do { Thread.Sleep(1000); // Keeping it simple here, to minimize interference on task scheduler/thread scheduler etc. (Assumption: not used on production systems) // TheCommonUtils.SleepOneEye(1000, 1000); var kpis = TheCommonUtils.GetTaskKpis(null); TheSystemMessageLog.ToCo($"Tasks {DateTime.Now}: {TheCommonUtils.SerializeObjectToJSONString(kpis)}"); } while (TheBaseAssets.MasterSwitch && TheBaseAssets.MyServiceHostInfo.EnableTaskKPIs); TheSystemMessageLog.ToCo($"Tasks {DateTime.Now}: NodeHost ending Task KPI thread"); }); taskKpiThread.Start(); } KPIHarvestInterval = TheCommonUtils.CInt(TheBaseAssets.MySettings.GetAppSetting("KPIHarvestIntervalInSeconds", "5", false, true)); if (KPIHarvestInterval > 0) { TheQueuedSenderRegistry.RegisterHealthTimer(sinkCyclic); } return(true); }
private void SinkStatChanged(TheDashPanelInfo tDas, cdeP prop) { var i = (prop != null) ? TheCommonUtils.CInt(prop.ToString()) : TheCommonUtils.CInt(MyBaseThing.Value); var tCol = i < 3 ? "orange" : "green"; var tLevel = i < 3 ? 2 : 1; if (i == 0) { tCol = "gray"; tLevel = 0; } SummaryForm.SetUXProperty(Guid.Empty, $"Background={tCol}"); if (MyBaseThing.StatusLevel != tLevel) { MyBaseThing.StatusLevel = tLevel; } }
void sinkPChanged(cdeP tProp) { if (m_Tag != null && tProp != null && tProp.HasChanged && tProp.Name == "DontMonitor") { if (!TheCommonUtils.CBool(tProp.ToString())) { m_Tag.SampleRate = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(MyBaseThing, "SampleRate")); string error; TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM(MyBaseThing.EngineName, $"Monitoring tag due to DontMonitor property change {m_Tag}", eMsgLevel.l4_Message, "")); var subscription = m_Tag.MyOPCServer.GetOrCreateSubscription(m_Tag.SampleRate); if (subscription != null) { m_Tag.MonitorTag(subscription, out error); // TODO Handle error } } else { m_Tag.UnmonitorTag(); } } }
void sinkStatChanged(TheDashPanelInfo tDas, cdeP prop) { int tLevel = 1; string tCol = "green"; int i = TheCommonUtils.CInt(MyBaseThing.Value); if (prop != null) { i = TheCommonUtils.CInt(prop.ToString()); } if (i < 3) { tCol = "orange"; tLevel = 2; } if (i == 0) { tCol = "gray"; tLevel = 0; } SummaryForm.SetUXProperty(Guid.Empty, string.Format("Background={0}", tCol)); if (MyBaseThing.StatusLevel != tLevel) { MyBaseThing.StatusLevel = tLevel; } }
public Dictionary <string, object> ReadAll() { if (MyModFieldStore == null || MyModFieldStore.TheValues.Count == 0) { return(null); } var timestamp = DateTimeOffset.Now; var dict = new Dictionary <string, object>(); dict["Timestamp"] = timestamp; // Read configured data items via Modbus int tMainOffset = (int)TheThing.GetSafePropertyNumber(MyBaseThing, "Offset"); int tSlaveAddress = (int)TheThing.GetSafePropertyNumber(MyBaseThing, "SlaveAddress"); int tReadWay = (int)TheThing.GetSafePropertyNumber(MyBaseThing, "ConnectionType"); foreach (var field in MyModFieldStore.TheValues) { try { int address = field.SourceOffset + tMainOffset; ushort[] data = null; float scale = field.ScaleFactor; if (scale == 0) { scale = 1.0f; } switch (tReadWay) { case 1: { bool[] datab = MyModMaster.ReadCoils((ushort)address, (ushort)field.SourceSize); for (int i = 0; i < field.SourceSize && i < datab.Length; i++) { dict[$"{field.PropertyName}_{i}"] = datab[i]; } field.Value = dict[$"{field.PropertyName}_0"]; } continue; case 2: { bool[] datab = MyModMaster.ReadInputs((ushort)address, (ushort)field.SourceSize); for (int i = 0; i < field.SourceSize && i < datab.Length; i++) { dict[$"{field.PropertyName}_{i}"] = datab[i]; } field.Value = dict[$"{field.PropertyName}_0"]; } continue; case 4: data = MyModMaster.ReadInputRegisters((byte)tSlaveAddress, (ushort)address, (ushort)field.SourceSize); break; default: data = MyModMaster.ReadHoldingRegisters((byte)tSlaveAddress, (ushort)address, (ushort)field.SourceSize); break; } if (data == null) { continue; } if (field.SourceType == "float") { var value1 = TypeFloat.Convert(data, TypeFloat.ByteOrder.CDAB); dict[field.PropertyName] = value1 / scale; } else if (field.SourceType == "float-abcd") { var value1 = TypeFloat.Convert(data, TypeFloat.ByteOrder.ABCD); dict[field.PropertyName] = value1 / scale; } else if (field.SourceType == "double") { var value1 = TypeDouble.Convert(data, TypeDouble.ByteOrder.ABCD); dict[field.PropertyName] = value1 / scale; } else if (field.SourceType == "double-cdab") { var value1 = TypeDouble.Convert(data, TypeDouble.ByteOrder.CDAB); dict[field.PropertyName] = value1 / scale; } else if (field.SourceType == "int32") { var value = TypeInt32.Convert(data); var dblValue = Convert.ToDouble(value); dict[field.PropertyName] = dblValue / scale; } else if (field.SourceType == "int64") { var value = TypeInt64.Convert(data); var dblValue = Convert.ToDouble(value); dict[field.PropertyName] = dblValue / scale; } else if (field.SourceType == "float32") { var value = TypeFloat.Convert(data, TypeFloat.ByteOrder.SinglePrecIEEE); dict[field.PropertyName] = value / scale; } else if (field.SourceType == "uint16") { var value = TypeUInt16.Convert(data); dict[field.PropertyName] = value / scale; } else if (field.SourceType == "int16") { var value = TheCommonUtils.CInt(data[0]); dict[field.PropertyName] = value / scale; } else if (field.SourceType == "utf8") { var value = TypeUTF8.Convert(data); dict[field.PropertyName] = value; } else if (field.SourceType == "byte") { byte value = (byte)(data[0] & 255); dict[field.PropertyName] = value; } field.Value = dict[field.PropertyName]; //dict[$"[{field.PropertyName}].[Status]"] = $""; } catch (Exception e) { try { // Future: convey per-tag status similar to OPC statuscode? //dict[$"[{field.PropertyName}].[Status]"] = $"##cdeError: {e.Message}"; TheBaseAssets.MySYSLOG.WriteToLog(10000, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseThing.EngineName, $"Error reading property {field.PropertyName}", eMsgLevel.l2_Warning, e.ToString())); } catch { } } } return(dict); }
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()} <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 }
void sinkPrePro(cdeP pProp) { if (TheThing.GetSafePropertyString(MyBaseThing, "StateSensorType") != "analog") { SetProperty("Value", pProp.Value); return; } int prepro = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(MyBaseThing, "PrePro")); int preprotime = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(MyBaseThing, "PreProTime")); double valScale = TheCommonUtils.CDbl(TheThing.GetSafePropertyNumber(MyBaseThing, "StateSensorScaleFactor")); var pPropString = TheCommonUtils.CStr(pProp); if (!string.IsNullOrEmpty(ValueFilterPattern)) { try { if (ValueFilterPattern != filterPattern || filterRegex == null) { #if !CDE_NET4 filterRegex = new Regex(ValueFilterPattern, RegexOptions.Compiled | RegexOptions.CultureInvariant, new TimeSpan(0, 0, 5)); #else filterRegex = new Regex(ValueFilterPattern, RegexOptions.Compiled | RegexOptions.CultureInvariant); #endif filterPattern = ValueFilterPattern; } pPropString = filterRegex.Match(pPropString).Value; } catch (Exception e) { LastMessage = $"Error applying filter pattern: {e.Message}"; return; // CODE REVIEW: Or ist it better to treat this as 0, so other time processing doesn not get confused? } } double pValue; if (!string.IsNullOrEmpty(ValueMatchPattern)) { try { if (ValueMatchPattern != matchPattern || matchRegex == null) { #if !CDE_NET4 matchRegex = new Regex(ValueMatchPattern, RegexOptions.Compiled | RegexOptions.CultureInvariant, new TimeSpan(0, 0, 5)); #else matchRegex = new Regex(ValueMatchPattern, RegexOptions.Compiled | RegexOptions.CultureInvariant); #endif matchPattern = ValueMatchPattern; } if (matchRegex.IsMatch(pProp.ToString())) { pValue = 1; } else { pValue = 0; } } catch (Exception e) { LastMessage = $"Error applying match pattern: {e.Message}"; return; // CODE REVIEW: Or ist it better to treat this as 0, so other time processing doesn not get confused? } } else { pValue = TheCommonUtils.CDbl(pPropString); } if (valScale != 0) { pValue /= valScale; } if (pValue < 0 && TheThing.GetSafePropertyBool(MyBaseThing, "StateSensorIsAbs")) { pValue = Math.Abs(pValue); } if (preprotime > 0 && prepro > 0) { if (pValue < min) { min = pValue; } if (pValue > max) { max = pValue; } ave += pValue; aveCnt++; if (DateTimeOffset.Now.Subtract(lastWrite).TotalSeconds < preprotime) { return; } lastWrite = DateTimeOffset.Now; switch (prepro) { case 1: if (min == double.MaxValue) { return; } pValue = min; min = double.MaxValue; break; case 2: if (max == double.MinValue) { return; } pValue = max; min = double.MinValue; break; case 3: if (aveCnt == 0) { return; } pValue = ave / aveCnt; ave = 0; aveCnt = 0; break; } } if (GetProperty("StateSensorDigits", false) != null) { int tDigits = (int)TheThing.GetSafePropertyNumber(MyBaseThing, "StateSensorDigits"); SetProperty("Value", decimal.Round((decimal)pValue, tDigits, MidpointRounding.AwayFromZero)); } else { SetProperty("Value", pValue); } }
/// <summary> /// Creates an installation package for a plugin. /// </summary> /// <param name="tInfo">Meta information about the plug-in. (can be null, but then tPlace has to be specified)</param> /// <param name="tPlace">Additional information about the plug-in's presence in a market place (can be null, but then tInfo has to be specified)</param> /// <param name="outputDirectory">Path to a directory that will be used for temporary files as well as the generated installation package</param> /// <param name="bForce">Overwrites output files if they already exists.</param> /// <param name="packageFilePath">Path to the installation package within the outputDirectory.</param> /// <returns>null or empty string if successful. Error information on failure.</returns> public static string CreatePluginPackage(ThePluginInfo tInfo, TheServicesMarketPlace tPlace, string outputDirectory, bool bForce, out string packageFilePath) { packageFilePath = null; string tMetaFile = ""; if (tInfo != null) { if (tInfo.Capabilities != null && tInfo.Capabilities.Contains(eThingCaps.Internal)) { return($"{tInfo.ServiceName} Is Internal Only"); } if (String.IsNullOrEmpty(outputDirectory)) { tMetaFile = TheCommonUtils.cdeFixupFileName($"store\\{tInfo.cdeMID}\\{tInfo.Platform}\\"); } else { tMetaFile = $"{outputDirectory}\\store\\{tInfo.cdeMID}\\{tInfo.Platform}\\"; } if (!Directory.Exists(tMetaFile)) { TheCommonUtils.CreateDirectories(tMetaFile); } WriteServiceInfo(tInfo, outputDirectory); string tgr = tMetaFile + "new\\"; if (TheCommonUtils.IsOnLinux()) { tgr = tgr.Replace('\\', '/'); } if (Directory.Exists(tgr)) { Directory.Delete(tgr, true); } if (tInfo.FilesManifest != null && tInfo.FilesManifest.Count > 0) { foreach (string tFile in tInfo.FilesManifest) { if (tFile == null) { continue; } string tFinalFile = tFile; try { if (tFile.StartsWith("@")) //If a Manifest file starts with @ this function expects this syntax: "@<platform>@<FileName>" { var tC = tFile.Split('@'); if (tC.Length < 3) { continue; } switch (tC[1]) { case "net35": if (tInfo.Platform != cdePlatform.X32_V3) { continue; } break; case "net40": if (tInfo.Platform != cdePlatform.NETV4_32 && tInfo.Platform != cdePlatform.NETV4_64) { continue; } break; case "net45": if (tInfo.Platform != cdePlatform.X64_V3 && tInfo.Platform != cdePlatform.X32_V4) { continue; } break; case "netstandard2.0": break; default: if ((TheCommonUtils.CInt(tC[1]) > 0 && TheCommonUtils.CInt(tC[1]) != TheCommonUtils.CInt(tInfo.Platform))) { continue; } break; } tFinalFile = tC[2]; } string src = TheBaseAssets.MyServiceHostInfo.BaseDirectory; if (TheBaseAssets.MyServiceHostInfo.cdeHostingType == cdeHostType.IIS) { src += "bin\\"; } src += tFinalFile; if (TheCommonUtils.IsOnLinux()) { src = src.Replace('\\', '/'); } tgr = tMetaFile + "new\\" + tFinalFile; if (TheCommonUtils.IsOnLinux()) { tgr = tgr.Replace('\\', '/'); } TheCommonUtils.CreateDirectories(tgr); File.Copy(src, tgr, true); } catch (Exception e) { return(string.Format("Manifest File {0} could not be copied: {1}", tFile, e.ToString())); //TheBaseAssets.MySYSLOG.WriteToLog(2, new TSM("ISMManager", string.Format("Manifest Filer {0} could not be copied.", tFile), eMsgLevel.l1_Error, e.ToString())); //Log Entry that service has been started } } } } else { tMetaFile = TheCommonUtils.cdeFixupFileName(string.Format("store\\{0}\\{1}\\", tPlace.PluginID, tPlace.Platform)); //now PluginID which contains ThePluginInfo.cdeMID } if (tPlace != null && File.Exists(tMetaFile + "META.CDEM")) { TheServicesMarketPlace tPl = null; using (StreamReader sr = new StreamReader(tMetaFile + "META.CDEM")) { String line = sr.ReadToEnd(); tPl = TheCommonUtils.DeserializeJSONStringToObject <TheServicesMarketPlace>(line); } if ((tInfo != null && tInfo.CurrentVersion <= tPl.CurrentVersion) || (tPl != null && tPlace.CurrentVersion <= tPl.CurrentVersion)) { return($"{tPlace?.ServiceName} has existing Version in Store: PInfo:{tInfo?.CurrentVersion} vs Meta:{tPl?.CurrentVersion} vs Place:{tPlace?.CurrentVersion}"); } } if (tPlace == null) { tPlace = new TheServicesMarketPlace(); tPlace.Capabilities = tInfo.Capabilities; tPlace.Categories = tInfo.Categories; tPlace.PluginID = tInfo.cdeMID; //PluginID now contains ThePluginInfo.cdeMID tPlace.CurrentVersion = tInfo.CurrentVersion; tPlace.LongDescription = tInfo.LongDescription; tPlace.Developer = tInfo.Developer; tPlace.DeveloperUrl = tInfo.DeveloperUrl; tPlace.HomeUrl = tInfo.HomeUrl; tPlace.Platform = tInfo.Platform; tPlace.Price = tInfo.Price; tPlace.ServiceName = tInfo.ServiceName; tPlace.AvailableSince = DateTime.Now; tPlace.RaterCount = new List <int>() { 0, 0, 0, 0, 0 }; tPlace.Rating = 0; tPlace.DownloadCounter = 0; tPlace.ServiceDescription = string.IsNullOrEmpty(tInfo.ServiceDescription) ? tInfo.ServiceName : tInfo.ServiceDescription; if (TheBaseAssets.MyServiceHostInfo != null) { if (string.IsNullOrEmpty(tPlace.HomeUrl)) { tPlace.HomeUrl = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false) + "/%PluginID%"; } tPlace.IconUrl = tInfo.IconUrl; if (string.IsNullOrEmpty(tPlace.IconUrl) || tPlace.IconUrl == "toplogo-150.png") { tPlace.IconUrl = "<i class=\"cl-font cl-Logo cl-4x\"></i>"; // TheBaseAssets.MyServiceHostInfo.UPnPIcon; } if (tPlace.IconUrl.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || tPlace.IconUrl.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)) { tPlace.IconUrl = $"<img src='{tPlace.IconUrl}' class='Blocked' width='78' height='78'></img>"; } else if (tPlace.IconUrl.StartsWith("FA")) { tPlace.IconUrl = "<i class='fa faIcon " + (tPlace.IconUrl.Substring(3, 1) == "S" ? "fa-spin " : "") + "fa-" + tPlace.IconUrl.Substring(2, 1) + "x'>&#x" + tPlace.IconUrl.Substring(4, tPlace.IconUrl.Length - 4) + ";</i>"; } } if (Directory.Exists(tMetaFile + "new")) { var res = CreateCDEX(tPlace, tMetaFile, true, out packageFilePath); if (res != null) { return(res); } //Directory.Move(tMetaFile + "new", tMetaFile + "DONE_" + TheCommonUtils.GetTimeStamp()); } else { return("Error: Output directory does not exists"); } } else { if (tInfo.CurrentVersion > tPlace.CurrentVersion) { tPlace.CurrentVersion = tInfo.CurrentVersion; } var res = CreateCDEX(tPlace, tMetaFile, bForce, out packageFilePath); if (res != null) { return(res); } } tPlace.LastUpdate = DateTime.Now; using (StreamWriter sr = new StreamWriter(tMetaFile + "META.CDEM")) sr.Write(TheCommonUtils.SerializeObjectToJSONString <TheServicesMarketPlace>(tPlace)); return(""); }
internal static TheScreenInfo GenerateLiveScreen(Guid pScreenId, TheClientInfo tClientInfo) // Guid pUserGuid, int lcid, int pFlag) { if (TheCDEngines.MyNMIService == null) { return(null); } TheScreenInfo tInfo = new TheScreenInfo { cdeMID = pScreenId, MyDashboard = null, MyStorageInfo = new List <TheFormInfo>(), MyStorageMeta = new cdeConcurrentDictionary <string, TheFormInfo>(), MyStorageMirror = new List <object>(), MyDashPanels = new List <TheDashPanelInfo>() }; TheThing tLiveForm = TheThingRegistry.GetThingByMID("*", pScreenId); if (tLiveForm == null || !TheUserManager.HasUserAccess(tClientInfo.UserID, tLiveForm.cdeA)) { return(null); //V3.1: BUG 126 - could lead to racing condition. TODO: Revisit later //TheFormInfo tI = new TheFormInfo(tLiveForm) { FormTitle = (tLiveForm == null ? "Form not Found!" : "Access Denied!") }; //tI.TargetElement = pScreenId.ToString(); //tI.AssociatedClassName = pScreenId.ToString(); //tInfo.MyStorageInfo.Add(tI); //tI.FormFields = new List<TheFieldInfo>(); //TheFieldInfo tFldInfo = new TheFieldInfo(null, null, 10, 0, 0); //tFldInfo.Type = eFieldType.SmartLabel; //tFldInfo.Header = (tLiveForm == null ? "This Form was defined but has not Meta-Data associated with it." : "You do not have the required access permissions!"); //tI.FormFields.Add(tFldInfo); //return tInfo; } string tFormName = TheThing.GetSafePropertyString(tLiveForm, "FriendlyName"); List <TheThing> tFields = TheThingRegistry.GetThingsByFunc("*", s => s.cdeO == TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID && TheThing.GetSafePropertyString(s, "FormName") == tFormName && TheThing.GetSafePropertyBool(s, "IsLiveTag") && (s.UID == Guid.Empty || s.UID == tClientInfo.UserID)); if (tFields != null && tFields.Any()) { string tFormTitle = TheThing.GetSafePropertyString(tLiveForm, "FormTitle"); if (string.IsNullOrEmpty(tFormTitle)) { tFormTitle = tFormName; } TheFormInfo tI = new TheFormInfo(tLiveForm) { FormTitle = tFormTitle, TargetElement = pScreenId.ToString(), DefaultView = eDefaultView.Form, TileWidth = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(tLiveForm, "TileWidth")), TileHeight = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(tLiveForm, "TileHeight")), IsUsingAbsolute = TheThing.GetSafePropertyBool(tLiveForm, "IsAbsolute"), AssociatedClassName = pScreenId.ToString() }; tInfo.MyStorageInfo.Add(tI); tI.FormFields = new List <TheFieldInfo>(); int fldNo = 10; foreach (TheThing tTh in tFields) { int tfldNo = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(tTh, "FldOrder")); if (tfldNo == 0) { tfldNo = fldNo; } int tFlags = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(tTh, "Flags")); cdeP ValProp = tTh.GetProperty("Value"); bool IsNewFld = true; TheFieldInfo tFldInfo = TheNMIEngine.GetFieldById(TheThing.GetSafePropertyGuid(tTh, "FldID")); if (tFldInfo == null) { tFldInfo = new TheFieldInfo(tTh, "Value", tfldNo, tFlags & 0xFFBF, tTh.GetBaseThing().cdeA); } else { tFldInfo.FldOrder = tfldNo; tFldInfo.Flags = tFlags; IsNewFld = false; } if (tFldInfo.PropertyBag == null) { tFldInfo.PropertyBag = new ThePropertyBag(); } ThePropertyBag.PropBagUpdateValue(tFldInfo.PropertyBag, "IsOnTheFly", "=", "True"); ThePropertyBag.PropBagUpdateValue(tFldInfo.PropertyBag, "UXID", "=", $"{tTh.cdeMID}"); tFldInfo.Header = tTh.FriendlyName; RegisterNMISubscription(tClientInfo, "Value", tFldInfo); string tControlType = TheThing.GetSafePropertyString(tTh, "ControlType"); if (TheCommonUtils.CInt(tControlType) == 0 && !TheCommonUtils.IsNullOrWhiteSpace(tControlType)) { tFldInfo.Type = eFieldType.UserControl; RegisterFieldEvents(tTh, ValProp, IsNewFld, tFldInfo, tControlType); } else { tFldInfo.Type = (eFieldType)TheCommonUtils.CInt(tControlType); } tFldInfo.DefaultValue = ValProp?.ToString(); tFldInfo.TileWidth = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(tTh, "TileWidth")); tFldInfo.TileHeight = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(tTh, "TileHeight")); foreach (cdeP prop in tTh.GetNMIProperties()) { ThePropertyBag.PropBagUpdateValue(tFldInfo.PropertyBag, prop.Name, "=", prop.ToString()); } if (tFldInfo.Type == eFieldType.TileButton) { tTh.DeclareNMIProperty("IsDown", ePropertyTypes.TBoolean); ThePropertyBag.PropBagUpdateValue(tFldInfo.PropertyBag, "EnableTap", "=", "True"); tFldInfo.RegisterUXEvent(tTh, eUXEvents.OnPropertyChanged, "IsDown", (pThing, pObj) => { if (!(pObj is TheProcessMessage pMsg) || pMsg.Message == null) { return; } TheThing.SetSafePropertyBool(pThing, "IsDown", TheCommonUtils.CBool(pMsg.Message.PLS)); });
private static Image DrawStrip(Guid pThingGuid, DateTimeOffset now, TheFieldInfo pInfo) { int pixelWidth = 78 * TheCommonUtils.CInt(pInfo?.PropBagGetValue("TileWidth")); if (pixelWidth == 0) { pixelWidth = 78; } int Hours = TheCommonUtils.CInt(pInfo?.PropBagGetValue("Hours")); if (Hours == 0) { Hours = 1; } int pixelHeight = 1; Bitmap bmp = new Bitmap(pixelWidth, pixelHeight, PixelFormat.Format32bppArgb); int st = 0; string tColorString = pInfo?.PropBagGetValue("ChartColors"); string[] htmlColors = null; if (string.IsNullOrEmpty(tColorString)) { htmlColors = TheBaseAssets.MyServiceHostInfo.StatusColors.Split(';'); } else { htmlColors = tColorString.Split(';'); } Dictionary <int, SolidBrush> stateColorMapping = htmlColors.ToDictionary(x => st++, y => new SolidBrush(ColorTranslator.FromHtml(y))); TheThing tThing = TheThingRegistry.GetThingByMID("*", pThingGuid); if (tThing == null) { return(null); } cdeP pMSH = ((ICDEThing)tThing.GetObject())?.GetProperty("MachineStorageHistory", false); if (pMSH == null) { return(null); } List <TheMachineStateHistory> tList = TheCommonUtils.DeserializeJSONStringToObject <List <TheMachineStateHistory> >(pMSH.ToString()); if (tList == null) { return(null); } tList = tList.Where(s => now.Subtract(s.StateChangeTime).TotalHours < Hours).OrderBy(s => s.StateChangeTime).ToList(); cdeP LastDeletedEntry = tThing.GetProperty("LastDeletedEntry", false); TheMachineStateHistory lastState = null; if (LastDeletedEntry != null) { TheMachineStateHistory tHis = TheCommonUtils.DeserializeJSONStringToObject <TheMachineStateHistory>(LastDeletedEntry.ToString()); lastState = new TheMachineStateHistory() { State = tHis.State, StateChangeTime = now.Subtract(new TimeSpan(Hours, 0, 0)) }; } using (Graphics g = Graphics.FromImage(bmp)) { g.ScaleTransform((float)pixelWidth / (Hours * 60 * 60), 1.0f); List <KeyValuePair <int, RectangleF> > rectangles = new List <KeyValuePair <int, RectangleF> >(); foreach (var t in tList) { if (lastState != null && t.State != lastState.State) { float start = (float)now.Subtract(t.StateChangeTime).TotalSeconds; float size = (float)t.StateChangeTime.Subtract(lastState.StateChangeTime).TotalSeconds; rectangles.Add(new KeyValuePair <int, RectangleF>(lastState.State, new RectangleF(new PointF(start, 0), new SizeF(size, pixelHeight)))); lastState = t; } if (lastState == null) { lastState = t; } } if (lastState != null) { float size = (float)now.Subtract(lastState.StateChangeTime).TotalSeconds; rectangles.Add(new KeyValuePair <int, RectangleF>(lastState.State, new RectangleF(new PointF(0, 0), new SizeF(size, pixelHeight)))); } if (rectangles.Count > 0) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; // g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; for (int state = 0; state <= rectangles.Max(x => x.Key); state++) { if (stateColorMapping.ContainsKey(state)) { IEnumerable <RectangleF> rects = rectangles.Where(x => x.Key == state).Select(x => x.Value); var rectangleFs = rects as RectangleF[] ?? rects.ToArray(); if (rectangleFs.Any()) { if (state > stateColorMapping.Count) { g.FillRectangles(new SolidBrush(Color.Pink), rectangleFs.ToArray()); } else { g.FillRectangles(stateColorMapping[state], rectangleFs.ToArray()); } } } } } } if (TheCommonUtils.CBool(pInfo?.PropBagGetValue("DrawRightToLeft"))) { bmp.RotateFlip(RotateFlipType.RotateNoneFlipX); //draw right to left } return(bmp); }
void sinkSTChange(cdeP prop) { var t = TheThingRegistry.GetThingByMID(prop.cdeO); TheBaseAssets.MySYSLOG.WriteToLog(23010 + TheCommonUtils.CInt(prop), new TSM(MyBaseEngine.GetEngineName(), $"Plugin {t?.EngineName} Status Level Changed to {prop}", eMsgLevel.l4_Message)); }
public virtual void sinkThrottleChanged(cdeP pNewValue) { MyBaseThing.SetPublishThrottle(TheCommonUtils.CInt(pNewValue)); }
private void GetISMHealthData() { if (TheCommonUtils.cdeIsLocked(GetHealthLock) || !AreCounterInit) { return; } lock (GetHealthLock) { MyHealthData.StationWatts = LastStationWatts; MyHealthData.QSenders = TheCDEKPIs.QSenders; MyHealthData.QSReceivedTSM = TheCDEKPIs.QSReceivedTSM; MyHealthData.QSSendErrors = TheCDEKPIs.QSSendErrors; MyHealthData.QSInserted = TheCDEKPIs.QSInserted; MyHealthData.QSQueued = TheCDEKPIs.QSQueued; MyHealthData.QSRejected = TheCDEKPIs.QSRejected; MyHealthData.QSSent = TheCDEKPIs.QSSent; MyHealthData.QKBSent = Math.Floor(TheCDEKPIs.QKBSent > 0 ? TheCDEKPIs.QKBSent / 1024 : 0); MyHealthData.QKBReceived = Math.Floor(TheCDEKPIs.QKBReceived > 0 ? TheCDEKPIs.QKBReceived / 1024 : 0); MyHealthData.QSLocalProcessed = TheCDEKPIs.QSLocalProcessed; MyHealthData.CCTSMsRelayed = TheCDEKPIs.CCTSMsRelayed; MyHealthData.CCTSMsReceived = TheCDEKPIs.CCTSMsReceived; MyHealthData.CCTSMsEvaluated = TheCDEKPIs.CCTSMsEvaluated; MyHealthData.EventTimeouts = TheCDEKPIs.EventTimeouts; MyHealthData.TotalEventTimeouts = TheCDEKPIs.TotalEventTimeouts; MyHealthData.KPI1 = TheCDEKPIs.KPI1; MyHealthData.KPI2 = TheCDEKPIs.KPI2; MyHealthData.KPI3 = TheCDEKPIs.KPI3; MyHealthData.KPI4 = TheCDEKPIs.KPI4; MyHealthData.KPI5 = TheCDEKPIs.KPI5; MyHealthData.KPI6 = TheCDEKPIs.KPI6; MyHealthData.KPI7 = TheCDEKPIs.KPI7; MyHealthData.KPI8 = TheCDEKPIs.KPI8; MyHealthData.KPI9 = TheCDEKPIs.KPI9; MyHealthData.KPI10 = TheCDEKPIs.KPI10; MyHealthData.HTCallbacks = TheCDEKPIs.HTCallbacks; TheCDEKPIs.Reset(); MyHealthData.HostAddress = System.Environment.MachineName; MyHealthData.FriendlyName = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false); MyHealthData.HostVersion = TheBaseAssets.MyServiceHostInfo.Version; MyHealthData.LastUpdate = DateTimeOffset.Now; DiskInfo di = GetDiskInfo(); MyHealthData.DiskSpaceFree = di.TotalFreeSpace; if (di.TotalSize > 0 && di.TotalFreeSpace <= di.TotalSize) { MyHealthData.DiskSpaceUsage = ((di.TotalSize - di.TotalFreeSpace) / di.TotalSize) * 100; } else { MyHealthData.DiskSpaceUsage = 0; } try { if (wmiObjectWin32 != null) { var tRed = wmiObjectWin32.Get().Cast <ManagementObject>(); var memoryValues = tRed.Select(mo => new { FreePhysicalMemory = TheCommonUtils.CDbl(mo["FreePhysicalMemory"].ToString()), TotalVisibleMemorySize = TheCommonUtils.CDbl(mo["TotalVisibleMemorySize"].ToString()) }).FirstOrDefault(); if (memoryValues != null) { MyHealthData.RAMAvailable = memoryValues.FreePhysicalMemory; //var percent = ((memoryValues.TotalVisibleMemorySize - memoryValues.FreePhysicalMemory) / memoryValues.TotalVisibleMemorySize) * 100; } } } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(8007, new TSM("jcHealth", "wmiObject-Warning (Not Supported on XP)", eMsgLevel.l2_Warning, e.ToString())); } try { MeasureProcessCPU(); MyHealthData.cdeLoad = cpuUsageSinceLastMeasure; // Can also use cpuUsageSinceStart, depending on purpose of metric } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(8007, new TSM("jcHealth", "Could not get CPU usage for process", eMsgLevel.l2_Warning, e.ToString())); } try { if (MyCPULoadCounter != null) { MyHealthData.CPULoad = TheCommonUtils.CDbl(MyCPULoadCounter.NextValue()).cdeTruncate(2); } } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(8007, new TSM("jcHealth", "PerfCounter-Warning (Not Supported on XP)", eMsgLevel.l2_Warning, e.ToString())); MyCPULoadCounter = new PerformanceCounter { CategoryName = "Processor Information", CounterName = "% Processor Time", InstanceName = "_Total" }; } try { //if (MyHealthData != null && MyCDELoadCounter != null) // MyHealthData.cdeLoad = MyCDELoadCounter.NextValue().cdeTruncate(2); } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(8007, new TSM("jcHealth", "PerfCounter-Warning (Not Supported on XP)", eMsgLevel.l2_Warning, e.ToString())); MyCDELoadCounter = new PerformanceCounter { CategoryName = "Process", CounterName = "% Processor Time", InstanceName = Process.GetCurrentProcess().ProcessName }; } if (UseNicState) { UpdateNetworkInterface(); } else { if (MyCounter?.Count > 0) { foreach (var t in MyCounter) { try { MyHealthData.SetProperty(t.PropertyName, t.PerfCounter.NextValue()); } catch (Exception) { TheBaseAssets.MySYSLOG.WriteToLog(8007, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("jcHealth", $"PerfCounter: {t.PropertyName} could not be read", eMsgLevel.l2_Warning)); } } } } try { MyHealthData.cdeCTIM = DateTimeOffset.Now; MyHealthData.LastUpdate = DateTimeOffset.Now; using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select CreationDate from Win32_Process where Name='System'")) { foreach (ManagementObject share in searcher.Get()) { foreach (PropertyData pData in share.Properties) { if (pData.Name.Equals("CreationDate")) { DateTime dc = ManagementDateTimeConverter.ToDateTime(TheCommonUtils.CStr(pData.Value)); //dc = dc.AddTicks(-TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Ticks).ToLocalTime(); TimeSpan ts = DateTime.Now.Subtract(dc); MyHealthData.PCUptime = ts.TotalMinutes; } } } } /// cde Process Specific Information int nProcessID = Process.GetCurrentProcess().Id; using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select CreationDate,WorkingSetSize,HandleCount,ThreadCount from Win32_Process where ProcessID='" + nProcessID + "'")) { foreach (ManagementObject share in searcher.Get()) { foreach (PropertyData PC in share.Properties) { string objName = PC.Name; string objValue = ""; if (PC.Value != null && PC.Value.ToString() != "") { switch (PC.Value.GetType().ToString()) { case "System.String[]": string[] str = (string[])PC.Value; foreach (string st in str) { objValue += st + " "; } break; case "System.UInt16[]": ushort[] shortData = (ushort[])PC.Value; foreach (ushort st in shortData) { objValue += st.ToString() + " "; } break; default: objValue = PC.Value.ToString(); break; } } switch (objName) { case "CreationDate": DateTime dc = ManagementDateTimeConverter.ToDateTime(PC.Value.ToString()); //dc=dc.AddTicks(-TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Ticks).ToLocalTime(); TimeSpan ts = DateTime.Now.Subtract(dc); MyHealthData.cdeUptime = ts.TotalMinutes; break; case "WorkingSetSize": MyHealthData.cdeWorkingSetSize = TheCommonUtils.CLng(objValue) / 1024; break; case "HandleCount": MyHealthData.cdeHandles = TheCommonUtils.CInt(objValue); break; case "ThreadCount": MyHealthData.cdeThreadCount = TheCommonUtils.CInt(objValue); break; } } break; } } //if (!WasRunBefore) UpdateDiagInfo(MyHealthData); } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(8008, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("jcHealth", "Ring0-Warning", eMsgLevel.l2_Warning, e.ToString())); } } }
public override bool DoCreateUX() { 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}}", MyBaseThing.FriendlyName) }; var ts = TheNMIEngine.AddStatusBlock(MyBaseThing, MyStatusForm, 10); ts["Group"].SetParent(1); // loading spinner //var tDash = TheThingRegistry.IsEngineRegistered("CDMyNMIControls.TheNMIctrls") var tDash = new nmiDashboardTile { ClassName = "cdeDashPlate", Format = "Loading... <i class='fa fa-spinner fa-pulse'></i>", TileWidth = 2, TileHeight = 2, HTML = "<div><p><%C20:FriendlyName%></p><div id='COUNTD%cdeMID%'></div></div>", Style = "background-image:url('GlasButton.png');color:white;background-color:gray", RSB = true }; //: new ThePropertyBag { $"Format={MyBaseThing.FriendlyName}<br>{{0}}", "Foreground=white" }; SummaryForm.PropertyBag = tDash; SummaryForm.RegisterPropertyChanged(SinkStatChanged); var tControl = TheCommonUtils.CInt(TheThing.GetSafePropertyNumber(MyBaseThing, "ControlType")); var tBag = ThePropertyBag.CreateUXBagFromProperties(MyBaseThing); tBag.Add("ParentFld=1"); CountBar = tControl > 0 ? TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, (eFieldType)tControl, 21, 2, 0, "Current Value", "Value", tBag) : TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.BarChart, 21, 2, 0, "Current Value", "Value", new nmiCtrlBarChart { ParentFld = 1 }); //if (TheThingRegistry.IsEngineRegistered("CDMyNMIControls.TheNMIctrls")) { //MyGauge=TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.UserControl, 4000, 2, 0, "Countdown", "Value", new ThePropertyBag { "TileWidth=2", "NoTE=true", "EngineName=CDMyNMIControls.TheNMIctrls", "RenderTarget=COUNTD%cdeMID%", "ControlType=cdeNMI.ctrlCircularGauge", "LabelForeground=#00b9ff", "Foreground=#FFFFFF" }); MyGauge = TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.CircularGauge, 4000, 2, 0, "Countdown", "Value", new ThePropertyBag { "TileWidth=2", "NoTE=true", "RenderTarget=COUNTD%cdeMID%", "LabelForeground=#00b9ff", "Foreground=#FFFFFF" }); } var mSendbutton = TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.TileButton, 120, 2, 0x80, "Trigger", false, "", null, new nmiCtrlTileButton { NoTE = true, TileWidth = 3, ParentFld = 10, ClassName = "cdeGoodActionButton" }); mSendbutton.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "", (pThing, pPara) => { if (_mTimer != null) { _mTimer.Dispose(); _mTimer = null; } SinkTriggered(GetProperty("StartValue", false)); }); var mSP = TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.TileButton, 130, 2, 0x80, "Stop", false, "", null, new nmiCtrlTileButton { NoTE = true, TileWidth = 3, ParentFld = 10, ClassName = "cdeBadActionButton" }); mSP.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "", (pThing, pPara) => { if (_mTimer != null) { _mTimer.Dispose(); _mTimer = null; } }); // Settings Controls & User Input TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.CollapsibleGroup, 151, 2, 0x80, "Settings...", null, ThePropertyBag.Create(new nmiCtrlCollapsibleGroup { ParentFld = 1, TileWidth = 6, IsSmall = true, DoClose = true })); TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.Number, 153, 2, 0x80, "Tick time in ms", nameof(Frequency), new nmiCtrlNumber { TileWidth = 3, TileHeight = 1, ParentFld = 151 }); TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.Number, 156, 2, 0x80, "Step", nameof(Step), new nmiCtrlNumber { TileWidth = 3, TileHeight = 1, ParentFld = 151 }); TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.Number, 157, 2, 0x80, "Amplitude", nameof(Amplitude), new nmiCtrlNumber { TileWidth = 3, TileHeight = 1, ParentFld = 151 }); TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.Number, 158, 2, 0x80, "Shift", nameof(Shift), new nmiCtrlNumber { TileWidth = 3, TileHeight = 1, ParentFld = 151 }); TheNMIEngine.AddSmartControl(MyBaseThing, MyStatusForm, eFieldType.SingleCheck, 180, 2, 0x80, "Autostart", nameof(AutoStart), new nmiCtrlNumber { TileWidth = 3, TileHeight = 1, ParentFld = 151 }); return(true); }
private void GetCPUInfo(string URL) { MyCPUInfoData.HostAddress = System.Environment.MachineName; MyCPUInfoData.DiskSizeTotal = GetDiskInfo().TotalSize; MyCPUInfoData.LastUpdate = DateTimeOffset.Now; try { using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select Name,Description,Version,Manufacturer,Revision,AddressWidth,MaxClockSpeed,L2CacheSize,NumberOfCores from Win32_Processor")) { try { foreach (ManagementObject share in searcher.Get()) { foreach (PropertyData PC in share.Properties) { string objName = PC.Name; string objValue = ""; if (PC.Value != null && PC.Value.ToString() != "") { switch (PC.Value.GetType().ToString()) { case "System.String[]": string[] str = (string[])PC.Value; foreach (string st in str) { objValue += st + " "; } break; case "System.UInt16[]": ushort[] shortData = (ushort[])PC.Value; foreach (ushort st in shortData) { objValue += st.ToString() + " "; } break; default: objValue = PC.Value.ToString(); break; } } switch (objName) { case "Name": MyCPUInfoData.FriendlyName = objValue; break; case "Description": MyCPUInfoData.Description = objValue; break; case "Version": MyCPUInfoData.Version = objValue; break; case "Manufacturer": MyCPUInfoData.Manufacturer = objValue; break; case "Revision": MyCPUInfoData.Revision = TheCommonUtils.CInt(objValue); break; case "AddressWidth": MyCPUInfoData.AddressWidth = TheCommonUtils.CInt(objValue); break; case "MaxClockSpeed": MyCPUInfoData.MaxClockSpeed = TheCommonUtils.CInt(objValue); break; case "L2CacheSize": MyCPUInfoData.L2CacheSize = TheCommonUtils.CInt(objValue); break; case "NumberOfCores": MyCPUInfoData.NumberOfCores = TheCommonUtils.CInt(objValue); break; } } break; } } catch (Exception exp) { TheBaseAssets.MySYSLOG.WriteToLog(8009, new TSM("jcHealth", "CPUInfoGather-Warning", eMsgLevel.l2_Warning, exp.ToString())); } } } catch (Exception e) { MyCPUInfoData.Description = "MOS not supported"; } MyCoreTemps = new double[MyCPUInfoData.NumberOfCores]; MyCoreSpeeds = new uint[MyCPUInfoData.NumberOfCores]; }
/// <summary> /// Handles Messages sent from a host sub-engine to its clients /// </summary> /// <param name="Command"></param> /// <param name="pMessage"></param> public override void HandleMessage(ICDEThing sender, object pIncoming) { TheProcessMessage pMsg = pIncoming as TheProcessMessage; if (pMsg == null) { return; } string[] cmd = pMsg.Message.TXT.Split(':'); switch (cmd[0]) { case nameof(TheThing.MsgBrowseSensors): var browseRequest = TheCommRequestResponse.ParseRequestMessageJSON <TheThing.MsgBrowseSensors>(pMsg.Message); var browseResponse = new TheThing.MsgBrowseSensorsResponse { Error = "Internal error", Sensors = new List <TheThing.TheSensorSourceInfo>() }; foreach (FieldMapping fld in MyModFieldStore.TheValues) { browseResponse.Sensors.Add(new TheThing.TheSensorSourceInfo { SourceType = fld.SourceType, cdeType = ePropertyTypes.TNumber, SensorId = TheCommonUtils.CStr(fld.cdeMID), ExtensionData = new Dictionary <string, object> { { nameof(FieldMapping.SourceOffset), fld.SourceOffset }, { nameof(FieldMapping.SourceSize), fld.SourceSize }, { nameof(FieldMapping.AllowWrite), fld.AllowWrite } }, DisplayNamePath = new string[] { MyBaseEngine.GetEngineName(), MyBaseThing.FriendlyName, fld.PropertyName } }); } browseResponse.Error = null; TheCommRequestResponse.PublishResponseMessageJson(pMsg.Message, browseResponse); break; case nameof(TheThing.MsgSubscribeSensors): var subscribeRequest = TheCommRequestResponse.ParseRequestMessageJSON <TheThing.MsgSubscribeSensors>(pMsg.Message); var subscribeResponse = new TheThing.MsgSubscribeSensorsResponse { Error = "Internal error", SubscriptionStatus = new List <TheThing.TheSensorSubscriptionStatus>() }; if (subscribeRequest.ReplaceAll) { MyModFieldStore.RemoveAllItems(); } var subscriptionStatus = new List <TheThing.TheSensorSubscriptionStatus>(); foreach (TheThing.TheSensorSubscription sub in subscribeRequest.SubscriptionRequests) { FieldMapping fld = new FieldMapping() { PropertyName = sub.TargetProperty, cdeMID = TheCommonUtils.CGuid(sub.SensorId) }; if (fld.cdeMID == Guid.Empty) { fld.cdeMID = Guid.NewGuid(); } object sourceType; if (sub.ExtensionData != null) { if (sub.ExtensionData.TryGetValue(nameof(TheThing.TheSensorSourceInfo.SourceType), out sourceType)) { fld.SourceType = TheCommonUtils.CStr(sourceType); } object offset; if (sub.ExtensionData.TryGetValue("SourceOffset", out offset)) { fld.SourceOffset = TheCommonUtils.CInt(offset); } object size; if (sub.ExtensionData.TryGetValue("SourceSize", out size)) { fld.SourceSize = TheCommonUtils.CInt(size); } object allowWrite; if (sub.ExtensionData.TryGetValue("AllowWrite", out allowWrite)) { fld.AllowWrite = TheCommonUtils.CBool(allowWrite); } MyModFieldStore.AddAnItem(fld); subscriptionStatus.Add(CreateSubscriptionStatusFromFieldMapping(fld)); } else { subscriptionStatus.Add(new TheThing.TheSensorSubscriptionStatus { Error = "Missing source info", Subscription = sub, }); } } subscribeResponse.SubscriptionStatus = subscriptionStatus; subscribeResponse.Error = null; TheCommRequestResponse.PublishResponseMessageJson(pMsg.Message, subscribeResponse); break; case nameof(TheThing.MsgGetSensorSubscriptions): var getResponse = new TheThing.MsgGetSensorSubscriptionsResponse { Error = "Internal error" }; getResponse.Subscriptions = MyModFieldStore.TheValues.Select(fld => CreateSubscriptionStatusFromFieldMapping(fld).Subscription).ToList(); getResponse.Error = null; TheCommRequestResponse.PublishResponseMessageJson(pMsg.Message, getResponse); break; case nameof(TheThing.MsgUnsubscribeSensors): var unsubscribeRequest = TheCommRequestResponse.ParseRequestMessageJSON <TheThing.MsgUnsubscribeSensors>(pMsg.Message); var unsubscribeResponse = new TheThing.MsgUnsubscribeSensorsResponse { Error = "Internal error", Failed = new List <TheThing.TheSensorSubscriptionStatus>() }; if (unsubscribeRequest.UnsubscribeAll) { MyModFieldStore.RemoveAllItems(); if (MyModFieldStore.GetCount() > 0) { unsubscribeResponse.Failed = MyModFieldStore.TheValues.Select(fld => CreateSubscriptionStatusFromFieldMapping(fld)).ToList(); } } else { List <FieldMapping> toRemove = MyModFieldStore.TheValues.FindAll(fld => unsubscribeRequest.SubscriptionIds.Contains(fld.cdeMID)); MyModFieldStore.RemoveItems(toRemove, null); foreach (FieldMapping fld in MyModFieldStore.TheValues) { if (toRemove.Any(t => t.cdeMID == fld.cdeMID)) { unsubscribeResponse.Failed.Add(CreateSubscriptionStatusFromFieldMapping(fld)); } } } unsubscribeResponse.Error = null; TheCommRequestResponse.PublishResponseMessageJson(pMsg.Message, unsubscribeResponse); break; case nameof(TheThing.MsgExportConfig): var exportRequest = TheCommRequestResponse.ParseRequestMessageJSON <TheThing.MsgExportConfig>(pMsg.Message); var exportResponse = new TheThing.MsgExportConfigResponse { Error = "Internal error" }; // No custom config beyond config properties and subscriptions exportResponse.Error = null; TheCommRequestResponse.PublishResponseMessageJson(pMsg.Message, exportResponse); break; case nameof(TheThing.MsgApplyConfig): break; default: break; } TheThing.TheSensorSubscriptionStatus CreateSubscriptionStatusFromFieldMapping(FieldMapping fld) { return(new TheThing.TheSensorSubscriptionStatus { Subscription = new TheThing.TheSensorSubscription { TargetProperty = fld.PropertyName, SensorId = TheCommonUtils.CStr(fld.cdeMID), SubscriptionId = fld.cdeMID, ExtensionData = new Dictionary <string, object> { { nameof(FieldMapping.SourceType), fld.SourceType }, { nameof(FieldMapping.SourceOffset), fld.SourceOffset }, { nameof(FieldMapping.SourceSize), fld.SourceSize }, { nameof(FieldMapping.AllowWrite), fld.AllowWrite } }, TargetThing = new TheThingReference(MyBaseThing), SampleRate = (int?)this.Interval }, Error = null, }); } }