public override bool Init() { if (mIsInitCalled) { return(false); } mIsInitCalled = true; MyBaseThing.RegisterEvent(eEngineEvents.IncomingMessage, HandleMessage); MyBaseEngine.RegisterEvent(eEngineEvents.ThingDeleted, OnDeletedThing); MyBaseEngine.RegisterEvent(eEngineEvents.ThingRegistered, OnThingRegistered); MyBaseEngine.RegisterEvent(eEngineEvents.ShutdownEvent, OnShutdown); TheCommonUtils.cdeRunAsync("Init Prometheus Exporters", false, (state) => { try { InitServers(); } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(181001, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, "Error initializing instances", eMsgLevel.l1_Error, e.ToString())); } mIsInitialized = true; FireEvent(eThingEvents.Initialized, this, true, true); MyBaseEngine.ProcessInitialized(); }, null); return(false); }
/// <summary> /// Handles Messages sent from a host sub-engine to its clients /// </summary> public void HandleMessage(ICDEThing sender, object pIncoming) { if (!(pIncoming is TheProcessMessage pMsg)) { return; } switch (pMsg.Message.TXT) { case "CDE_INITIALIZED": TheBaseAssets.MySYSLOG.WriteToLog(888, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("MiniRelayService", $"BackChannel Updated - ORG:{TheCommonUtils.GetDeviceIDML(pMsg.Message.GetLastRelay())}", eMsgLevel.l3_ImportantMessage)); break; default: if (pMsg.Message.TXT.Equals("CDE_INITIALIZE")) { TSM tRelayMsg = new TSM(MyBaseEngine.GetEngineName(), "CDE_INITIALIZED") { QDX = 3, SID = pMsg.Message.SID }; tRelayMsg.SetNoDuplicates(true); TheBaseAssets.MySYSLOG.WriteToLog(888, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("MiniRelayService", $"Message Text {tRelayMsg.TXT} relayed - ORG:{TheCommonUtils.GetDeviceIDML(tRelayMsg.ORG)}", eMsgLevel.l3_ImportantMessage)); //ORG-OK TheCommCore.PublishCentral(MyBaseEngine.GetEngineName() + pMsg.Message?.AddScopeIDFromTSM(), tRelayMsg); } break; } }
void InitServers() { List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(this.MyBaseEngine.GetEngineName()); if (tDevList.Count > 0) { foreach (TheThing tDev in tDevList) { try { if (!tDev.HasLiveObject) { switch (tDev.DeviceType) { case PrometheusDeviceTypes.PrometheusExporter: var tPS = new ThePrometheusExporter(tDev, this); TheThingRegistry.RegisterThing(tPS); break; } } } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(181001, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, $"Error creating exporter instance {tDev?.cdeMID} / {tDev?.FriendlyName}", eMsgLevel.l1_Error, e.ToString())); } } } MyBaseEngine.SetStatusLevel(-1); }
void sinkThingWasUpdated(ICDEThing sender, object pPara) { if (TheBaseAssets.MyServiceHostInfo.IsCloudService) { return; //TODO: Allow Cloud Rules } TheThing pThing = sender as TheThing; if (pThing != null && TheThing.GetSafePropertyString(pThing, "DeviceType") == eKnownDeviceTypes.TheThingRule) { TheRule tRule = pThing.GetObject() as TheRule; if (tRule == null) { tRule = new TheRule(pThing, this); tRule.RegisterEvent(eEngineEvents.ThingUpdated, sinkUpdated); RegisterRule(tRule); } { tRule.IsRuleWaiting = true; tRule.IsRuleRunning = false; TheSystemMessageLog.WriteLog(4445, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(eKnownDeviceTypes.TheThingRule, $"Rule {tRule.FriendlyName} stopped on Rule Update"), false); TheThingRegistry.UpdateThing(tRule, false); } ActivateRules(); } }
private static void SetCookies(TheInternalRequestState myRequestState) { myRequestState.MyRequestData.TempCookies = new CookieContainer(); if (myRequestState.MyRequestData.RequestCookies != null && myRequestState.MyRequestData.RequestCookies.Count > 0) { foreach (string nam in myRequestState.MyRequestData.RequestCookies.Keys) { try { string tVal = myRequestState.MyRequestData.RequestCookies[nam]; if (string.IsNullOrEmpty(tVal)) { continue; } string[] co = tVal.Split(';'); string val = co[0]; string pat = "/"; //if (co.Length > 1) pat = co[1]; //string dom = ""; if (co.Length > 2) dom = co[2]; string dom = myRequestState.MyRequestData.RequestUri.Host.Trim(); //if (string.IsNullOrEmpty(dom)) //TheSystemMessageLog.ToCo(string.Format("GetREST: Cookie: ({0}) ({1}) ({2}) ({3})", nam,val,pat,dom)); myRequestState.MyRequestData.TempCookies.Add(myRequestState.MyRequestData.RequestUri, new Cookie(nam.Trim(), val.Trim(), pat, dom)); } catch (Exception e) { if (TheBaseAssets.MySYSLOG != null) { TheBaseAssets.MySYSLOG.WriteToLog(254, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheREST", "SetCookies Exception: " + myRequestState.MyRequestData.RequestUri, eMsgLevel.l1_Error, e.Message)); } } } //TheSystemMessageLog.ToCo(string.Format("GetREST: CookieCont: ({0})", myRequestState.MyRequestData.TempCookies.GetCookieHeader(myRequestState.MyRequestData.RequestUri))); } }
public void LogChanges(bool IsConsumer, cdeP[] changedProperties = null) { string logMessage = ""; if (IsConsumer) { List <TheThingStore> history = testThing.GetThingHistory(historyToken, 1, false); logMessage = "Aggregated - "; foreach (TheThingStore snapShot in history) { foreach (string property in properties) { if (snapShot.PB.TryGetValue(property, out var propValue)) { logMessage += $"{property}: {propValue} | "; } } } } else { logMessage = $"{testThing.FriendlyName} - "; if (changedProperties != null) { foreach (cdeP property in changedProperties) { logMessage += $"{property.Name}: {property.Value} | "; } } } // Log the message to SYSLOG TheBaseAssets.MySYSLOG.WriteToLog( 2020, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseEngine.GetEngineName(), logMessage, IsConsumer ? eMsgLevel.l3_ImportantMessage : eMsgLevel.l4_Message)); }
public static void ConditionRefresh(Subscription subscription, TheOPCUARemoteServer serverForLogging) { bool refreshNeeded = false; foreach (var monitoredItem in subscription.MonitoredItems) { if (monitoredItem.Handle is TheOPCEvent eventTag) { if (eventTag.RefreshNeeded) { refreshNeeded = true; eventTag.RefreshNeeded = false; TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(serverForLogging.GetBaseThing()?.EngineName, $"Will trigger refresh for {serverForLogging.GetLogAddress()}, {eventTag.GetInfoForLog()}", eMsgLevel.l6_Debug)); } else { TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(serverForLogging.GetBaseThing()?.EngineName, $"Skipping condition refresh for {serverForLogging.GetLogAddress()}, {eventTag.GetInfoForLog()}", eMsgLevel.l6_Debug)); } } } if (refreshNeeded) { TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(serverForLogging.GetBaseThing()?.EngineName, $"Refreshing conditions for {serverForLogging.GetLogAddress()}", eMsgLevel.l6_Debug)); try { subscription.ConditionRefresh(); TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(serverForLogging.GetBaseThing()?.EngineName, $"Requested condition refresh for {serverForLogging.GetLogAddress()}", eMsgLevel.l6_Debug)); } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(78102, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(serverForLogging.GetBaseThing()?.EngineName, $"Internal error requesting condition request for {serverForLogging.GetLogAddress()}", eMsgLevel.l1_Error, TSM.L(eDEBUG_LEVELS.VERBOSE) ? e.Message : e.ToString())); } } }
/// <summary> /// Sets a client Certificate on TheRequestData /// </summary> /// <param name="pData"></param> /// <param name="pThumbPrint"></param> /// <returns></returns> internal static bool SetClientCert(TheRequestData pData, string pThumbPrint) { if (!string.IsNullOrEmpty(pThumbPrint)) { try { X509Certificate2Collection certs = null; if (pThumbPrint == TheBaseAssets.MyServiceHostInfo.ClientCertificateThumb) { certs = TheBaseAssets.MyServiceHostInfo.ClientCerts; //Use cached value if master cache } else { certs = GetClientCertificatesByThumbprint(pThumbPrint); //load a custom cert for ISB Connect and other client cert scenarios } if (certs?.Count > 0) { pData.ClientCert = certs[0]; return(true); //Client cert could be set to TheRequestData } } catch (Exception certex) { TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheCommonUtils", "Error setting Client Certificate", eMsgLevel.l1_Error, certex.ToString())); } return(false); //ClientThumb is set but could not be added to TheRequestData...let caller know } return(true); //Not set..all is good }
internal bool Startup() { if (TheBaseAssets.MyServiceHostInfo.MyStationWSPort == 0 || TheBaseAssets.MyServiceHostInfo.MyStationWSPort == TheBaseAssets.MyServiceHostInfo.MyStationPort) return false; mHttpListener = new HttpListener(); Uri tUri = new Uri(TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false)); MyHttpUrl = tUri.Scheme + "://*"; // +tUri.Host; MyHttpUrl += ":" + TheBaseAssets.MyServiceHostInfo.MyStationWSPort; MyHttpUrl += "/"; try { mHttpListener.Prefixes.Add(MyHttpUrl); mHttpListener.Start(); TheBaseAssets.MySYSLOG.WriteToLog(4370, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheWSServer", "New WebSockets8 HttpListener started ", eMsgLevel.l4_Message, $"Port: {TheBaseAssets.MyServiceHostInfo.MyStationWSPort}")); IsActive = true; TheCommonUtils.cdeRunAsync("WebSocketServer - Processing Thread", true, async o => { while (IsActive && TheBaseAssets.MasterSwitch) { try { if (mHttpListener != null) { HttpListenerContext context = await mHttpListener.GetContextAsync(); if (!context.Request.IsWebSocketRequest) { context.Response.StatusCode = 400; context.Response.Close(); continue; } TheCommonUtils.cdeRunAsync("WSWait4AcceptThread", false, async oo => { try { await WaitForWSAccept(context); } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(4371, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSServer", "Error During WSAccept", eMsgLevel.l1_Error, e.ToString())); IsActive = false; } }); } } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(4372, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSServer", "WebSocketServer:Failed - Will Stop!", eMsgLevel.l1_Error, e.ToString())); IsActive = false; } } ShutDown(); }); } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(4373, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSServer", "Error During Startup", eMsgLevel.l1_Error, $"Port: {TheBaseAssets.MyServiceHostInfo?.MyStationWSPort} {e.ToString()}")); IsActive = false; } return IsActive; }
/// <summary> /// Sets a new client Certificate. If it contains a scopeid and ApplyScope is true, the node will be scoped with that ScopeID /// </summary> /// <param name="pCertThumb">Thumbprint of the new client certificate</param> /// <param name="ApplyScope">if true, the scope in the certificate will be used to scope the node</param> /// <returns></returns> public static string SetClientCertificate(string pCertThumb, bool ApplyScope = false) { if (!string.IsNullOrEmpty(pCertThumb)) { TheBaseAssets.MyServiceHostInfo.ClientCertificateThumb = pCertThumb; TheBaseAssets.MyServiceHostInfo.ClientCerts = GetClientCertificatesByThumbprint(pCertThumb); if (TheBaseAssets.MyServiceHostInfo.ClientCerts == null || TheBaseAssets.MyServiceHostInfo.ClientCerts?.Count == 0) //No valid client certifcate found { TheBaseAssets.MyServiceHostInfo.ClientCertificateThumb = null; TheBaseAssets.MyServiceHostInfo.ClientCerts = null; TheBaseAssets.MySYSLOG.WriteToLog(4151, new TSM("TheBaseAssets", $"Client Certificate with Thumbprint {pCertThumb} required but not found! Connection to Cloud not possible", eMsgLevel.l1_Error)); } else { string error = ""; var tScopes = GetScopesFromCertificate(TheBaseAssets.MyServiceHostInfo.ClientCerts[0], ref error); if (tScopes?.Count > 0) { TheBaseAssets.MySYSLOG.WriteToLog(2821, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheCommonUtils", $"Scope {tScopes[0]} found in Certificate {(ApplyScope ? "and applied" : "")}", eMsgLevel.l3_ImportantMessage)); if (ApplyScope) { TheBaseAssets.MyScopeManager.SetScopeIDFromEasyID(tScopes[0]); } return(tScopes[0]); } else { TheBaseAssets.MySYSLOG.WriteToLog(4151, new TSM("TheBaseAssets", $"Client Certificate with Thumbprint {pCertThumb} found and will be applied as soon as cloud is connected")); } } } return(null); }
public void WriteSession(TheSessionState pSession) { if (pSession == null || pSession.HasExpired) //we should never write an expired Session { return; } try { pSession.LastAccess = DateTimeOffset.Now; pSession.cdeCTIM = DateTimeOffset.Now; pSession.PageHits++; MySessionStates.UpdateItem(pSession, null); #if CDE_LOGSESSIONS if (TheCDEngines.MyStorageService != null) { //LogSession(pSession.cdeMID, pSession.CurrentURL, pSession.Browser, pSession.BrowserDesc, pSession.InitReferer, pSession.CustomData); TheBaseAssets.MySYSLOG.WriteToLog(1236, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("SSM", "WriteRession: Writing ", eMsgLevel.l6_Debug, pSession.ToString())); } #endif } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(1237, new TSM("SSM", "WriteRession: Exception occured:", eMsgLevel.l2_Warning, e.ToString())); } }
internal void Startup() { TheDiagnostics.SetThreadName("WSStartup"); if (TheBaseAssets.MyServiceHostInfo.MyStationWSPort == 0) return; Uri tUri = new Uri(TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false)); MyHttpUrl = tUri.Scheme + "://*"; // +tUri.Host; MyHttpUrl += ":" + TheBaseAssets.MyServiceHostInfo.MyStationWSPort; MyHttpUrl += "/"; appServer = new WebSocketServer(); //Setup the appServer if (!appServer.Setup(new ServerConfig() { Port = TheBaseAssets.MyServiceHostInfo.MyStationWSPort, MaxRequestLength = 400000 })) //Setup with listening port { TheBaseAssets.MySYSLOG.WriteToLog(4343, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSServer", "Error During Startup", eMsgLevel.l1_Error)); return; } appServer.NewMessageReceived += new SessionHandler<WebSocketSession, string>(appServer_NewMessageReceived); appServer.NewDataReceived += appServer_NewDataReceived; appServer.NewSessionConnected += appServer_NewSessionConnected; appServer.SessionClosed += appServer_SessionClosed; //Try to start the appServer if (!appServer.Start()) { TheBaseAssets.MySYSLOG.WriteToLog(4343, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSServer", "Failed to start Super-Web-Socket Server", eMsgLevel.l1_Error)); IsActive = false; return; } IsActive = true; TheBaseAssets.MySYSLOG.WriteToLog(4343, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheWSServer", "New Super-Web-Socket Server started ", eMsgLevel.l4_Message)); }
private async void OnWatchDogTimer(object state) { try { OnSendAttempt(null); var timeSinceLastAttempt = DateTimeOffset.Now - LastSendAttemptTime; if (timeSinceLastAttempt > new TimeSpan(0, 0, WatchDogIdleRecycleIntervalInMinutes, 0)) { TheBaseAssets.MySYSLOG.WriteToLog(95014, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"WatchDog: No activity since {LastSendAttemptTime}. Disconnecting Sender and waiting 5 seconds to reconnect.", eMsgLevel.l4_Message)); Disconnect(true); try { await TheCommonUtils.TaskDelayOneEye(5000, 100); } catch (TaskCanceledException) { } if (TheBaseAssets.MasterSwitch) { TheBaseAssets.MySYSLOG.WriteToLog(95015, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"WatchDog: Reconnecting Sender.", eMsgLevel.l4_Message)); Connect(); } } } catch (Exception ex) { TheBaseAssets.MySYSLOG.WriteToLog(95302, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"WatchDog: Internal error.", eMsgLevel.l1_Error, ex.ToString())); } }
private void StorageHasStarted(ICDEThing sender, object pReady) { if (pReady != null) { if (MyServiceHealthDataStore == null) { MyServiceHealthDataStore = new TheStorageMirror <TheThingStore>(TheCDEngines.MyIStorageService) { IsRAMStore = "RAM".Equals(pReady.ToString()), IsCachePersistent = "RAM".Equals(pReady.ToString()) && !TheBaseAssets.MyServiceHostInfo.IsCloudService, CacheTableName = "TheHealthHistory" }; if (MyServiceHealthDataStore.IsRAMStore) { MyServiceHealthDataStore.SetRecordExpiration(86400, null); //RAM stores for 1 day MyServiceHealthDataStore.InitializeStore(true, false); } else { MyServiceHealthDataStore.SetRecordExpiration(604800, null); //Storage stores for 7 days MyServiceHealthDataStore.CreateStore("C-DMyComputer: DeviceHealthData", "All health Data of a Device/Service", null, true, false); } TheBaseAssets.MySYSLOG.WriteToLog(8002, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("jcHealth", "Health Storage Started", eMsgLevel.l3_ImportantMessage)); } } }
/// <summary> /// Set the first request to the WS-Processor. It will be used to handle all WebSocket data for the session of the related node /// </summary> /// <param name="pRequest">If null, the Processor will create a new empty TheRequestData to handle all traffic</param> public void SetRequest(TheRequestData pRequest) { if (pRequest == null) { MySessionRequestData = new TheRequestData(); } else { MySessionRequestData = pRequest; } MySessionRequestData.WebSocket = this; mre = new ManualResetEventSlim(true); IsActive = true; CloseFired = false; try { if (TheCommCore.MyHttpService != null && MySessionRequestData.RequestUri != null) { TheCommCore.MyHttpService.cdeProcessPost(MySessionRequestData); } } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(4360, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSProcessor", "cdeProcssPost Error", eMsgLevel.l1_Error, e.ToString())); } }
void appServer_NewSessionConnected(WebSocketSession session) { TheBaseAssets.MySYSLOG.WriteToLog(4343, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheSWSServer", string.Format("New Session: {0} ID:{1}", session.RemoteEndPoint.ToString(), session.SessionID))); try { TheWSProcessor tProcessor = new TheWSProcessor(session); mSessionList.TryAdd(session.SessionID, tProcessor); TheRequestData tRequestData = new TheRequestData(); tRequestData.RequestUri = new Uri(session.UriScheme + "://" + session.Host + session.Path); // pContext.Request.Url; tRequestData.Header = new cdeConcurrentDictionary<string, string>(); foreach (var tKey in session.Items) { switch (tKey.Key.ToString().ToLower()) { case "user-agent": //tRequestData.UserAgent = pContext.Request.UserAgent; tRequestData.UserAgent = tKey.Value.ToString(); break; case "content-type": //tRequestData.ResponseMimeType = pContext.Request.ContentType; tRequestData.ResponseMimeType = tKey.Value.ToString(); break; } tRequestData.Header.TryAdd(tKey.Key.ToString(), tKey.Value.ToString()); } tRequestData.ServerTags = null; tProcessor.SetRequest(tRequestData); } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(4343, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheSWSServer", "Error during new Session-Connect", eMsgLevel.l1_Error,e.ToString())); } }
bool ProcessCDEngine(TheUPnPDeviceInfo tHistory, Uri tLocationUrl) { if ((tLocationUrl.Host.Equals(TheBaseAssets.MyServiceHostInfo.MyStationIP) && tLocationUrl.Port == TheBaseAssets.MyServiceHostInfo.MyStationPort) || !tHistory.PacketString.Contains(TheBaseAssets.MyServiceHostInfo.ApplicationName) || tLocationUrl.Host.Contains("127.0.0.1")) { return(true); } TheBaseAssets.MySYSLOG.WriteToLog(111, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("UPnP", string.Format("C-DEngine Root Device Found: {0}", tHistory), eMsgLevel.l7_HostDebugMessage)); if (!TheBaseAssets.MyServiceHostInfo.DisableUPnPAutoConnect && TheBaseAssets.MyServiceHostInfo.ApplicationName.Equals(tHistory.ModelName)) { if (!string.IsNullOrEmpty(tHistory.CDEContextID)) { if (!string.IsNullOrEmpty(tHistory.CDEProvisionUrl)) { TheBaseAssets.MySettings.SetSetting("AutoProvisioningUrl", tHistory.CDEProvisionUrl); } if (!TheBaseAssets.MyScopeManager.IsScopingEnabled || (TheBaseAssets.MyScopeManager.IsScopingEnabled && !TheBaseAssets.MyScopeManager.ScopeID.Equals(TheBaseAssets.MyScopeManager.GetRealScopeID(tHistory.CDEContextID)))) //GRSI: rare { return(false); } } else { if (TheBaseAssets.MyScopeManager.IsScopingEnabled || !TheBaseAssets.MyServiceHostInfo.AllowUnscopedMesh) { return(false); } } if (!TheCommonUtils.DoesContainLocalhost(tHistory.CDEConnectUrl) && !TheCommonUtils.DoesContainLocalhost(tHistory.CDEConnectWsUrl)) { string strStationRoles = tHistory.FriendlyName; int pos = strStationRoles.LastIndexOf(':') + 1; if (!string.IsNullOrEmpty(strStationRoles) && pos >= 0) { strStationRoles = strStationRoles.Substring(pos, strStationRoles.Length - pos); string[] sRoles = strStationRoles.Split(';'); List <string> discoveredStationRoles = new List <string>(); foreach (string gt in sRoles) { discoveredStationRoles.Add(TheBaseAssets.MyScopeManager.AddScopeID(gt)); } string[] apps = TheCommonUtils.cdeSplit(tHistory.FriendlyName, " at:", false, false); string appName = "Unknown App"; if (apps != null && apps.Length > 0) { appName = apps[0].Trim(); } string tConnectUrl = tHistory.CDEConnectUrl; if (!string.IsNullOrEmpty(tHistory.CDEConnectWsUrl)) { tConnectUrl = tHistory.CDEConnectWsUrl; } TheBaseAssets.MySYSLOG.WriteToLog(112, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("UPnP", $"Compatible Service Found: {tHistory.FriendlyName} {tHistory.Manufacturer} {tHistory.ModelName} {tHistory.ModelNumber} {tHistory.SerialNumber} {tConnectUrl}", eMsgLevel.l7_HostDebugMessage)); eventWSDMatchFound?.Invoke(tHistory.CDENodeID, tConnectUrl, discoveredStationRoles); TheBaseAssets.MySYSLOG.WriteToLog(113, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("UPnP", "New " + appName + " Station found at: " + tConnectUrl, eMsgLevel.l3_ImportantMessage)); } } } return(true); }
public bool RegisterRule(TheThingRule pRule) { if (pRule == null || TheBaseAssets.MyServiceHostInfo.IsCloudService) { return(false); } pRule.GetBaseThing().EngineName = MyBaseEngine.GetEngineName(); if (pRule.TriggerCondition == eRuleTrigger.Set) { pRule.ActionValue = null; } pRule.IsRuleRunning = false; pRule.IsRuleWaiting = true; pRule.IsIllegal = false; pRule.IsTriggerObjectAlive = false; pRule.Parent = MyBaseThing.ID; pRule.GetBaseThing().EngineName = MyBaseEngine.GetEngineName(); TheSystemMessageLog.WriteLog(4445, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(eKnownDeviceTypes.TheThingRule, $"Rule {pRule.FriendlyName} stopped during Register Rule - waiting for startup"), false); TheThing.SetSafePropertyDate(pRule.GetBaseThing(), "LastTriggered", DateTimeOffset.MinValue); TheThing.SetSafePropertyDate(pRule.GetBaseThing(), "LastAction", DateTimeOffset.MinValue); TheThingRegistry.RegisterThing(pRule); return(true); }
bool Connect(TheProcessMessage pMsg) { bool bSuccess = false; try { MyBaseThing.StatusLevel = 4; // ReaderThread will set statuslevel to 1 foreach (var field in MyModFieldStore.TheValues) { var p = MyBaseThing.GetProperty(field.PropertyName, true); p.cdeM = "MODPROP"; p.UnregisterEvent(eThingEvents.PropertyChangedByUX, null); p.RegisterEvent(eThingEvents.PropertyChangedByUX, sinkPChanged); } SetupModbusProperties(true, pMsg); IsConnected = true; MyBaseThing.LastMessage = $"{DateTime.Now} - Device Connecting"; TheBaseAssets.MySYSLOG.WriteToLog(10000, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseThing.EngineName, MyBaseThing.LastMessage, eMsgLevel.l4_Message)); TheCommonUtils.cdeRunAsync($"ModRunThread{MyBaseThing.FriendlyName}", true, (o) => { ReaderThread(); }); bSuccess = true; } catch (Exception e) { MyBaseThing.StatusLevel = 3; string error = $"Error connecting: {e.Message}"; MyBaseThing.LastMessage = $"{DateTimeOffset.Now}: {error}"; TheBaseAssets.MySYSLOG.WriteToLog(10000, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, error, eMsgLevel.l1_Error, e.ToString())); IsConnected = false; } return(bSuccess); }
internal static List <string> GetScopesFromCertificate(X509Certificate2 x509cert, ref string error) { string extensions = ""; List <string> scopeIds = new List <string>(); foreach (X509Extension extension in x509cert.Extensions) { // Create an AsnEncodedData object using the extensions information. AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData); extensions += $"{extension.Oid.FriendlyName} {asndata.Oid.Value} {asndata.RawData.Length} {asndata.Format(false)}"; try { if (extension.Oid.Value == "2.5.29.17") // SAN { string strSANEntry = asndata.Format(true); var lines = strSANEntry.Split(new[] { "\r\n", "\n\r", "\n", "\r" }, StringSplitOptions.None); foreach (var line in lines) { try { if (line.StartsWith("URL=")) { var scopeidUriStr = line.Substring("URL=".Length); var scopeidUri = TheCommonUtils.CUri(scopeidUriStr, true); if (scopeidUri.Scheme.ToLowerInvariant() == "com.c-labs.cdescope") { var scopeid = scopeidUri.Host; scopeIds.Add(scopeid); } } else if (line.StartsWith("URI:")) // TODO check why .Net Core on Linux returns a different prefix (openssl?) - are there platform agnostic ways of doing this? Are there other platforms with different behavior? { var scopeidUriStr = line.Substring("URI:".Length); var scopeidUri = TheCommonUtils.CUri(scopeidUriStr, true); if (scopeidUri.Scheme.ToLowerInvariant() == "com.c-labs.cdescope") { var scopeid = scopeidUri.Host; scopeIds.Add(scopeid); } } } catch (Exception e) { error += e.ToString(); } } } } catch (Exception e) { error += e.ToString(); } //Console.WriteLine("Extension type: {0}", extension.Oid.FriendlyName); //Console.WriteLine("Oid value: {0}", asndata.Oid.Value); //Console.WriteLine("Raw data length: {0} {1}", asndata.RawData.Length, Environment.NewLine); //Console.WriteLine(asndata.Format(true)); } TheBaseAssets.MySYSLOG.WriteToLog(2351, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("HttpService", $"{DateTimeOffset.Now}: {x509cert?.Subject} ScopeIds: {TheCommonUtils.CListToString(scopeIds, ",")} {error} [ Raw: {extensions} ] [Cert: {Convert.ToBase64String(x509cert.RawData)}]")); return(scopeIds); }
private void OnOpcLibraryTrace(object sender, TraceEventArgs e) { try { var mask = OPCTraceMask; if (mask == 0 || ((e.TraceMask & mask) != 0)) { string output; if (e.Arguments != null) { try { output = String.Format(CultureInfo.InvariantCulture, e.Format, e.Arguments); } catch { output = e.Format; } } else { output = e.Format; } if (!string.IsNullOrEmpty(e.Message)) { output = $"{e.Message}: {output}"; } TheBaseAssets.MySYSLOG.WriteToLog(78008, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, $"OPC Trace: {e.TraceMask:X04} - {output}", e.Exception != null ? eMsgLevel.l1_Error : eMsgLevel.l6_Debug, e.Exception?.ToString())); } } catch (Exception ex) { TheBaseAssets.MySYSLOG.WriteToLog(78008, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, $"OPC Client Library Trace: Error processing event", eMsgLevel.l1_Error, ex.ToString())); } }
/// <summary> /// Construtor for network related events /// </summary> /// <param name="onNewInterfaceSink"></param> /// <param name="onDeletedInterfaceSink"></param> public TheNetworkInfo(Action <object, TheIPDef> onNewInterfaceSink, Action <object, TheIPDef> onDeletedInterfaceSink) { TheBaseAssets.MySYSLOG.WriteToLog(138, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("UPnP", "Enter NetworkInfo")); TheQueuedSenderRegistry.RegisterHealthTimer(PollInterface); MyHostName = cdeGetHostName(); TheBaseAssets.MySYSLOG.WriteToLog(139, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("UPnP", "NetworkInfo - HostName :" + MyHostName)); GetLocalIPs(true); if (onNewInterfaceSink != null) { OnNewInterfaceEvent += onNewInterfaceSink; foreach (TheIPDef address in AddressTable.Values) { if (address.IsDnsEnabled) { TheBaseAssets.MySYSLOG.WriteToLog(141, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("UPnP", string.Format("NetworkInfo - Init-Address: {0} of {1}", address, AddressTable.Count), eMsgLevel.l3_ImportantMessage)); OnNewInterfaceEvent?.Invoke(this, address); } } } if (OnInterfaceDisabledEvent != null) { OnInterfaceDisabledEvent += onDeletedInterfaceSink; } TheBaseAssets.MySYSLOG.WriteToLog(144, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("UPnP", "NetworkInfo - All Interfaces Initialized")); }
internal static void ParseUnsubscribe(string pTopics, TheQueuedSender pQSender) { TheBaseAssets.MySYSLOG.WriteToLog(301, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("CoreComm", $"ParseUnsubscribe for Topics={pTopics} of {pQSender.MyTargetNodeChannel?.ToMLString()}", eMsgLevel.l7_HostDebugMessage)); if (string.IsNullOrEmpty(pTopics) || pQSender == null) { return; } bool WasSubscribed = pQSender.Unsubscribe(pTopics); TheBaseAssets.MySYSLOG.WriteToLog(302, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("CoreComm", $"ParseUnsubscribe: Removing Topic Topics={pTopics} of {pQSender.MyTargetNodeChannel?.ToMLString()} Was Sub'ed: {WasSubscribed}", eMsgLevel.l7_HostDebugMessage)); #region DebugInfo if (TheBaseAssets.MyServiceHostInfo.DebugLevel > eDEBUG_LEVELS.FULLVERBOSE) { string tContent = "ParseUnsubscribe - Unsubscribed from: " + pTopics; eMsgLevel tLev = eMsgLevel.l4_Message; if (WasSubscribed) { tLev = eMsgLevel.l2_Warning; tContent = "A Subscription was not Found for: " + pTopics; } TheBaseAssets.MySYSLOG.WriteToLog(304, new TSM("CoreComm", tContent, tLev)); } #endregion }
public void CancelSender(TheThing myBaseThingForLogging, CancellationToken?masterToken = null, bool triggerCancelOnly = false) { StopThingMatcher(); SenderTaskInfo previousTaskInfo = null; if (pendingHistoryLoops.TryGetValue(cdeMID, out previousTaskInfo)) { try { if (!masterToken.HasValue) { masterToken = TheBaseAssets.MasterSwitchCancelationToken; } try { previousTaskInfo.cancelSource.Cancel(); } catch { } if (triggerCancelOnly) { return; } int count = 0; const int timePerLoop = 1000; const int timeout = 1 * 60; while (!masterToken.Value.IsCancellationRequested && previousTaskInfo.task.Status != TaskStatus.Canceled && previousTaskInfo.task.Status != TaskStatus.Faulted && previousTaskInfo.task.Status != TaskStatus.RanToCompletion && count < timeout ) { try { previousTaskInfo.task.Wait(timePerLoop, masterToken.Value); } catch (OperationCanceledException) { } count++; if (count >= timeout) { TheBaseAssets.MySYSLOG.WriteToLog(95275, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(myBaseThingForLogging.EngineName, "Connect", eMsgLevel.l2_Warning, $"Waiting on cancel previous send loop for {myBaseThingForLogging.FriendlyName} - {cdeMID}: timeout after {count * timePerLoop} ms. Retrying.")); count = 0; } } if (count >= timeout) { TheBaseAssets.MySYSLOG.WriteToLog(95275, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(myBaseThingForLogging.EngineName, "Connect", eMsgLevel.l2_Warning, $"Unable to cancel previous send loop for {myBaseThingForLogging.FriendlyName} - {cdeMID}: timeout after {count * timePerLoop} ms")); } previousTaskInfo.cancelSource?.Dispose(); pendingHistoryLoops.RemoveNoCare(cdeMID); } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(95257, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(myBaseThingForLogging.EngineName, "Connect", eMsgLevel.l6_Debug, String.Format("Exception while cancelling previous send loop for thing {0}: {1}", cdeMID, TheCommonUtils.GetAggregateExceptionMessage(e)))); } } }
public void StartDiscoDevice() { if (TheBaseAssets.MyServiceHostInfo.IsIsolated) { return; } TheBaseAssets.MySYSLOG.WriteToLog(100, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("CommonDISCO", "Starting DISCO...", eMsgLevel.l7_HostDebugMessage)); StartUPnPDiscovery(TheBaseAssets.MyServiceHostInfo.MyLiveServices); TheBaseAssets.MySYSLOG.WriteToLog(101, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("CommonDISCO", "...DISCO Started", eMsgLevel.l3_ImportantMessage)); }
void appServer_SessionClosed(WebSocketSession session, CloseReason value) { TheBaseAssets.MySYSLOG.WriteToLog(4343, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheSWSServer", string.Format("Session-Closed: {0} ID:{1}", session.RemoteEndPoint.ToString(), session.SessionID))); TheWSProcessor tPross = null; if (mSessionList.TryRemove(session.SessionID, out tPross)) { if (tPross!=null) tPross.Shutdown(true); } }
internal void ShutDown() { IsActive = false; if (appServer != null) { TheBaseAssets.MySYSLOG.WriteToLog(4378, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("TheWSServer", "Stopping WebSocket-sharp Server!", eMsgLevel.l6_Debug)); appServer.Stop(); appServer = null; } }
internal void RemoveSession(TheSessionState SessionState) { if (SessionState == null) { return; } SessionState.HasExpired = true; SessionState.EndTime = DateTimeOffset.Now; SessionState.ARApp = Guid.Empty; TheBaseAssets.MySYSLOG.WriteToLog(1234, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("SSM", $"Session killed at {TheCommonUtils.GetDateTimeString(DateTimeOffset.Now)} for RemoteAdr: {TheCommonUtils.GetDeviceIDML(SessionState.MyDevice)}", eMsgLevel.l3_ImportantMessage)); TheCommonUtils.cdeRunAsync("RemoveSession", true, (o) => MySessionStates.RemoveAnItem(SessionState, null)); //Do not block the main thread...take your time HasExpired is set :) }
/// <summary> /// Returns true if new subscriptions were added /// </summary> /// <param name="pScopedTopics"></param> /// <param name="OwnedSubs"></param> /// <returns></returns> internal bool Subscribe(string pScopedTopics, bool OwnedSubs = false) { int len = MySubscriptions.Count; CombineSubscriptions(pScopedTopics, out bool WasUpdated, OwnedSubs); if (WasUpdated) //len != MySubscriptions.Count || { TheBaseAssets.MySYSLOG.WriteToLog(296, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("QueuedSender", $"New # of Subscriptions {MySubscriptions?.Count} - Previously {len} for {MyTargetNodeChannel?.ToMLString()}", eMsgLevel.l4_Message)); return(true); } return(false); }
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); } }