/// <summary> /// Initializes the asset database. Similar to <see cref="Game.InitializeAssetDatabase"/>, but accessible without using internals. /// </summary> private static void InitializeAssetDatabase() { // Create and mount database file system var objDatabase = new ObjectDatabase("/data/db", "index", "/local/db"); // Only set a mount path if not mounted already var mountPath = VirtualFileSystem.ResolveProviderUnsafe("/asset", true).Provider == null ? "/asset" : null; var databaseFileProvider = new DatabaseFileProvider(objDatabase, mountPath); AssetManager.GetFileProvider = () => databaseFileProvider; }
public override void OnInspectorGUI() { myTarget = (ObjectDatabase)target; DrawDefaultInspector(); if (GUILayout.Button("Save")) Save(); if (GUILayout.Button("Load")) Load(); }
public void Init() { // Create and mount database file system var objDatabase = ObjectDatabase.CreateDefaultDatabase(); var databaseFileProvider = new DatabaseFileProvider(objDatabase); ContentManager.GetFileProvider = () => databaseFileProvider; shaderMixinParser = new ShaderMixinParser(ContentManager.FileProvider); shaderMixinParser.SourceManager.LookupDirectoryList.Add("/shaders"); }
public void RpcMeleeAttack(uint entityID, uint targetEntityID, short weaponID) { Entity entity = ObjectDatabase.GetEntity(entityID); Weapon weapon = ObjectDatabase.GetWeapon(weaponID); Entity targetEntity = ObjectDatabase.GetEntity(targetEntityID); RotateTowards(targetEntity.transform.position); entity.SetTrigger(weapon.animationTrigger); entity.BlockMovement(weapon.cantMoveTime); }
private void Init() { // Create and mount database file system var objDatabase = ObjectDatabase.CreateDefaultDatabase(); var databaseFileProvider = new DatabaseFileProvider(objDatabase); manager = new ShaderSourceManager(databaseFileProvider); manager.LookupDirectoryList.Add("shaders"); logger = new Stride.Core.Shaders.Utility.LoggerResult(); loader = new ShaderLoader(manager); }
/// <summary> /// Reparents all objects in the allObjects treeview to the correct parent. /// </summary> private void RebuildAllObjectsParents() { foreach (TreeNode node in m_treeNodes.Values) { ProjectObject nodeObject; if (ObjectDatabase.TryGetObject(node.Name, out nodeObject)) { AddObject(nodeObject); } } }
public static void Main5() { // Create and mount database file system var objDatabase = ObjectDatabase.CreateDefaultDatabase(); var assetIndexMap = ContentIndexMap.Load(VirtualFileSystem.ApplicationDatabaseIndexPath); var databaseFileProvider = new DatabaseFileProvider(assetIndexMap, objDatabase); var test = new TestGenericClass(); test.Run(); }
public void Init() { // Create and mount database file system var objDatabase = new ObjectDatabase("/data/db", "index", "/local/db"); var databaseFileProvider = new DatabaseFileProvider(objDatabase); AssetManager.GetFileProvider = () => databaseFileProvider; shaderMixinParser = new ShaderMixinParser(); shaderMixinParser.SourceManager.LookupDirectoryList.Add("/shaders"); }
public void AttemptingToAccessDisposedObjectDatabaseObjecetThrows() { ObjectDatabaseObject obj; using (Repository repo = SandboxRepository("testrepo")) using (ObjectDatabase odb = repo.ObjectDatabase) using (obj = odb.Read(new ObjectId("a71586c1dfe8a71c6cbf6c129f404c5642ff31bd"))) { } Assert.Throws <ObjectDisposedException>(() => obj.Id); }
public void Init() { // Create and mount database file system var objDatabase = ObjectDatabase.CreateDefaultDatabase(); var databaseFileProvider = new DatabaseFileProvider(objDatabase); AssetManager.GetFileProvider = () => databaseFileProvider; sourceManager = new ShaderSourceManager(); sourceManager.LookupDirectoryList.Add(@"shaders"); shaderLoader = new ShaderLoader(sourceManager); }
public static bool OpenEditor(int instanceId, int line) { ObjectDatabase obj = EditorUtility.InstanceIDToObject(instanceId) as ObjectDatabase; if (obj != null) { ObjectDatabaseEditorWindow.OpenWindow(obj); return(true); } return(false); }
private void Init() { // Create and mount database file system var objDatabase = ObjectDatabase.CreateDefaultDatabase(); var databaseFileProvider = new DatabaseFileProvider(objDatabase); Compiler = new EffectCompiler(databaseFileProvider); Compiler.SourceDirectories.Add("shaders"); MixinParameters = new CompilerParameters(); MixinParameters.EffectParameters.Platform = GraphicsPlatform.Direct3D11; MixinParameters.EffectParameters.Profile = GraphicsProfile.Level_11_0; ResultLogger = new LoggerResult(); }
public void ServerSetTarget(Transform target, float speed, int damage, uint attackerID, uint victimID) { isServer = true; this.target = target; this.speed = speed; this.damage = damage; this.attackerID = attackerID; this.victimID = victimID; attackerName = ObjectDatabase.GetEntity(attackerID).Name; }
public void Init() { // Create and mount database file system var objDatabase = ObjectDatabase.CreateDefaultDatabase(); var databaseFileProvider = new DatabaseFileProvider(objDatabase); ContentManager.GetFileProvider = () => databaseFileProvider; manager = new ShaderSourceManager(); manager.LookupDirectoryList.Add("shaders"); logger = new SiliconStudio.Shaders.Utility.LoggerResult(); loader = new ShaderLoader(manager); }
public static void Main5() { // Create and mount database file system var objDatabase = new ObjectDatabase("/data/db"); var assetIndexMap = AssetIndexMap.Load(); var databaseFileProvider = new DatabaseFileProvider(assetIndexMap, objDatabase); AssetManager.GetFileProvider = () => databaseFileProvider; var test = new TestGenericClass(); test.Run(); }
public override string ToString() { ProjectObject documentAsset; if (ObjectDatabase.TryGetObject(DocumentId, out documentAsset)) { return(documentAsset.ToString()); } else { return(DocumentId); } }
public void Init() { // Create and mount database file system var objDatabase = new ObjectDatabase("/data/db", "index", "/local/db"); var databaseFileProvider = new DatabaseFileProvider(objDatabase); AssetManager.GetFileProvider = () => databaseFileProvider; manager = new ShaderSourceManager(); manager.LookupDirectoryList.Add("shaders"); logger = new SiliconStudio.Shaders.Utility.LoggerResult(); loader = new ShaderLoader(manager); }
private void OnAllObjectsTreeViewSelectionChanged(object sender, TreeViewEventArgs e) { if (allObjectsTreeView.SelectedNode == null) { relationshipsListView.Items.Clear(); return; } TreeNode selectedItem = allObjectsTreeView.SelectedNode; //HACK: ensure that the selection sticks when the element doesn't have focus if (m_lastSelectedTreeNode != null) { m_lastSelectedTreeNode.BackColor = SystemColors.Window; m_lastSelectedTreeNode.ForeColor = SystemColors.WindowText; } m_lastSelectedTreeNode = selectedItem; selectedItem.BackColor = SystemColors.ActiveBorder; selectedItem.ForeColor = SystemColors.HighlightText; ProjectObject selectedObject; if (ObjectDatabase.TryGetObject(selectedItem.Name, out selectedObject)) { // load the object into the inspect panel UnityObjectKey unityObjectKey; unityObjectKey = new UnityObjectKey(selectedObject.UniqueId); selectedObjectGuidTextBox.Text = unityObjectKey.AssetGuid.ToString(); selectedObjectFileIdTextBox.Text = unityObjectKey.FileId.ToString(); selectedObjectFilePathTextBox.Text = selectedObject.GetFilePath(); projectObjectTypeTextBox.Text = selectedObject.GetType().Name; if (selectedObject.ParseError != null) { viewErrorButton.Visible = true; toolTip.SetToolTip(viewErrorButton, selectedObject.ParseError.ToString()); } else { viewErrorButton.Visible = false; } } else { selectedObjectGuidTextBox.Text = ""; selectedObjectFileIdTextBox.Text = ""; selectedObjectFilePathTextBox.Text = ""; projectObjectTypeTextBox.Text = ""; } ReloadRelationships(); }
public void CanRead(string id, string contents, long size, ObjectType type) { using (Repository repo = SandboxRepository("testrepo")) using (ObjectDatabase odb = repo.ObjectDatabase) using (ObjectDatabaseObject obj = odb.Read(new ObjectId(id))) { var contentBytes = Encoding.UTF8.GetBytes(contents); Assert.Equal(id, obj.Id.ToString()); Assert.Equal(type, obj.Type); Assert.Equal(size, obj.Size); Assert.True(new ReadOnlySpan <byte>(contentBytes).SequenceEqual(obj.Data)); } }
/// <summary> /// Opens the selected object in the allObjects view in explorer. /// </summary> private void openInExplorerToolStripMenuItem_Click(object sender, EventArgs e) { ProjectObject projectObject; if (allObjectsTreeView.SelectedNode != null && ObjectDatabase.TryGetObject(allObjectsTreeView.SelectedNode.Name, out projectObject)) { string objectPath = projectObject.GetFilePath(); if (!string.IsNullOrEmpty(objectPath)) { Process.Start("explorer.exe", "/select,\"" + objectPath + "\""); } } }
public Commit LoadParent() { if (ParentKey == null) { return(null); } if (_parent == null) { _parent = ObjectDatabase.RetrieveCommit(ParentKey); } return(_parent); }
public static IObjectDatabase TemporarySQLiteDB() { if (File.Exists(SQLiteDBPath)) { File.Delete(SQLiteDBPath); } IObjectDatabase sqliteDB; var configDBConnectionString = $"Data Source={SQLiteDBPath};Version=3;Pooling=False;Cache Size=1073741824;Journal Mode=Off;Synchronous=Off;Foreign Keys=True;Default Timeout=60"; sqliteDB = ObjectDatabase.GetObjectDatabase(ConnectionType.DATABASE_SQLITE, configDBConnectionString); return(sqliteDB); }
public override void OnLoaded() { db = DB.GetDatabaseProxy("TheController"); mailSettings = MailSettings.LoadSettings(); if (mailSettings == null) { mailSettings = new MailSettings(); mailSettings.From = "Enter address of sender here."; mailSettings.Recipient = "Enter recipient of alarm mails here."; mailSettings.SaveNew(); } }
public void ChangeCwdTest() { Directory.CreateDirectory("dir"); CreateFile("dir/a.txt", "a content"); Directory.SetCurrentDirectory("dir"); Blob blob = new Blob(new RelativePath("a.txt")); HashKey blobKey = ObjectDatabase.Store(blob); Blob retrievedBlob = ObjectDatabase.RetrieveBlob(blobKey); Assert.Equal(retrievedBlob, blob); }
/// <summary> /// Opens the selected ojbect in the allObjects view in the default editor. /// </summary> private void editToolStripMenuItem_Click(object sender, EventArgs e) { ProjectObject projectObject; if (allObjectsTreeView.SelectedNode != null && ObjectDatabase.TryGetObject(allObjectsTreeView.SelectedNode.Name, out projectObject)) { string objectPath = projectObject.GetFilePath(); if (!string.IsNullOrEmpty(objectPath)) { Process.Start(objectPath); } } }
public void Init() { using (var profile = Profiler.Begin(GameProfilingKeys.ObjectDatabaseInitialize)) { // Create and mount database file system var objDatabase = new ObjectDatabase("/data/db", "index", "/local/db"); var databaseFileProvider = new DatabaseFileProvider(objDatabase); AssetManager.GetFileProvider = () => databaseFileProvider; } sourceManager = new ShaderSourceManager(); sourceManager.LookupDirectoryList.Add(@"shaders"); shaderLoader = new ShaderLoader(sourceManager); }
internal static DatabaseFileProvider InitializeAssetDatabase() { using (Profiler.Begin(GameProfilingKeys.ObjectDatabaseInitialize)) { // Create and mount database file system var objDatabase = ObjectDatabase.CreateDefaultDatabase(); // Only set a mount path if not mounted already var mountPath = VirtualFileSystem.ResolveProviderUnsafe("/asset", true).Provider == null ? "/asset" : null; var result = new DatabaseFileProvider(objDatabase, mountPath); return(result); } }
private void additionalHaves(ObjectDatabase db) { AlternateRepositoryDatabase b = (db as AlternateRepositoryDatabase); if (b != null) { additionalHaves(b.getRepository()); } foreach (ObjectDatabase alt in db.getAlternates()) { additionalHaves(alt); } }
public void CanStopObjectIteration() { int count = 0; using (Repository repo = SandboxRepository("testrepo")) using (ObjectDatabase odb = repo.ObjectDatabase) { odb.ForEachObject((id) => { return((++count == 5) ? false : true); }); } Assert.Equal(5, count); }
public static void Main() { using (var profile = Profiler.Begin(GameProfilingKeys.ObjectDatabaseInitialize)) { // Create and mount database file system var objDatabase = new ObjectDatabase("/data/db"); var assetIndexMap = AssetIndexMap.Load(); var databaseFileProvider = new DatabaseFileProvider(assetIndexMap, objDatabase); AssetManager.GetFileProvider = () => databaseFileProvider; } var test = new TestGenericClass(); test.Run(); }
public void CanIterateObjects() { int count = 0; using (Repository repo = SandboxRepository("testrepo")) using (ObjectDatabase odb = repo.ObjectDatabase) { odb.ForEachObject((id) => { count++; return(true); }); } Assert.Equal(1703, count); }
public static void Main (string[] args) { Log.Register (new ConsoleOutEventLog (80)); Log.Information ("Initializing application..."); HttpSocketClient.RegisterHttpProxyUse (false, false); // Don't look for proxies. Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => { e.Cancel = true; executing = false; }; // Object database setup DB.BackupConnectionString = "Data Source=controller.db;Version=3;"; DB.BackupProviderName = "Clayster.Library.Data.Providers.SQLiteServer.SQLiteServerProvider"; db = DB.GetDatabaseProxy ("TheController"); // Mail setup mailSettings = MailSettings.LoadSettings (); if (mailSettings == null) { mailSettings = new MailSettings (); mailSettings.Host = "Enter mailserver SMTP host name here."; mailSettings.Port = 25; mailSettings.Ssl = false; mailSettings.From = "Enter address of sender here."; mailSettings.User = "******"; mailSettings.Password = "******"; mailSettings.Recipient = "Enter recipient of alarm mails here."; mailSettings.SaveNew (); } SmtpOutbox.Host = mailSettings.Host; SmtpOutbox.Port = mailSettings.Port; SmtpOutbox.Ssl = mailSettings.Ssl; SmtpOutbox.From = mailSettings.From; SmtpOutbox.User = mailSettings.User; SmtpOutbox.Password = mailSettings.Password; SmtpOutbox.OutboxPath = "MailOutbox"; SmtpOutbox.Start (Directory.GetCurrentDirectory ()); // UPnP Interface upnpServer = new HttpServer (8080, 10, true, true, 1); Log.Information ("UPnP Server receiving requests on port " + upnpServer.Port.ToString ()); ssdpClient = new SsdpClient (upnpServer, 10, true, true, false, false, false, 30); stillImageCameras = new Dictionary<string, IUPnPService> (); subscriptions = new SortedDictionary<DateTime, Subscription> (); stateVariables = new Dictionary<string, Dictionary<string, string>> (); events = new UPnPEvents ("/events"); upnpServer.Register (events); ssdpClient.OnUpdated += NetworkUpdated; events.OnEventsReceived += EventsReceived; // Main loop Log.Information ("Initialization complete. Application started..."); try { #if USE_HTTP MonitorHttp (); #elif USE_COAP MonitorCoap (); #elif USE_MQTT MonitorMqtt (); #endif } catch (Exception ex) { Log.Exception (ex); } finally { Log.Information ("Terminating application."); Log.Flush (); Log.Terminate (); SmtpOutbox.Terminate (); ssdpClient.Dispose (); upnpServer.Dispose (); } }
private void additionalHaves(ObjectDatabase db) { if (db is AlternateRepositoryDatabase) { additionalHaves(((AlternateRepositoryDatabase)db).getRepository()); } foreach (ObjectDatabase alt in db.getAlternates()) { additionalHaves(alt); } }
public static int Main (string[] args) { Log.Register (new ConsoleOutEventLog (80)); Log.Information ("Initializing application..."); HttpSocketClient.RegisterHttpProxyUse (false, false); // Don't look for proxies. DB.BackupConnectionString = "Data Source=actuator.db;Version=3;"; DB.BackupProviderName = "Clayster.Library.Data.Providers.SQLiteServer.SQLiteServerProvider"; db = DB.GetDatabaseProxy ("TheActuator"); Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => { e.Cancel = true; executionLed.Low (); }; // HTTP Interface HttpServer HttpServer = new HttpServer (80, 10, true, true, 1); int i; Log.Information ("HTTP Server receiving requests on port " + HttpServer.Port.ToString ()); HttpServer.RegisterAuthenticationMethod (new DigestAuthentication ("The Actuator Realm", GetDigestUserPasswordHash)); HttpServer.RegisterAuthenticationMethod (new SessionAuthentication ()); credentials = LoginCredentials.LoadCredentials (); if (credentials == null) { credentials = new LoginCredentials (); credentials.UserName = "******"; credentials.PasswordHash = CalcHash ("Admin", "Password"); credentials.SaveNew (); } state = State.LoadState (); if (state == null) { state = new State (); state.SaveNew (); } else { for (i = 0; i < 8; i++) digitalOutputs [i].Value = state.GetDO (i + 1); if (state.Alarm) AlarmOn (); else AlarmOff (); } WebServiceAPI wsApi; HttpServer.Register ("/", HttpGetRoot, HttpPostRoot, false); // Synchronous, no authentication HttpServer.Register ("/credentials", HttpGetCredentials, HttpPostCredentials, false); // Synchronous, no authentication HttpServer.Register ("/set", HttpGetSet, HttpPostSet, true); // Synchronous, http authentication HttpServer.Register ("/xml", HttpGetXml, true); // Synchronous, http authentication HttpServer.Register ("/json", HttpGetJson, true); // Synchronous, http authentication HttpServer.Register ("/turtle", HttpGetTurtle, true); // Synchronous, http authentication HttpServer.Register ("/rdf", HttpGetRdf, true); // Synchronous, http authentication HttpServer.Register (wsApi = new WebServiceAPI (), true); // HTTPS interface // Certificate must be a valid P12 (PFX) certificate file containing a private key. // X509Certificate2 Certificate = new X509Certificate2 ("Certificate.pfx", "PASSWORD"); // HttpServer HttpsServer = new HttpServer (443, 10, true, true, 1, true, false, Certificate); // // HttpsServer.RegisterAuthenticationMethod (new DigestAuthentication ("The Actuator Realm", GetDigestUserPasswordHash)); // // foreach (IHttpServerResource Resource in HttpServer.GetResources()) // HttpsServer.Register (Resource); // // Log.Information ("HTTPS Server receiving requests on port " + HttpsServer.Port.ToString ()); // CoAP Interface CoapEndpoint CoapEndpoint = new CoapEndpoint (); Log.Information ("CoAP endpoint receiving requests on port " + CoapEndpoint.Port.ToString ()); //CoapEndpoint.RegisterLineListener (new ConsoleOutLineListenerSink (BinaryFormat.Hexadecimal, true)); for (i = 1; i <= 8; i++) { CoapEndpoint.RegisterResource ("do" + i.ToString () + "/txt", "Digital Output " + i.ToString () + ", as text.", CoapBlockSize.BlockLimit_64Bytes, false, 30, false, CoapGetDigitalOutputTxt, CoapSetDigitalOutputTxt); } CoapEndpoint.RegisterResource ("do/txt", "Digital Outputs, as a number 0-255 as text.", CoapBlockSize.BlockLimit_64Bytes, false, 30, false, CoapGetDigitalOutputsTxt, CoapSetDigitalOutputsTxt); CoapEndpoint.RegisterResource ("alarm/txt", "Alarm Output " + i.ToString () + ", as text.", CoapBlockSize.BlockLimit_64Bytes, false, 30, false, CoapGetAlarmOutputTxt, CoapSetAlarmOutputTxt); foreach (CoapBlockSize BlockSize in Enum.GetValues(typeof(CoapBlockSize))) { if (BlockSize == CoapBlockSize.BlockLimit_Datagram) continue; string Bytes = (1 << (4 + (int)BlockSize)).ToString (); CoapEndpoint.RegisterResource ("xml/" + Bytes, "Complete sensor readout, in XML. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetXml); CoapEndpoint.RegisterResource ("json/" + Bytes, "Complete sensor readout, in JSON. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetJson); CoapEndpoint.RegisterResource ("turtle/" + Bytes, "Complete sensor readout, in TURTLE. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetTurtle); CoapEndpoint.RegisterResource ("rdf/" + Bytes, "Complete sensor readout, in RDF. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetRdf); } // MQTT MqttClient MqttClient = new MqttClient ("iot.eclipse.org", MqttClient.DefaultPort, "LearningIoTActuator", string.Empty, false); //MqttClient.RegisterLineListener (new ConsoleOutLineListenerSink (BinaryFormat.Hexadecimal)); MqttClient.Open (); MqttClient.CONNECT (20, true); MqttClient.PUBLISH ("Clayster/LearningIoT/Actuator/ao", state.Alarm ? "1" : "0", MqttQoS.QoS1_Acknowledged, true); MqttClient.PUBLISH ("Clayster/LearningIoT/Actuator/do", wsApi.GetDigitalOutputs ().ToString (), MqttQoS.QoS1_Acknowledged, true); for (i = 1; i <= 8; i++) MqttClient.PUBLISH ("Clayster/LearningIoT/Actuator/do" + i.ToString (), wsApi.GetDigitalOutput (i) ? "1" : "0", MqttQoS.QoS1_Acknowledged, true); MqttClient.SUBSCRIBE (new KeyValuePair<string, MqttQoS> ("Clayster/LearningIoT/Actuator/#", MqttQoS.QoS1_Acknowledged)); MqttClient.OnDataPublished += OnMqttDataPublished; Log.Information ("Receiving commands via MQTT from Clayster/LearningIoT/Actuator @ ", EventLevel.Minor, MqttClient.Host + ":" + MqttClient.PortNumber.ToString ()); // Main loop Log.Information ("Initialization complete. Application started..."); try { while (executionLed.Value) { System.Threading.Thread.Sleep (1000); RemoveOldSessions (); } } catch (Exception ex) { Log.Exception (ex); executionLed.Low (); } finally { Log.Information ("Terminating application."); Log.Flush (); Log.Terminate (); HttpServer.Dispose (); //HttpsServer.Dispose (); if (MqttClient != null) MqttClient.Dispose (); executionLed.Dispose (); foreach (DigitalOutput Output in digitalOutputs) Output.Dispose (); if (alarmThread != null) { alarmThread.Abort (); alarmThread = null; } } return 0; }
public static int Main (string[] args) { Log.Register (new ConsoleOutEventLog (80)); Log.Information ("Initializing application..."); HttpSocketClient.RegisterHttpProxyUse (false, false); // Don't look for proxies. DB.BackupConnectionString = "Data Source=sensor.db;Version=3;"; DB.BackupProviderName = "Clayster.Library.Data.Providers.SQLiteServer.SQLiteServerProvider"; db = DB.GetDatabaseProxy ("TheSensor"); Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => { e.Cancel = true; executionLed.Low (); }; // Initializing hardware and retrieving current sensor values try { tmp102.Configure (false, TexasInstrumentsTMP102.FaultQueue.ConsecutiveFaults_6, TexasInstrumentsTMP102.AlertPolarity.AlertActiveLow, TexasInstrumentsTMP102.ThermostatMode.ComparatorMode, false, TexasInstrumentsTMP102.ConversionRate.Hz_1, false); temp = (short)tmp102.ReadTemperatureRegister (); temperatureC = temp / 256.0; for (int i = 0; i < 10; i++) tempAvgWindow [i] = temp; sumTemp = temp * 10; } catch (Exception ex) { Log.Exception (ex); sumTemp = 0; temperatureC = 0; errorLed.High (); } try { adc.Configure (true, false, false, false, false, false); light = adc.ReadRegistersBinary () [0]; lightPercent = (100.0 * light) / 0x0fff; for (int i = 0; i < 10; i++) lightAvgWindow [i] = light; sumLight = light * 10; } catch (Exception ex) { Log.Exception (ex); sumLight = 0; lightPercent = 0; errorLed.High (); } // Loading historical Sensor Values Log.Information ("Loading Minute Values."); perMinute.AddRange (Record.LoadRecords (Rank.Minute)); Log.Information ("Loading Hour Values."); perHour.AddRange (Record.LoadRecords (Rank.Hour)); Log.Information ("Loading Day Values."); perDay.AddRange (Record.LoadRecords (Rank.Day)); Log.Information ("Loading Month Values."); perMonth.AddRange (Record.LoadRecords (Rank.Month)); // Resuming average calculations int Pos = perSecond.Count; DateTime CurrentTime = DateTime.Now; DateTime Timestamp; while (Pos-- > 0) { Record Rec = perSecond [Pos]; Timestamp = Rec.Timestamp; if (Timestamp.Minute == CurrentTime.Minute && Timestamp.Hour == CurrentTime.Hour && Timestamp.Date == CurrentTime.Date) { sumSeconds += Rec; nrSeconds++; } else break; } Pos = perMinute.Count; while (Pos-- > 0) { Record Rec = perMinute [Pos]; Timestamp = Rec.Timestamp; if (Timestamp.Hour == CurrentTime.Hour && Timestamp.Date == CurrentTime.Date) { sumMinutes += Rec; nrMinutes++; } else break; } Pos = perHour.Count; while (Pos-- > 0) { Record Rec = perHour [Pos]; Timestamp = Rec.Timestamp; if (Timestamp.Date == CurrentTime.Date) { sumHours += Rec; nrHours++; } else break; } Pos = perDay.Count; while (Pos-- > 0) { Record Rec = perDay [Pos]; Timestamp = Rec.Timestamp; if (Timestamp.Month == CurrentTime.Month && Timestamp.Year == CurrentTime.Year) { sumDays += Rec; nrDays++; } else break; } // Sampling of new Sensor Values Timer Timer = new Timer (SampleSensorValues, null, 1000 - DateTime.Now.Millisecond, 1000); // Every second. // HTTP Interface HttpServer HttpServer = new HttpServer (80, 10, true, true, 1); Log.Information ("HTTP Server receiving requests on port " + HttpServer.Port.ToString ()); HttpServer.RegisterAuthenticationMethod (new DigestAuthentication ("The Sensor Realm", GetDigestUserPasswordHash)); HttpServer.RegisterAuthenticationMethod (new SessionAuthentication ()); credentials = LoginCredentials.LoadCredentials (); if (credentials == null) { credentials = new LoginCredentials (); credentials.UserName = "******"; credentials.PasswordHash = CalcHash ("Admin", "Password"); credentials.SaveNew (); } HttpServer.Register ("/", HttpGetRoot, HttpPostRoot, false); // Synchronous, no authentication HttpServer.Register ("/html", HttpGetHtml, false); // Synchronous, no authentication HttpServer.Register ("/historygraph", HttpGetHistoryGraph, false); // Synchronous, no authentication HttpServer.Register ("/credentials", HttpGetCredentials, HttpPostCredentials, false); // Synchronous, no authentication HttpServer.Register ("/xml", HttpGetXml, true); // Synchronous, http authentication HttpServer.Register ("/json", HttpGetJson, true); // Synchronous, http authentication HttpServer.Register ("/turtle", HttpGetTurtle, true); // Synchronous, http authentication HttpServer.Register ("/rdf", HttpGetRdf, true); // Synchronous, http authentication HttpServer.Register ("/event/xml", HttpGetEventXml, true, false); // Asynchronous, http authentication HttpServer.Register ("/event/json", HttpGetEventJson, true, false); // Asynchronous, http authentication HttpServer.Register ("/event/turtle", HttpGetEventTurtle, true, false); // Asynchronous, http authentication HttpServer.Register ("/event/rdf", HttpGetEventRdf, true, false); // Asynchronous, http authentication // HTTPS interface // Certificate must be a valid P12 (PFX) certificate file containing a private key. // X509Certificate2 Certificate = new X509Certificate2 ("Certificate.pfx", "PASSWORD"); // HttpServer HttpsServer = new HttpServer (443, 10, true, true, 1, true, false, Certificate); // // HttpsServer.RegisterAuthenticationMethod (new DigestAuthentication ("The Sensor Realm", GetDigestUserPasswordHash)); // HttpsServer.RegisterAuthenticationMethod (new SessionAuthentication ()); // // foreach (IHttpServerResource Resource in HttpServer.GetResources()) // HttpsServer.Register (Resource); // // Log.Information ("HTTPS Server receiving requests on port " + HttpsServer.Port.ToString ()); // CoAP Interface CoapEndpoint CoapEndpoint = new CoapEndpoint (); Log.Information ("CoAP endpoint receiving requests on port " + CoapEndpoint.Port.ToString ()); //CoapEndpoint.RegisterLineListener (new ConsoleOutLineListenerSink (BinaryFormat.Hexadecimal, true)); CoapEndpoint.RegisterResource ("temp/txt", "Current Temperature, as text.", CoapBlockSize.BlockLimit_64Bytes, false, 30, true, (Request, Payload) => { return FieldNumeric.Format (temperatureC, "C", 1); }); motionTxt = CoapEndpoint.RegisterResource ("motion/txt", "Motion detection, as text.", CoapBlockSize.BlockLimit_64Bytes, false, 10, true, (Request, Payload) => { return motionDetected ? "1" : "0"; }); CoapEndpoint.RegisterResource ("light/txt", "Current Light Density, as text.", CoapBlockSize.BlockLimit_64Bytes, false, 2, true, (Request, Payload) => { return FieldNumeric.Format (lightPercent, "%", 1); }); foreach (CoapBlockSize BlockSize in Enum.GetValues(typeof(CoapBlockSize))) { if (BlockSize == CoapBlockSize.BlockLimit_Datagram) continue; string Bytes = (1 << (4 + (int)BlockSize)).ToString (); CoapEndpoint.RegisterResource ("xml/" + Bytes, "Complete sensor readout, in XML. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetXml); CoapEndpoint.RegisterResource ("json/" + Bytes, "Complete sensor readout, in JSON. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetJson); CoapEndpoint.RegisterResource ("turtle/" + Bytes, "Complete sensor readout, in TURTLE. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetTurtle); CoapEndpoint.RegisterResource ("rdf/" + Bytes, "Complete sensor readout, in RDF. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetRdf); } // MQTT mqttThread = new Thread (MqttThread); mqttThread.Name = "MQTT"; mqttThread.Priority = ThreadPriority.BelowNormal; mqttThread.Start (); // Main loop Log.Information ("Initialization complete. Application started..."); try { while (executionLed.Value) { System.Threading.Thread.Sleep (1000); } } catch (Exception ex) { Log.Exception (ex); executionLed.Low (); } finally { Log.Information ("Terminating application."); Log.Flush (); Log.Terminate (); Timer.Dispose (); HttpServer.Dispose (); //HttpsServer.Dispose (); CoapEndpoint.Dispose (); if (mqttThread != null) { mqttThread.Abort (); mqttThread = null; } executionLed.Dispose (); measurementLed.Dispose (); errorLed.Dispose (); networkLed.Dispose (); motion.Dispose (); i2cBus.Dispose (); } return 0; }
public static int Main (string[] args) { Log.Register (new ConsoleOutEventLog (80)); Log.Information ("Initializing application..."); HttpSocketClient.RegisterHttpProxyUse (false, false); // Don't look for proxies. DB.BackupConnectionString = "Data Source=actuator.db;Version=3;"; DB.BackupProviderName = "Clayster.Library.Data.Providers.SQLiteServer.SQLiteServerProvider"; db = DB.GetDatabaseProxy ("TheActuator"); Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => { e.Cancel = true; executionLed.Low (); }; // HTTP Interface HttpServer HttpServer = new HttpServer (80, 10, true, true, 1); Log.Information ("HTTP Server receiving requests on port " + HttpServer.Port.ToString ()); HttpServer.RegisterAuthenticationMethod (new DigestAuthentication ("The Actuator Realm", GetDigestUserPasswordHash)); HttpServer.RegisterAuthenticationMethod (new SessionAuthentication ()); credentials = LoginCredentials.LoadCredentials (); if (credentials == null) { credentials = new LoginCredentials (); credentials.UserName = "******"; credentials.PasswordHash = CalcHash ("Admin", "Password"); credentials.SaveNew (); } state = State.LoadState (); if (state == null) { state = new State (); state.SaveNew (); } else { for (int i = 0; i < 8; i++) digitalOutputs [i].Value = state.GetDO (i + 1); if (state.Alarm) AlarmOn (); else AlarmOff (); } HttpServer.Register ("/", HttpGetRoot, HttpPostRoot, false); // Synchronous, no authentication HttpServer.Register ("/credentials", HttpGetCredentials, HttpPostCredentials, false); // Synchronous, no authentication HttpServer.Register ("/set", HttpGetSet, HttpPostSet, true); // Synchronous, http authentication HttpServer.Register ("/xml", HttpGetXml, true); // Synchronous, http authentication HttpServer.Register ("/json", HttpGetJson, true); // Synchronous, http authentication HttpServer.Register ("/turtle", HttpGetTurtle, true); // Synchronous, http authentication HttpServer.Register ("/rdf", HttpGetRdf, true); // Synchronous, http authentication HttpServer.Register (new WebServiceAPI (), true); // HTTPS interface // Certificate must be a valid P12 (PFX) certificate file containing a private key. // X509Certificate2 Certificate = new X509Certificate2 ("Certificate.pfx", "PASSWORD"); // HttpServer HttpsServer = new HttpServer (443, 10, true, true, 1, true, false, Certificate); // // HttpsServer.RegisterAuthenticationMethod (new DigestAuthentication ("The Actuator Realm", GetDigestUserPasswordHash)); // // foreach (IHttpServerResource Resource in HttpServer.GetResources()) // HttpsServer.Register (Resource); // // Log.Information ("HTTPS Server receiving requests on port " + HttpsServer.Port.ToString ()); // Main loop Log.Information ("Initialization complete. Application started..."); try { while (executionLed.Value) { System.Threading.Thread.Sleep (1000); RemoveOldSessions (); } } catch (Exception ex) { Log.Exception (ex); executionLed.Low (); } finally { Log.Information ("Terminating application."); Log.Flush (); Log.Terminate (); HttpServer.Dispose (); //HttpsServer.Dispose (); executionLed.Dispose (); foreach (DigitalOutput Output in digitalOutputs) Output.Dispose (); if (alarmThread != null) { alarmThread.Abort (); alarmThread = null; } } return 0; }
public static void Main (string[] args) { Log.Register (new ConsoleOutEventLog (80)); Log.Information ("Initializing application..."); HttpSocketClient.RegisterHttpProxyUse (false, false); // Don't look for proxies. DB.BackupConnectionString = "Data Source=camera.db;Version=3;"; DB.BackupProviderName = "Clayster.Library.Data.Providers.SQLiteServer.SQLiteServerProvider"; db = DB.GetDatabaseProxy ("TheCamera"); defaultSettings = DefaultSettings.LoadSettings (); if (defaultSettings == null) { defaultSettings = new DefaultSettings (); defaultSettings.SaveNew (); } Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => { e.Cancel = true; executionLed.Low (); }; try { // HTTP Interface httpServer = new HttpServer (80, 10, true, true, 1); Log.Information ("HTTP Server receiving requests on port " + httpServer.Port.ToString ()); httpServer.RegisterAuthenticationMethod (new DigestAuthentication ("The Camera Realm", GetDigestUserPasswordHash)); httpServer.RegisterAuthenticationMethod (new SessionAuthentication ()); credentials = LoginCredentials.LoadCredentials (); if (credentials == null) { credentials = new LoginCredentials (); credentials.UserName = "******"; credentials.PasswordHash = CalcHash ("Admin", "Password"); credentials.SaveNew (); } httpServer.Register ("/", HttpGetRootProtected, HttpPostRoot, false); // Synchronous, no authentication httpServer.Register ("/html", HttpGetHtmlProtected, false); // Synchronous, no authentication httpServer.Register ("/camera", HttpGetImgProtected, true); // Synchronous, www-authentication httpServer.Register ("/credentials", HttpGetCredentials, HttpPostCredentials, false); // Synchronous, no authentication // UPnP Interface upnpServer = new HttpServer (8080, 10, true, true, 1); Log.Information ("UPnP Server receiving requests on port " + upnpServer.Port.ToString ()); upnpServer.Register ("/", HttpGetRootUnprotected, HttpPostRoot, false); // Synchronous, no authentication upnpServer.Register ("/html", HttpGetHtmlUnprotected, false); // Synchronous, no authentication upnpServer.Register ("/camera", HttpGetImgUnprotected, false); // Synchronous, no authentication upnpServer.Register ("/CameraDevice.xml", HttpGetCameraDevice, false); upnpServer.Register (new HttpServerEmbeddedResource ("/StillImageService.xml", "Camera.UPnP.StillImageService.xml")); upnpServer.Register (stillImageWS = new DigitalSecurityCameraStillImage ()); // Icons taken from: http://www.iconarchive.com/show/the-bourne-ultimatum-icons-by-leoyue/Camera-icon.html upnpServer.Register (new HttpServerEmbeddedResource ("/Icon/16x16.png", "Camera.UPnP.16x16.png")); upnpServer.Register (new HttpServerEmbeddedResource ("/Icon/24x24.png", "Camera.UPnP.24x24.png")); upnpServer.Register (new HttpServerEmbeddedResource ("/Icon/32x32.png", "Camera.UPnP.32x32.png")); upnpServer.Register (new HttpServerEmbeddedResource ("/Icon/48x48.png", "Camera.UPnP.48x48.png")); upnpServer.Register (new HttpServerEmbeddedResource ("/Icon/64x64.png", "Camera.UPnP.64x64.png")); upnpServer.Register (new HttpServerEmbeddedResource ("/Icon/128x128.png", "Camera.UPnP.128x128.png")); upnpServer.Register (new HttpServerEmbeddedResource ("/Icon/256x256.png", "Camera.UPnP.256x256.png")); ssdpClient = new SsdpClient (upnpServer, 10, true, true, false, false, false, 30); ssdpClient.OnNotify += OnSsdpNotify; ssdpClient.OnDiscovery += OnSsdpDiscovery; // Initializing camera Log.Information ("Initializing camera."); try { currentResolution = defaultSettings.Resolution; currentCompressionRatio = defaultSettings.CompressionLevel; try { camera.Reset (); // First try @ 38400 baud camera.SetImageSize (currentResolution); camera.Reset (); camera.SetBaudRate (LinkSpriteJpegColorCamera.BaudRate.Baud_115200); camera.Dispose (); camera = new LinkSpriteJpegColorCamera (LinkSpriteJpegColorCamera.BaudRate.Baud_115200); } catch (Exception) // If already at 115200 baud. { camera.Dispose (); camera = new LinkSpriteJpegColorCamera (LinkSpriteJpegColorCamera.BaudRate.Baud_115200); } finally { camera.SetCompressionRatio (currentCompressionRatio); } } catch (Exception ex) { Log.Exception (ex); errorLed.High (); camera = null; } // Main loop Log.Information ("Initialization complete. Application started."); while (executionLed.Value) { Thread.Sleep (1000); RemoveOldSessions (); } } catch (Exception ex) { Log.Exception (ex); executionLed.Low (); } finally { Log.Information ("Terminating application."); Log.Flush (); Log.Terminate (); ssdpClient.Dispose (); if (upnpServer != null) upnpServer.Dispose (); if (httpServer != null) httpServer.Dispose (); executionLed.Dispose (); cameraLed.Dispose (); networkLed.Dispose (); errorLed.Dispose (); camera.Dispose (); } }
public static int Main (string[] args) { Log.Register (new ConsoleOutEventLog (80)); Log.Information ("Initializing application..."); HttpSocketClient.RegisterHttpProxyUse (false, false); // Don't look for proxies. DB.BackupConnectionString = "Data Source=sensor.db;Version=3;"; DB.BackupProviderName = "Clayster.Library.Data.Providers.SQLiteServer.SQLiteServerProvider"; db = DB.GetDatabaseProxy ("TheSensor"); Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => { e.Cancel = true; executionLed.Low (); }; // Initializing hardware and retrieving current sensor values try { tmp102.Configure (false, TexasInstrumentsTMP102.FaultQueue.ConsecutiveFaults_6, TexasInstrumentsTMP102.AlertPolarity.AlertActiveLow, TexasInstrumentsTMP102.ThermostatMode.ComparatorMode, false, TexasInstrumentsTMP102.ConversionRate.Hz_1, false); temp = (short)tmp102.ReadTemperatureRegister (); temperatureC = temp / 256.0; for (int i = 0; i < 10; i++) tempAvgWindow [i] = temp; sumTemp = temp * 10; } catch (Exception ex) { Log.Exception (ex); sumTemp = 0; temperatureC = 0; errorLed.High (); } try { adc.Configure (true, false, false, false, false, false); light = adc.ReadRegistersBinary () [0]; lightPercent = (100.0 * light) / 0x0fff; for (int i = 0; i < 10; i++) lightAvgWindow [i] = light; sumLight = light * 10; } catch (Exception ex) { Log.Exception (ex); sumLight = 0; lightPercent = 0; errorLed.High (); } // Loading historical Sensor Values Log.Information ("Loading Minute Values."); perMinute.AddRange (Record.LoadRecords (Rank.Minute)); Log.Information ("Loading Hour Values."); perHour.AddRange (Record.LoadRecords (Rank.Hour)); Log.Information ("Loading Day Values."); perDay.AddRange (Record.LoadRecords (Rank.Day)); Log.Information ("Loading Month Values."); perMonth.AddRange (Record.LoadRecords (Rank.Month)); // Resuming average calculations int Pos = perSecond.Count; DateTime CurrentTime = DateTime.Now; DateTime Timestamp; while (Pos-- > 0) { Record Rec = perSecond [Pos]; Timestamp = Rec.Timestamp; if (Timestamp.Minute == CurrentTime.Minute && Timestamp.Hour == CurrentTime.Hour && Timestamp.Date == CurrentTime.Date) { sumSeconds += Rec; nrSeconds++; } else break; } Pos = perMinute.Count; while (Pos-- > 0) { Record Rec = perMinute [Pos]; Timestamp = Rec.Timestamp; if (Timestamp.Hour == CurrentTime.Hour && Timestamp.Date == CurrentTime.Date) { sumMinutes += Rec; nrMinutes++; } else break; } Pos = perHour.Count; while (Pos-- > 0) { Record Rec = perHour [Pos]; Timestamp = Rec.Timestamp; if (Timestamp.Date == CurrentTime.Date) { sumHours += Rec; nrHours++; } else break; } Pos = perDay.Count; while (Pos-- > 0) { Record Rec = perDay [Pos]; Timestamp = Rec.Timestamp; if (Timestamp.Month == CurrentTime.Month && Timestamp.Year == CurrentTime.Year) { sumDays += Rec; nrDays++; } else break; } // Sampling of new Sensor Values Timer Timer = new Timer (SampleSensorValues, null, 1000 - DateTime.Now.Millisecond, 1000); // Every second. // HTTP Interface HttpServer HttpServer = new HttpServer (80, 10, true, true, 1); Log.Information ("HTTP Server receiving requests on port " + HttpServer.Port.ToString ()); HttpServer.RegisterAuthenticationMethod (new DigestAuthentication ("The Sensor Realm", GetDigestUserPasswordHash)); HttpServer.RegisterAuthenticationMethod (new SessionAuthentication ()); credentials = LoginCredentials.LoadCredentials (); if (credentials == null) { credentials = new LoginCredentials (); credentials.UserName = "******"; credentials.PasswordHash = CalcHash ("Admin", "Password"); credentials.SaveNew (); } HttpServer.Register ("/", HttpGetRoot, HttpPostRoot, false); // Synchronous, no authentication HttpServer.Register ("/html", HttpGetHtml, false); // Synchronous, no authentication HttpServer.Register ("/historygraph", HttpGetHistoryGraph, false); // Synchronous, no authentication HttpServer.Register ("/credentials", HttpGetCredentials, HttpPostCredentials, false); // Synchronous, no authentication HttpServer.Register ("/xml", HttpGetXml, true); // Synchronous, http authentication HttpServer.Register ("/json", HttpGetJson, true); // Synchronous, http authentication HttpServer.Register ("/turtle", HttpGetTurtle, true); // Synchronous, http authentication HttpServer.Register ("/rdf", HttpGetRdf, true); // Synchronous, http authentication HttpServer.Register ("/event/xml", HttpGetEventXml, true, false); // Asynchronous, http authentication HttpServer.Register ("/event/json", HttpGetEventJson, true, false); // Asynchronous, http authentication HttpServer.Register ("/event/turtle", HttpGetEventTurtle, true, false); // Asynchronous, http authentication HttpServer.Register ("/event/rdf", HttpGetEventRdf, true, false); // Asynchronous, http authentication // HTTPS interface // Certificate must be a valid P12 (PFX) certificate file containing a private key. // X509Certificate2 Certificate = new X509Certificate2 ("Certificate.pfx", "PASSWORD"); // HttpServer HttpsServer = new HttpServer (443, 10, true, true, 1, true, false, Certificate); // // HttpsServer.RegisterAuthenticationMethod (new DigestAuthentication ("The Sensor Realm", GetDigestUserPasswordHash)); // HttpsServer.RegisterAuthenticationMethod (new SessionAuthentication ()); // // foreach (IHttpServerResource Resource in HttpServer.GetResources()) // HttpsServer.Register (Resource); // // Log.Information ("HTTPS Server receiving requests on port " + HttpsServer.Port.ToString ()); // Main loop Log.Information ("Initialization complete. Application started..."); try { while (executionLed.Value) { System.Threading.Thread.Sleep (1000); } } catch (Exception ex) { Log.Exception (ex); executionLed.Low (); } finally { Log.Information ("Terminating application."); Log.Flush (); Log.Terminate (); Timer.Dispose (); HttpServer.Dispose (); //HttpsServer.Dispose (); executionLed.Dispose (); measurementLed.Dispose (); errorLed.Dispose (); networkLed.Dispose (); motion.Dispose (); i2cBus.Dispose (); } return 0; }
/// <summary> /// Create a new pack indexer utility. /// </summary> /// <param name="src"> /// stream to read the pack data from. If the stream is buffered /// use <see cref="BUFFER_SIZE"/> as the buffer size for the stream. /// </param> /// <param name="dstBase"></param> public IndexPack(Repository db, Stream src, FileInfo dstBase) { _repo = db; _objectDatabase = db.ObjectDatabase.newCachedDatabase(); _stream = src; _crc = new Crc32(); _inflater = InflaterCache.Instance.get(); _windowCursor = new WindowCursor(); _buffer = new byte[BUFFER_SIZE]; _objectData = new byte[BUFFER_SIZE]; _objectDigest = Constants.newMessageDigest(); _tempObjectId = new MutableObjectId(); _packDigest = Constants.newMessageDigest(); if (dstBase != null) { DirectoryInfo dir = dstBase.Directory; string nam = dstBase.Name; _dstPack = new FileInfo(Path.Combine(dir.FullName, GetPackFileName(nam))); _dstIdx = new FileInfo(Path.Combine(dir.FullName, GetIndexFileName(nam))); _packOut = _dstPack.Create(); } else { _dstPack = null; _dstIdx = null; } }