public void CollectInformation() { try { var nodeInfo = new CdeNodeInfo(_hostInfo); var targetDir = Path.Combine(_hostInfo.FileSystemUserBasePath, "diagnostics"); if (!Directory.Exists(targetDir)) { Directory.CreateDirectory(targetDir); } var file = $"CdeServiceHost_{_hostInfo.Id}.json"; var targetFile = Path.Combine(targetDir, file); if (File.Exists(targetFile)) { File.Delete(targetFile); } var serializedInfo = TheCommonUtils.SerializeObjectToJSONString(nodeInfo); File.WriteAllText(targetFile, serializedInfo); } catch (Exception ex) { _log.LogError(ex, $"Failed to collect and save service host diagnostic information!"); } }
/// <summary> /// Requests the capabilities of the Server /// </summary> /// <param name="pMagicID">MagicID to be used for back-publish</param> /// <param name="pCallBack">If set, and the call came from a local service, the sevices calls back without using the communication system</param> public void EdgeStorageServerRequestCaps(string pMagicID, Action <TSM> pCallBack) { if (TheCDEngines.MyIStorageService == null || TheCDEngines.MyIStorageService.GetBaseEngine().GetEngineState().IsService) { return; } string serializedXML = TheCommonUtils.SerializeObjectToJSONString(TheCDEngines.MyIStorageService.GetStorageCaps()); string post = "CDE_GETEDGECAPS"; if (pMagicID.Length > 0 && pCallBack != null) { MyTimedCallbacks.AddAnItem(new TheTimedCallback() { cdeMID = TheCommonUtils.CGuid(pMagicID), MyCallback = pCallBack }); post += ":" + pMagicID; } TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), post, serializedXML); if (TheCDEngines.MyIStorageService.GetBaseEngine().GetEngineState().IsService) { ProcessStorageServiceCommands(tTSM, pCallBack, true); } //else //Later for Remote Storage //{ // tTSM.SetToServiceOnly(true); // TheCommCore.PublishCentral(tTSM); //} }
private void OnDownloadClick(ICDEThing pThing, object pPara) { TheProcessMessage pMSG = pPara as TheProcessMessage; if (pMSG == null || pMSG.Message == null) { return; } string[] cmd = pMSG.Message.PLS.Split(':'); if (cmd.Length > 2) { TheThing tThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(cmd[2]), true); if (tThing == null) { return; } TSM tFilePush = new TSM(eEngineName.ContentService, string.Format("CDE_FILE:{0}.JSON:application/zip", tThing.FriendlyName)) { SID = pMSG.Message.SID, PLS = "bin", PLB = TheCommonUtils.CUTF8String2Array(TheCommonUtils.SerializeObjectToJSONString(tThing)) }; TheCommCore.PublishToOriginator(pMSG.Message, tFilePush); } }
private static void SendGlobalThings(Guid targetNodeId) { // Do not send more often than every 60 seconds if (lastGlobalThingSendPerNode.TryGetValue(targetNodeId, out thingSendStatus timeAndPending)) { if (DateTimeOffset.Now.Subtract(timeAndPending.lastSend).TotalSeconds < 59) // && !timeAndPending.Pending) { return; } } var globalThings = TheThingRegistry.GetThingsByFunc("*", (t) => TheThing.GetSafePropertyBool(t, "IsRegisteredGlobally") && t.IsOnLocalNode()); if (globalThings != null) { TSM tTSM = new TSM(eEngineName.ContentService, "CDE_SYNC_THINGS", TheCommonUtils.SerializeObjectToJSONString(globalThings)); tTSM.SetToServiceOnly(true); if (targetNodeId == Guid.Empty) { TheCommCore.PublishCentral(tTSM); } else { TheCommCore.PublishToNode(targetNodeId, tTSM); } lastGlobalThingSendPerNode[targetNodeId] = new thingSendStatus { lastSend = DateTimeOffset.Now, Pending = false }; } }
/// <summary> /// Encrypts the ISBConnect Class Properties against the local node's ScopeID /// </summary> /// <returns></returns> public byte[] EncryptedBuffer() { this.ES = TheBaseAssets.MyScopeManager.GetScrambledScopeID(); //SECURITY-REVIEW: No more ScopeID in clear Text string tPLS = TheCommonUtils.SerializeObjectToJSONString(this); byte [] tEncry = TheBaseAssets.MyCrypto.Encrypt(TheCommonUtils.CUnicodeString2Array(tPLS), TheBaseAssets.MySecrets.GetAK(), TheBaseAssets.MySecrets.GetNodeKey()); this.ES = null; return(tEncry); }
public static void CreateJsonResponse <T>(TheRequestData pRequest, T responsedata) { pRequest.ResponseMimeType = "application/json"; string strJson = TheCommonUtils.SerializeObjectToJSONString <T>(responsedata); pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array(strJson); pRequest.StatusCode = (int)eHttpStatusCode.OK; pRequest.DontCompress = true; pRequest.AllowStatePush = false; }
public static void SetResponseValue(TheRequestData pRequest, Guid guidValue) { pRequest.ResponseMimeType = "application/json"; string strJson = TheCommonUtils.SerializeObjectToJSONString <Guid>(guidValue); pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array(strJson); pRequest.StatusCode = (int)eHttpStatusCode.OK; pRequest.DontCompress = true; pRequest.AllowStatePush = false; }
//private static object GetTypedValue(StructMemberValue member) //{ // // TODO Use OPC and other type hints from cdeM to improve the type fidelity? // // TODO Move this into TheCommonUtils or cdeP itself // object retVal = member.Value; // switch (member.cdeT) // { // case (int)ePropertyTypes.TNumber: // retVal = TheCommonUtils.CDbl(member.Value); // break; // case (int)ePropertyTypes.TBoolean: // retVal = TheCommonUtils.CBool(member.Value); // break; // case (int)ePropertyTypes.TDate: // retVal = TheCommonUtils.CDate(member.Value); // break; // case (int)ePropertyTypes.TBinary: // retVal = TheCommonUtils.CByte(member.Value); // break; // case (int)ePropertyTypes.TGuid: // retVal = TheCommonUtils.CGuid(member.Value); // break; // case (int)ePropertyTypes.TString: // default: // retVal = member.Value; // break; // } // return retVal; //} string SerializeJSonArray(IEnumerable <JSonOpcArrayElement> jsonArray) { if (!(jsonArray is List <JSonOpcArrayElement>)) { jsonArray = new List <JSonOpcArrayElement>(jsonArray); } string eventPayloadJson = TheCommonUtils.SerializeObjectToJSONString(jsonArray as List <JSonOpcArrayElement>); return(eventPayloadJson); }
public void RegisterDeviceWithServer(Uri pTargetServer, Action <string, TheUPnPDeviceInfo> pCallback) { TheREST tRest = new TheREST(); var builder = new UriBuilder(pTargetServer) { Path = "DEVICEREG.JSON" }; tRest.PostRESTAsync(builder.Uri, sinkRegResult, TheCommonUtils.SerializeObjectToJSONString(MyDeviceUPnPInfo), pCallback, sinkRegResult); }
/// <summary> /// Places any additional properties of a derived class into TheThing.TheSensorSubscription.ExtensionData /// </summary> /// <returns></returns> public virtual TheThing.TheSensorSubscription GetBaseSubscription() { if (this.GetType().IsSubclassOf(typeof(TheThing.TheSensorSubscription))) { var baseJson = TheCommonUtils.SerializeObjectToJSONString(this); var baseSubscription = TheCommonUtils.DeserializeJSONStringToObject <TheThing.TheSensorSubscription>(baseJson); return(baseSubscription); } return(this); }
private void sinkRequestMeshInfo(TheRequestData request) { if (request != null) { request.ResponseMimeType = "application/json"; string errorText = ""; Dictionary <string, string> tQ = TheCommonUtils.ParseQueryString(request.RequestUri?.Query); if (tQ != null) { tQ.TryGetValue("MESHINFOTOKEN", out string meshInfoToken); if (tQ.TryGetValue("ORG", out string tOrg)) { Guid requestorMID = TheCommonUtils.CGuid(tOrg); if (requestorMID != Guid.Empty) { TheMeshInfoStatus meshInfoStatus = TheQueuedSenderRegistry.GetMeshInfoForNodeID(requestorMID, meshInfoToken); if (string.IsNullOrEmpty(meshInfoStatus?.StatusMessage)) { request.StatusCode = (int)eHttpStatusCode.OK; request.ResponseBuffer = TheCommonUtils.CUTF8String2Array(TheCommonUtils.SerializeObjectToJSONString(meshInfoStatus.MeshInfo)); } else { request.StatusCode = meshInfoStatus.StatusCode; //Better if meshInfoStatus also defines this as there are different messages (wrong MIT, too frequent tests etc) errorText = meshInfoStatus.StatusMessage; } } else { request.StatusCode = 400; errorText = "Invalid or badly formed ORG parameter."; } } else { request.StatusCode = 400; errorText = "No ORG parameter found for mesh info request."; } } else { request.StatusCode = (int)eHttpStatusCode.AccessDenied; errorText = "Access denied"; } if (!string.IsNullOrEmpty(errorText)) { TheErrorResponse errorResponse = new TheErrorResponse { Error = errorText, CTIM = DateTimeOffset.Now }; request.ResponseBuffer = TheCommonUtils.CUTF8String2Array(TheCommonUtils.SerializeObjectToJSONString(errorResponse)); } } }
private void sinkProcessResponse(TheRequestData pRequest) { if (pRequest.StatusCode >= 400 && pRequest.ResponseBuffer == null && !string.IsNullOrEmpty(pRequest.ErrorDescription)) { pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array(pRequest.ErrorDescription); } if (pRequest.ResponseBuffer == null && string.IsNullOrEmpty(pRequest.ResponseBufferStr)) { pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array("EMPTY"); } if (pRequest.ResponseMimeType.StartsWith("text/html") || pRequest.ResponseMimeType.Contains("javascript")) //OK { pRequest.ResponseBufferStr = TheCommonUtils.CArray2UTF8String(pRequest.ResponseBuffer); } string tReqUri = pRequest.RequestUri.Host; if (pRequest.RequestUri.Port != 80) { tReqUri += ":" + pRequest.RequestUri.Port; } 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 != 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) { Uri tCloudUri = new Uri(pRequest.RequestUriString); //pRequest.ResponseBufferStr = pRequest.ResponseBufferStr.Replace(pRequest.RequestUri.Host + ":" + pRequest.RequestUri.Port, new Uri(tMyApp.CloudUrl).Host + ":" + new Uri(tMyApp.CloudUrl).Port); pRequest.ResponseBufferStr = pRequest.ResponseBufferStr.Replace(pRequest.RequestUri.Scheme + "://" + tReqUri, tCloudUri.Scheme + "://" + tCloudUri.Host + ":" + tCloudUri.Port); pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array(pRequest.ResponseBufferStr); } } } TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Response Bytes:{1} For Page:{0} Sent", pRequest.cdeRealPage, pRequest.ResponseBuffer != null ? pRequest.ResponseBuffer.Length : 0), eMsgLevel.l3_ImportantMessage)); if (pRequest.ResponseBuffer != null) { //TheCommonUtils.SleepOneEye(5000, 100); TSM message3 = new TSM(MyBaseEngine.GetEngineName(), "WEBRELAY_RESPONSE") { PLB = pRequest.ResponseBuffer }; pRequest.ResponseBuffer = null; pRequest.ResponseBufferStr = null; pRequest.RequestUriString = pRequest.RequestUri.ToString(); TSM tMSG = pRequest.CookieObject as TSM; pRequest.CookieObject = null; pRequest.PostData = null; message3.PLS = TheCommonUtils.SerializeObjectToJSONString(pRequest); TheCommCore.PublishToOriginator(tMSG, message3); } }
private void sinkNewData(TheServiceHealthData pHealth) { List <TheChartPoint> tb = new List <TheChartPoint> { new TheChartPoint { value = pHealth.CPULoad.cdeTruncate(2), name = "CPU Load" }, new TheChartPoint { value = pHealth.cdeLoad.cdeTruncate(2), name = "CDE Load" } }; //TheThing.SetSafePropertyNumber(MyBaseThing, "LoadBucket", pHealth.CPULoad.cdeTruncate(2)); TheThing.SetSafePropertyString(MyBaseThing, "LoadBucket", TheCommonUtils.SerializeObjectToJSONString(tb));// pHealth.cdeLoad.cdeTruncate(2) +";1"); MyServiceHealth.HealthUpdateCycle = HealthCollectionCycle; }
//Who uses the .CDES File in the store? Moved into platform folder private static void WriteServiceInfo(ThePluginInfo tInfo, string storePath) { string tInfoFile; if (String.IsNullOrEmpty(storePath)) { tInfoFile = TheCommonUtils.cdeFixupFileName($"store\\{tInfo.cdeMID}\\{tInfo.Platform}\\{tInfo.ServiceName}.CDES"); } else { tInfoFile = Path.Combine(storePath, $"{tInfo.ServiceName}.CDES"); } using (StreamWriter sr = new StreamWriter(tInfoFile)) sr.Write(TheCommonUtils.SerializeObjectToJSONString <ThePluginInfo>(tInfo)); }
public void TestConfigModel() { var deviceTypes = TheThingRegistry.GetAllDeviceTypesByCap(nsCDEngine.ViewModels.eThingCaps.ConfigManagement, true); foreach (var deviceType in deviceTypes) { WriteLine($"{deviceType}: Starting test."); TestInfo testInfo; var configThing = CreateThingForTest(deviceType, out testInfo); WriteLine($"{deviceType}: Provider created"); int subscriptionCount; if (configThing.Capabilities.Contains(nsCDEngine.ViewModels.eThingCaps.SensorProvider)) { subscriptionCount = BrowseAndSubscribeAllSensors(configThing, null, testInfo.MaximumBrowseTags, testInfo.MinimumBrowseTags, out var browseResponse, out var sensorSubscriptionResponse, out var successfullSubscriptions); WriteLine($"{deviceType}: Browsed and subscribed to {subscriptionCount} source sensors"); } else { WriteLine($"{deviceType}: Not a sensor provider: skipping browse and subscribe"); subscriptionCount = 0; } { var exportedConfig = configThing.GetThingConfigurationAsync(false).Result; Assert.IsNotNull(exportedConfig, $"Timeout or subscribe message not implemented by plug-in: {deviceType}"); //Assert.IsTrue(string.IsNullOrEmpty(exportedConfig.Error)); // TODO Add an error property to TheThingConfiguration? Assert.AreEqual(subscriptionCount, exportedConfig.SensorSubscriptions?.Count ?? 0); Assert.Greater(exportedConfig.ConfigurationValues.Count, 0, $"No config properties returned: {deviceType}"); var configAsJson = TheCommonUtils.SerializeObjectToJSONString(exportedConfig); WriteLine($"{deviceType}: Generated configuration export with {exportedConfig.ConfigurationValues.Count} settings, {exportedConfig.SensorSubscriptions?.Count ?? 0} sensor subscriptions: " + "{0}", configAsJson); } { var exportedGeneralizedConfig = configThing.GetThingConfigurationAsync(true).Result; Assert.IsNotNull(exportedGeneralizedConfig, $"Timeout or subscribe message not implemented by plug-in: {deviceType}"); //Assert.IsTrue(string.IsNullOrEmpty(exportedConfig.Error)); // TODO Add an error property to TheThingConfiguration? Assert.AreEqual(subscriptionCount, exportedGeneralizedConfig.SensorSubscriptions?.Count ?? 0); Assert.Greater(exportedGeneralizedConfig.ConfigurationValues.Count, 0, $"No config properties returned: {deviceType}"); var configAsJson = TheCommonUtils.SerializeObjectToJSONString(exportedGeneralizedConfig); WriteLine($"{deviceType}: Generated generalized configuration with {exportedGeneralizedConfig.ConfigurationValues.Count} settings, {exportedGeneralizedConfig.SensorSubscriptions?.Count ?? 0} sensor subscriptions: " + "{0}", configAsJson); } TheThingRegistry.DeleteThing(configThing); } }
public void SendCPUInfo(TSM message) { Guid originator = message.GetOriginator(); if (originator == Guid.Empty) { SendCPUInfo(originator); } else { GetCPUInfo(TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false)); TSM tMsg = new TSM(MyEngineName, "CPUINFO", TheCommonUtils.SerializeObjectToJSONString <TheCPUInfo>(MyCPUInfoData)); tMsg.SetNoDuplicates(true); TheCommCore.PublishToOriginator(message, tMsg, true); TheBaseAssets.MySYSLOG.WriteToLog(8003, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : tMsg); } }
public static void SanitizeP08Data(List <OpcClientDataLogEntry> opcTags, List <OpcClientDataLogEntry> meshTags) { foreach (var t in opcTags) { t.Type = null; t.ReceiveTime = default(DateTimeOffset); if (t.TagId == "integer Array" && t.value != null) { t.value = TheCommonUtils.SerializeObjectToJSONString(t.value).Replace("[", "{").Replace(",", " |").Replace("]", "}"); } // // - value {{ // "Body": { // "ByteString": { // "@xmlns": "http://opcfoundation.org/UA/2008/02/Types.xsd", // "#text": "AQw=" // } // } // } // } // object {cdeNewtonsoft.Json.Linq.JObject //} if (t.value?.GetType().Name == "JObject") { t.value = new Dictionary <string, object> { { "IsAvailable", true }, { "QualityValue", 12 } }; } } foreach (var t in meshTags) { //if ((t.value as String)?.Contains("QualityValue") == true) //{ // var valueDict = TheCommonUtils.DeserializeJSONStringToObject<Dictionary<string,object>>(t.value as string); // valueDict["QualityValue"] = 12; // t.value = TheCommonUtils.SerializeObjectToJSONString(valueDict); //} if (t.value?.GetType().Name == "JObject") { t.value = new Dictionary <string, object> { { "IsAvailable", true }, { "QualityValue", 12 } }; } } }
internal string GetUserPrefString() { TheUserPreferences tPr = new TheUserPreferences { ShowClassic = ShowClassic, LCID = LCID, ThemeName = ThemeName, SpeakToasts = SpeakToasts, ShowToolTipsInTable = ShowToolTipsInTable, Transforms = TheNMIEngine.GetTransforms(this), CurrentUserName = Name, StartScreen = !string.IsNullOrEmpty(HomeScreen) ? HomeScreen.Split(';')[0] : null, PortalScreen = !string.IsNullOrEmpty(HomeScreen) && HomeScreen.Split(';').Length > 1 ? HomeScreen.Split(';')[1] : null }; return(TheCommonUtils.SerializeObjectToJSONString(tPr)); }
public void SendHealthInfo(TSM message) { Guid originator = message.GetOriginator(); if (originator == Guid.Empty) { SendHealthInfo(originator); } else { GetISMHealthData(); TSM tMsg = new TSM(MyEngineName, "ISMHEALTH", TheCommonUtils.SerializeObjectToJSONString <TheServiceHealthData>(MyHealthData)); tMsg.SetNoDuplicates(true); TheCommCore.PublishToOriginator(message, tMsg, true); eventNewHealthData?.Invoke(MyHealthData); TheBaseAssets.MySYSLOG.WriteToLog(8004, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : tMsg); } }
public void SendCPUInfo(Guid pOrg) { GetCPUInfo(TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false)); TSM tMsg = new TSM(MyEngineName, "CPUINFO", TheCommonUtils.SerializeObjectToJSONString <TheCPUInfo>(MyCPUInfoData)); tMsg.SetNoDuplicates(true); if (!TheBaseAssets.MyServiceHostInfo.IsCloudService) //Cloud would send unscoped Message going nowhere! { if (pOrg == Guid.Empty) { TheCommCore.PublishCentral(MyEngineName, tMsg); } else { TheCommCore.PublishToNode(pOrg, tMsg); } } TheBaseAssets.MySYSLOG.WriteToLog(8003, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : tMsg); }
public bool Init() { if (mIsInitCalled) { return(false); } mIsInitCalled = true; MyBaseThing.RegisterEvent(eEngineEvents.IncomingMessage, HandleMessage); if (TheThing.GetSafePropertyString(MyBaseThing, "VisitorCount") == "") { VisitorCount = 0; } MyNodePrintsName = $"NodePrints{TheThing.GetSafeThingGuid(MyBaseThing, "NodePrints")}"; TheBaseEngine.WaitForStorageReadiness(OnStorageReady, true); MyBaseThing.SetPublishThrottle(15000); TheCommCore.RegisterRelayEvents(null, null, sinkNewConnection); if (MyVisitorLog == null) { MyVisitorLog = new TheVisitorLog(MyBaseThing); } TheQueuedSenderRegistry.RegisterHealthTimer(GetSystemInfo); TheCDEngines.MyNMIService.RegisterEvent("NMI_MY_LOCATION", (sender2, para) => { var t = para as TheNMILocationInfo; if (t != null) { var NewEntry = new TheVisitorLogData { cdeN = t.cdeN, latitude = t.Latitude, longitude = t.Longitude, ip = t.ClientInfo?.UserID.ToString(), LastVisit = DateTimeOffset.Now, Description = t.ClientInfo != null && t.ClientInfo.UserID != Guid.Empty ? TheUserManager.GetUserFullName(t.ClientInfo.UserID) : "Unknown user" }; MyVisitorLog.LogVisitor(NewEntry); myGoogleMap?.SetUXProperty(Guid.Empty, $"AddMarker={TheCommonUtils.SerializeObjectToJSONString(NewEntry)}"); } }); TheCommCore.MyHttpService.RegisterHttpInterceptorB4("/cdemeshinfo.aspx", sinkRequestMeshInfo); MyBaseEngine.ProcessInitialized(); MyBaseEngine.SetEngineReadiness(true, null); MyBaseEngine.SetStatusLevel(1); mIsInitialized = true; return(true); }
private static void ResponseCreateToken(TheRequestData pRequest) { Guid pNewToken = Guid.NewGuid(); DateTime pNow = DateTime.Now; if (dictValidAccessTokens == null) { InitAccessTokenTable(); } dictValidAccessTokens[pNewToken] = pNow; pRequest.ResponseMimeType = "application/json"; string strJson = TheCommonUtils.SerializeObjectToJSONString <Guid>(pNewToken); pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array(strJson); pRequest.StatusCode = (int)eHttpStatusCode.OK; pRequest.DontCompress = true; pRequest.AllowStatePush = false; }
public override IEnumerable <object> GetEventData(IEnumerable <TheThingStore> thingUpdates, IThingToConvert senderThing, int maxEventDataSize, bool doNotBatchEvents) { var eventList = new List <object>(); foreach (var thingUpdate in thingUpdates) { var jsonArray = GetJSONArray(thingUpdate); if (doNotBatchEvents) { eventList.AddRange(jsonArray.Select(elem => (object)TheCommonUtils.SerializeObjectToJSONString(elem))); } eventList.AddRange(GetEvents(jsonArray, maxEventDataSize)); //if (events.Count() > 1) //{ // Console.WriteLine("Returning {0} events for {1} properties", events.Count(), jsonArray.Count); //} } return(eventList); }
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); }
private void ProcessPubSubMessage(DateTimeOffset time, string channel, string message) { try { var pubSubMessage = TheCommonUtils.DeserializeJSONStringToObject <ThePubSubMessage>(message); var bSuccess = ProcessMessage(pubSubMessage.MsgId, pubSubMessage.PayloadFormat, time, pubSubMessage.Payload, null, true, out var ReceiveErrorCount, out var bSendAck); if (bSendAck) { var ackMessage = new ThePubSubAckMessage { MsgId = pubSubMessage.MsgId, Error = ReceiveErrorCount, Success = bSuccess, }; var ackMessageString = TheCommonUtils.SerializeObjectToJSONString(ackMessage); _publisher.Publish($"{channel}/ack", ackMessageString); } } catch { } }
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); }
public override void Connect(TheProcessMessage pMsg) { if (IsConnected) { return; } IsConnected = true; MyBaseThing.StatusLevel = 1; MyBaseThing.LastMessage = $"Connected to Logger at {DateTimeOffset.Now}"; mLogFilePath = Address; mMaxLogFileSize = (int)TheThing.GetSafePropertyNumber(MyBaseThing, "MaxLogFileSize"); mWriteToConsole = TheThing.GetSafePropertyBool(MyBaseThing, "WriteToConsole"); MyCurLog = TheThing.GetSafePropertyString(MyBaseThing, "LogFilePath"); mLogFileDate = TheThing.GetSafePropertyDate(MyBaseThing, "LogFileDate"); if (string.IsNullOrEmpty(MyCurLog) || (mLogFileDate != DateTimeOffset.MinValue && mLogFileDate.Day != DateTimeOffset.Now.Day)) { LogFilePath = MyCurLog = TheCommonUtils.cdeFixupFileName(mLogFilePath + string.Format("\\LOG_{0:yyyMMdd_HHmmss}.txt", DateTime.Now)); LogFileDate = mLogFileDate = DateTimeOffset.Now; } TheCommonUtils.CreateDirectories(MyCurLog); TheCDEngines.MyContentEngine.RegisterEvent(eEngineEvents.NewEventLogEntry, sinkNewEvent); #if !CDE_NET4 && !CDE_NET35 if (TheBaseAssets.MyCmdArgs?.ContainsKey("CreateEventLog") != true) { // CODE REVIEW: What is the purpose of this export? var pipelineConfig = MyBaseThing.GetThingPipelineConfigurationAsync(false).Result; if (pipelineConfig != null) { var tWrite = TheCommonUtils.SerializeObjectToJSONString(pipelineConfig); TheCommonUtils.CreateDirectories(TheCommonUtils.cdeFixupFileName($"\\ConfigTemplates\\{MyBaseThing.FriendlyName}.cdeConfig")); using (System.IO.StreamWriter fs = new System.IO.StreamWriter(TheCommonUtils.cdeFixupFileName($"\\ConfigTemplates\\{MyBaseThing.FriendlyName}.cdeConfig"), false)) { fs.Write(tWrite); } } } #endif }
string SerializeJSonArray(TheThingStore thingEvent, IEnumerable<Measurement> measurements) { if (!(measurements is List<Measurement>)) { measurements = new List<Measurement>(measurements); } var payload = new MeasurementPayload(); object deviceId; if (thingEvent.PB.TryGetValue("deviceID", out deviceId)) { payload.device.deviceID = TheCommonUtils.CStr(deviceId); } else { payload.device.deviceID = TheCommonUtils.cdeGuidToString(thingEvent.cdeMID); } payload.measurements.AddRange(measurements); string eventPayloadJson = TheCommonUtils.SerializeObjectToJSONString(payload); //eventPayloadJson = eventPayloadJson.Replace("\"contentspec\"", "\"content-spec\""); // Hack to avoid newtonsoft dependency for now: attribute ignored by cdeEngine internal serializer return eventPayloadJson; }
private void LogKPIs() { var kpis = new Dictionary <string, object>(); foreach (var kpiPropName in new List <string> { nameof(EventsSentSinceStart), nameof(PendingEvents), nameof(EventsSentErrorCountSinceStart), nameof(LastSendTime), nameof(LastSendAttemptTime), }) { kpis.Add(kpiPropName, TheThing.GetSafeProperty(MyBaseThing, kpiPropName)); } var message = new TSM(strPrometheusExporter, "Prometheus Exporter KPIs", eMsgLevel.l4_Message, TheCommonUtils.SerializeObjectToJSONString(kpis)); TheBaseAssets.MySYSLOG.WriteToLog(95013, TSM.L(eDEBUG_LEVELS.OFF) ? null : message); if (!String.IsNullOrEmpty(KPIPublishPropertyName)) { foreach (var senderThing in MySenderThings.MyMirrorCache.TheValues) { TheThing.SetSafeProperty(senderThing.GetThing(), KPIPublishPropertyName, new TSMObjectPayload(message, kpis), ePropertyTypes.NOCHANGE); // CODE REVIEW: OK to put an entire message here? This will be serialized to JSON properly, but... } } }
private async Task <bool> Initialize(OPCUAParameters opcUAParameters, ThingCreationParameters thingCreation) { if (thingCreation == null) { thingCreation = new ThingCreationParameters(); } Dictionary <string, object> properties; if (opcUAParameters != null) { try { properties = TheCommonUtils.DeserializeJSONStringToObject <Dictionary <string, object> >(TheCommonUtils.SerializeObjectToJSONString(opcUAParameters)); } catch { return(false); } } else { properties = new Dictionary <string, object>(); } var tTaskForThing = TheThingRegistry.CreateOwnedThingAsync(new TheThingRegistry.MsgCreateThingRequestV1 { EngineName = TheOPCUAClientEngines.EngineName, DeviceType = eOPCUAClientDeviceTypes.RemoteServer, Address = ServerAddress, CreateIfNotExist = thingCreation.CreateIfNotExist, FriendlyName = thingCreation.FriendlyName, Hidden = thingCreation.Hidden, ReadOnly = thingCreation.ReadOnly, InstanceId = thingCreation.InstanceId, OwnerAddress = OwnerAddress, Properties = properties, }, new TheMessageAddress { Node = TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID }, new TimeSpan(0, 0, 30)); var tThing = await tTaskForThing; if (tThing == null) { return(false); } OpcThingAddress = tThing; _opcThing = tThing; RegisterEvent(eOPCUAClientEvents.ConnectComplete, sinkConnected); RegisterEvent(eOPCUAClientEvents.ConnectFailed, sinkConnectFailure); RegisterEvent(eOPCUAClientEvents.DisconnectComplete, sinkDisconnected); return(true); }