// Register for history on our Thing public void ConsumeHistory() { if (testThing != null) { TheHistoryParameters historyParameters = new TheHistoryParameters { Properties = properties, SamplingWindow = TimeSpan.FromMilliseconds(5000), // Every 5 seconds ReportUnchangedProperties = true, ReportInitialValues = true, Persistent = true, MaintainHistoryStore = false, ComputeAvg = true, ComputeMax = true, ComputeMin = true }; historyToken = testThing.RegisterForUpdateHistory(historyParameters); TheQueuedSenderRegistry.RegisterHealthTimer((l) => { // Every 6 seconds, log the aggregated values. Sampling window for historian is 5 seconds. if (l % 6 == 0) { LogChanges(true); } }); } }
/// <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")); }
public override bool Init() { if (!mIsInitStarted) { mIsInitStarted = true; MyBaseThing.StatusLevel = 4; MyBaseThing.LastMessage = "Logger Service has started"; MyBaseThing.RegisterEvent(eEngineEvents.IncomingMessage, HandleMessage); MyBaseEngine.RegisterEvent(eEngineEvents.ThingDeleted, OnThingDeleted); cdeP tP = null; if (TheBaseAssets.MyServiceHostInfo.DisableConsole) { TheThing.SetSafePropertyBool(MyBaseThing, "DisableStandardLog", TheBaseAssets.MyServiceHostInfo.DisableConsole); } else { tP = GetProperty("DisableStandardLog", true); } tP.RegisterEvent(eThingEvents.PropertyChanged, sinkDisableChanged); if (TheCommonUtils.CBool(tP.ToString())) { TheBaseAssets.MyServiceHostInfo.DisableConsole = true; } if (TheBaseAssets.MyServiceHostInfo.UseGELFLoggingFormat) { tP = TheThing.SetSafePropertyBool(MyBaseThing, "UseGELF", TheBaseAssets.MyServiceHostInfo.UseGELFLoggingFormat); } else { tP = GetProperty("UseGELF", true); } tP.RegisterEvent(eThingEvents.PropertyChanged, sinkGELF); if (TheCommonUtils.CBool(tP.ToString())) { TheBaseAssets.MyServiceHostInfo.UseGELFLoggingFormat = true; } bool DoLogKPIs = TheCommonUtils.CBool(TheBaseAssets.MySettings.GetSetting("LogKPIs")); if (DoLogKPIs) { TheThing.SetSafePropertyBool(MyBaseThing, "LogKPIs", true); } TheQueuedSenderRegistry.RegisterHealthTimer(sinkTimer); // If not lengthy initialized you can remove cdeRunasync and call this synchronously TheCommonUtils.cdeRunAsync(MyBaseEngine.GetEngineName() + " Init Services", true, (o) => { // Perform any long-running initialization (i.e. network access, file access) here InitServices(); MyBaseEngine.ProcessInitialized(); //Set the status of the Base Engine according to the status of the Things it manages mIsInitCompleted = true; }); } return(false); }
/// <summary> /// Connect to the Thing /// </summary> public void Connect() { if (MyIsolator == null) { return; } readBytesSec = new PerformanceCounter("Process", "IO Other Bytes/sec", MyIsolator.ProcessName); TheThing.SetSafePropertyBool(MyBaseThing, "IsConnected", true); TheQueuedSenderRegistry.RegisterHealthTimer(sinkTimer); }
public TheHealthMonitor(int pHealthCycle, TheCDMyComputerEngine pEngineName, bool DisableCollection) { if (pEngineName != null) { MyEngineName = pEngineName.GetBaseEngine().GetEngineName(); MyBaseEngine = pEngineName; } if (pHealthCycle > 0) { HealthUpdateCycle = pHealthCycle; } mDisableCollection = DisableCollection; TheBaseEngine.WaitForStorageReadiness(StorageHasStarted, true); InitHealthCollection(); TheQueuedSenderRegistry.RegisterHealthTimer(CheckOnHealthTimer); }
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); }
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 StartUPnPDiscovery(string pLiveEngines) { if (MyUPnPDiscoveryPast != null) { TheBaseAssets.MySYSLOG.WriteToLog(109, new TSM("UPnP", "DISCO aready running!")); return; } MyUPnPDiscoveryPast = new TheStorageMirror <TheUPnPDeviceInfo>(Engines.TheCDEngines.MyIStorageService) { IsRAMStore = true, BlockWriteIfIsolated = true }; MyUPnPDiscoveryPast.SetRecordExpiration(DISCOExpireTime, sinkDeviceExpired); //MyUPnPDiscoveryPast.CacheStoreInterval = 60; //MyUPnPDiscoveryPast.IsStoreIntervalInSeconds = true; //MyUPnPDiscoveryPast.IsCachePersistent = true; MyUPnPDiscoveryPast.InitializeStore(true, true); var tCDEConnectUrl = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false); TheBaseAssets.MySYSLOG.WriteToLog(107, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("UPnP", "Starting Device", eMsgLevel.l3_ImportantMessage)); MyDeviceUPnPInfo = new TheUPnPDeviceInfo() { FriendlyName = TheBaseAssets.MyServiceHostInfo.ApplicationTitle + " at: " + tCDEConnectUrl + " - Services:" + pLiveEngines,// pStationEngines; Manufacturer = TheBaseAssets.MyServiceHostInfo.VendorName, ManufacturerUrl = TheBaseAssets.MyServiceHostInfo.VendorUrl, ModelName = TheBaseAssets.MyServiceHostInfo.ApplicationName, ModelNumber = string.Format("V{0:0.0000}", TheBaseAssets.MyServiceHostInfo.CurrentVersion), SerialNumber = TheBaseAssets.CurrentVersionInfo, PacketString = "", RawMetaXml = "", LocationURL = tCDEConnectUrl, ST = "C-DEngine", CDEConnectUrl = tCDEConnectUrl, CDENodeID = TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID, UUID = TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString(), USN = TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString(), IsCDEngine = true }; if (!TheBaseAssets.MyServiceHostInfo.RequiresConfiguration) { MyDeviceUPnPInfo.CDEContextID = TheBaseAssets.MyScopeManager.GetScrambledScopeID(); //GRSI: rare } if (TheCommonUtils.IsHostADevice()) { MyDeviceUPnPInfo.HasPresentation = false; } else { if (!TheBaseAssets.MyServiceHostInfo.DisableWebSockets && TheBaseAssets.MyServiceHostInfo.MyStationWSPort > 0) { var builder = new UriBuilder(TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false)); builder.Scheme = builder.Scheme == "https" ? "wss" : "ws"; builder.Port = TheBaseAssets.MyServiceHostInfo.MyStationWSPort; MyDeviceUPnPInfo.CDEConnectWsUrl = TheCommonUtils.TruncTrailingSlash(builder.Uri.ToString()); } MyDeviceUPnPInfo.HasPresentation = true; } eventDiscoReady?.Invoke(true); TheQueuedSenderRegistry.RegisterHealthTimer(DoScan4Devices); TheBaseAssets.MySYSLOG.WriteToLog(108, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("UPnP", "DISCO engine ready...")); }
static void Main(string[] args) { Thread.CurrentThread.Name = "Main thread"; // Helps Debugging //SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS! TheScopeManager.SetApplicationID("/cVjzPfjlO;{@QMj:jWpW]HKKEmed[llSlNUAtoE`]G?"); // // Establish service parameters // TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application) { // TODO: Generate host service unique ID cdeMID = TheCommonUtils.CGuid("{AE1F4BBB-B9E3-47D5-B08A-FE71A5697D20}"), // TCP/IP Port Assignments MyStationPort = 8713, // Port for REST access to this node. // If your PC already uses port 80 for another webserver, change this port. // We recommend using Port 8700 and higher for UPnP to work properly. MyStationWSPort = 8714, // Enables WebSockets on the station port. // If UseRandomDeviceID is false, this Value cannot be changed here once the // app runs for the first time. // On Windows 8 and later, MyStationPort and MyStationWSPort // can be the same port if running as Administrator. ISMMainExecutable = "MyTestHost", // Name of the executable (without .exe) ApplicationName = "My-Relay", // Friendly Name of Application Title = "My-Relay (C) 2020 ", // Title of this Host Service ApplicationTitle = "My-Relay Portal", // Title visible in the NMI Portal SiteName = "http://cloud.c-labs.com", // Link to the main Cloud Node of this host. // Not required, for documentation only CurrentVersion = 1.0001, // Service version of this Service. // Increase when you publish a new version so the // online store can display the correct update icon DebugLevel = eDEBUG_LEVELS.ESSENTIALS, // Define a DebugLevel for the SystemLog output. ServiceRoute = "wss://cloud.c-labs.com", // Points at the cloud }; // Generate random Scope ID every time we run. strScope = TheScopeManager.GenerateNewScopeID(); // TIP: instead of creating a new random ID every // time your host starts, you can put a breakpoint in the // next line, record the ID and feed it in the "SetScopeIDFromEasyID". // Or even set a fixed ScopeID here. (FOR TESTING ONLY!!) TheScopeManager.SetScopeIDFromEasyID("1234"); // Set a ScopeID - the security context of this node. // Replace strScope with any random 8 characters or numbers // // Create dictionary to hold configuration settings. // #region Args Parsing ArgList = new Dictionary <string, string>(); for (int i = 0; i < args.Length; i++) { string[] tArgs = args[i].Split('='); if (tArgs.Length == 2) { string key = tArgs[0].ToUpper(); ArgList[key] = tArgs[1]; } } #endregion ArgList["DontVerifyTrust"] = "True"; // When "false", all plugins have to be signed with the // same certificate as the host application or C-DEngine.DLL. // When "true", ignore code signing security check (dev only!) ArgList["UseRandomDeviceID"] = "True"; // When "true", assigns a new device ID everytime // the host starts. No configuration data retained on disk. // When "false", enables persistence between system starts ArgList["ScopeUserLevel"] = "255"; // Set the Scope Access Level // Create a new Base (C-DEngine IoT) Application MyBaseApplication = new TheBaseApplication(); // Start the C-DEngine Host Application. // If a PluginService class is added DIRECTLY to the host project you can // instantiate the Service here. Replace null with "new cdePluginService1()" if (!MyBaseApplication.StartBaseApplication(null, ArgList)) { // If the Application fails to start, quit the app. // StartBaseApplication returns very fast because all // C-DEngine code is running asynchronously return; } // (Optional) Whether to use Universal Plug // and Play (UPnP) to find devices. // MyBaseApplication.MyCommonDisco.RegisterUPnPUID("*", null); // Set up URL for our node. string strStationURL = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false); strStationURL = String.Format("{0}/lnmi", strStationURL); // Set up messaging (for basic sample) TheCDEngines.RegisterPubSubTopic("MyTestEngine2"); // The engine for MyTestHost2 IBaseEngine eng = TheCDEngines.RegisterPubSubTopic("MyTestEngine"); // The engine for THIS host eng.RegisterEvent(eEngineEvents.IncomingMessage, HandleMessage); TheQueuedSenderRegistry.RegisterHealthTimer(SinkTimer); #region Waiting for ESC Key pressed try { // User input loop while (true) { Console.WriteLine("\r\nStation URL: " + strStationURL); Console.WriteLine("\r\nScope ID: " + strScope); Console.WriteLine("\r\n[Esc] key to quit. 'B' (or 'b') to launch browser"); // Loop until (1) C-DEngine master switch, or (2) Keyboard input while (TheBaseAssets.MasterSwitch && Console.KeyAvailable == false) // Console.KeyAvailable throws exception in Docker { Thread.Sleep(250); } // Check C-DEngine master switch. if (!TheBaseAssets.MasterSwitch) { // Exit user input loop. break; } ConsoleKeyInfo key = Console.ReadKey(); if (key.Key == ConsoleKey.Escape) { break; } if (key.KeyChar == 'b' || key.KeyChar == 'B') { try { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { strStationURL = strStationURL.Replace("&", "^&"); Process.Start(new ProcessStartInfo("cmd.exe", $"/c start {strStationURL}") { CreateNoWindow = true }); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { System.Diagnostics.Process.Start("xdg-open", strStationURL); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { System.Diagnostics.Process.Start("open", strStationURL); } else { Console.WriteLine($"Error launching browser for URL {strStationURL}"); } } catch (Exception e) { Console.WriteLine($"Error launching browser for URL {strStationURL}"); Console.WriteLine($"Exception details: {e.ToString()}"); } } } // while (true) } catch (InvalidOperationException) { TheBaseAssets.MasterSwitchCancelationToken.WaitHandle.WaitOne(); } MyBaseApplication.Shutdown(true); #endregion }