示例#1
0
        private async void Start()
        {
            try
            {
                this.MainView.ShowStatus("Initializing");

                databaseProvider = await FilesProvider.CreateAsync(appDataFolder + "Data", "Default", 8192, 10000, 8192, Encoding.UTF8, 3600000);

                await databaseProvider.RepairIfInproperShutdown(appDataFolder + "Transforms" + Path.DirectorySeparatorChar + "DbStatXmlToHtml.xslt");

                await databaseProvider.Start();

                Database.Register(databaseProvider);

                await Database.Find <Question>(new FilterAnd(new FilterFieldEqualTo("OwnerJID", string.Empty),
                                                             new FilterFieldEqualTo("ProvisioningJID", string.Empty))); // To prepare indices, etc.

                ChatView.InitEmojis();

                this.MainView.ShowStatus("Initialization complete.");
            }
            catch (Exception ex)
            {
                ex = Log.UnnestException(ex);
                Log.Critical(ex);
                this.MainView.ShowStatus("Failure to initialize: " + ex.Message);
                ErrorBox(ex.Message);
            }
        }
示例#2
0
        private async void Initialize()
        {
            instance = this;

            Log.Register(new InternalSink());

            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                if (e.IsTerminating)
                {
                    Stop().Wait();
                }
            };

            TaskScheduler.UnobservedTaskException += (sender, e) =>
            {
                e.SetObserved();
            };

            Types.Initialize(
                typeof(App).Assembly,
                typeof(Database).Assembly,
                typeof(FilesProvider).Assembly,
                typeof(ObjectSerializer).Assembly,
                typeof(XmppClient).Assembly,
                typeof(ContractsClient).Assembly,
                typeof(Waher.Things.ThingReference).Assembly,
                typeof(Waher.Runtime.Settings.RuntimeSettings).Assembly,
                typeof(Waher.Runtime.Language.Language).Assembly,
                typeof(Waher.Networking.DNS.DnsResolver).Assembly,
                typeof(Waher.Networking.XMPP.Sensor.SensorClient).Assembly,
                typeof(Waher.Networking.XMPP.Control.ControlClient).Assembly,
                typeof(Waher.Networking.XMPP.Concentrator.ConcentratorClient).Assembly,
                typeof(Waher.Networking.XMPP.P2P.XmppServerlessMessaging).Assembly,
                typeof(Waher.Networking.XMPP.Provisioning.ProvisioningClient).Assembly,
                typeof(Waher.Security.EllipticCurves.EllipticCurve).Assembly);

            string AppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string DataFolder    = Path.Combine(AppDataFolder, "Data");

            FilesProvider Provider = await FilesProvider.CreateAsync(DataFolder, "Default", 8192, 10000, 8192, Encoding.UTF8, 10000, this.GetCustomKey);

            await Provider.RepairIfInproperShutdown(string.Empty);

            Database.Register(Provider);

            configuration = await Database.FindFirstDeleteRest <XmppConfiguration>();

            if (configuration is null)
            {
                await Task.Delay(1000);

                configuration = new XmppConfiguration();
                await Database.Insert(configuration);
            }



            await ShowPage();
        }
        public static async Task ClassInitialize(TestContext Context)
        {
#if LW
            provider = await FilesProvider.CreateAsync("Data", "Default", 8192, 10000, 8192, Encoding.UTF8, 10000);
#else
            provider = await FilesProvider.CreateAsync("Data", "Default", 8192, 10000, 8192, Encoding.UTF8, 10000, true);
#endif
        }
示例#4
0
        public async Task TestInitialize()
        {
            DBFilesBTreeTests.DeleteFiles();

#if LW
            this.provider = await FilesProvider.CreateAsync("Data", DBFilesBTreeTests.CollectionName, 8192, BlocksInCache, 8192, Encoding.UTF8, 10000);
#else
            this.provider = await FilesProvider.CreateAsync("Data", DBFilesBTreeTests.CollectionName, 8192, BlocksInCache, 8192, Encoding.UTF8, 10000, true);
#endif
            this.file = await this.provider.GetFile("Default");
        }
示例#5
0
        public static async Task ClassInitialize(TestContext Context)
        {
            DBFilesBTreeTests.DeleteFiles();

#if LW
            provider = await FilesProvider.CreateAsync("Data", "Default", BlockSize, BlocksInCache, Math.Max(BlockSize / 2, 1024), Encoding.UTF8, 10000);
#else
            provider = await FilesProvider.CreateAsync("Data", "Default", BlockSize, BlocksInCache, Math.Max(BlockSize / 2, 1024), Encoding.UTF8, 10000, true);
#endif
            file = await provider.GetFile("Default");
        }
示例#6
0
        public static async Task AssemblyInitialize(TestContext _)
        {
            Types.Initialize(
                typeof(Database).Assembly,
                typeof(FilesProvider).Assembly,
                typeof(ObjectSerializer).Assembly,
                typeof(DnsResolver).Assembly);

            filesProvider = await FilesProvider.CreateAsync("Data", "Default", 8192, 10000, 8192, Encoding.UTF8, 10000, true);

            Database.Register(filesProvider);
        }
示例#7
0
        public async Task TestInitialize()
        {
            DeleteFiles();

#if LW
            this.provider = await FilesProvider.CreateAsync(Folder, CollectionName, this.BlockSize, BlocksInCache, Math.Max(BlockSize / 2, 1024), Encoding.UTF8, 10000);
#else
            this.provider = await FilesProvider.CreateAsync(Folder, CollectionName, this.BlockSize, BlocksInCache, Math.Max(BlockSize / 2, 1024), Encoding.UTF8, 10000, true);
#endif
            this.file = await this.provider.GetFile(CollectionName);

            this.start = DateTime.Now;
        }
示例#8
0
        public static async Task AssemblyInitialize(TestContext _)
        {
            Types.Initialize(
                typeof(FilesProvider).Assembly,
                typeof(ObjectSerializer).Assembly,
                typeof(LanguageTests).Assembly,
                typeof(Expression).Assembly);

            Log.Register(consoleEventSink = new ConsoleEventSink());

            filesProvider = await FilesProvider.CreateAsync("Data", "Default", 8192, 10000, 8192, Encoding.UTF8, 10000, true);

            Database.Register(filesProvider);
        }
示例#9
0
        public static async Task ClassInitialize(TestContext Context)
        {
            try
            {
                IDatabaseProvider p = Database.Provider;
            }
            catch
            {
#if LW
                Database.Register(await FilesProvider.CreateAsync("Data", "Default", 8192, 8192, 8192, Encoding.UTF8, 10000));
#else
                Database.Register(await FilesProvider.CreateAsync("Data", "Default", 8192, 8192, 8192, Encoding.UTF8, 10000, true));
#endif
            }
        }
示例#10
0
		private async static Task<IDatabaseProvider> GetDatabase(XmlElement DatabaseConfig)
		{
			if (!CommonTypes.TryParse(DatabaseConfig.Attributes["encrypted"].Value, out bool Encrypted))
				Encrypted = true;

			FilesProvider Result = await FilesProvider.CreateAsync(Gateway.AppDataFolder + DatabaseConfig.Attributes["folder"].Value,
				DatabaseConfig.Attributes["defaultCollectionName"].Value,
				int.Parse(DatabaseConfig.Attributes["blockSize"].Value),
				int.Parse(DatabaseConfig.Attributes["blocksInCache"].Value),
				int.Parse(DatabaseConfig.Attributes["blobBlockSize"].Value), Encoding.UTF8,
				int.Parse(DatabaseConfig.Attributes["timeoutMs"].Value),
				Encrypted, true);

			return Result;
		}
示例#11
0
        public async Task TestInitialize()
        {
            if (!File.Exists(DBFilesBTreeTests.MasterFileName + ".bak") ||
                !File.Exists(DBFilesBTreeTests.DefaultFileName + ".bak") ||
                !File.Exists(DBFilesBTreeTests.DefaultBlobFileName + ".bak") ||
                !File.Exists(DBFilesBTreeTests.DefaultLabelsFileName + ".bak"))
            {
                Assert.Inconclusive("No backup files to test against.");
            }

            if (File.Exists(DBFilesBTreeTests.MasterFileName))
            {
                File.Delete(DBFilesBTreeTests.MasterFileName);
            }

            if (File.Exists(DBFilesBTreeTests.DefaultFileName))
            {
                File.Delete(DBFilesBTreeTests.DefaultFileName);
            }

            if (File.Exists(DBFilesBTreeTests.DefaultBlobFileName))
            {
                File.Delete(DBFilesBTreeTests.DefaultBlobFileName);
            }

            if (File.Exists(DBFilesBTreeTests.DefaultLabelsFileName))
            {
                File.Delete(DBFilesBTreeTests.DefaultLabelsFileName);
            }

            File.Copy(DBFilesBTreeTests.MasterFileName + ".bak", DBFilesBTreeTests.MasterFileName);
            File.Copy(DBFilesBTreeTests.DefaultFileName + ".bak", DBFilesBTreeTests.DefaultFileName);
            File.Copy(DBFilesBTreeTests.DefaultBlobFileName + ".bak", DBFilesBTreeTests.DefaultBlobFileName);
            File.Copy(DBFilesBTreeTests.DefaultLabelsFileName + ".bak", DBFilesBTreeTests.DefaultLabelsFileName);

            int BlockSize = this.LoadBlockSize();

#if LW
            this.provider = await FilesProvider.CreateAsync(DBFilesBTreeTests.Folder, DBFilesBTreeTests.CollectionName, BlockSize, 10000, Math.Max(BlockSize / 2, 1024), Encoding.UTF8, 10000);
#else
            this.provider = await FilesProvider.CreateAsync(DBFilesBTreeTests.Folder, DBFilesBTreeTests.CollectionName, BlockSize, 10000, Math.Max(BlockSize / 2, 1024), Encoding.UTF8, 10000, true);
#endif
            this.file = await this.provider.GetFile(DBFilesBTreeTests.CollectionName);

            this.start = DateTime.Now;

            await DBFilesBTreeTests.ExportXML(this.file, "Data\\BTreeBefore.xml");
        }
示例#12
0
        private static async Task <IDatabaseProvider> GetDatabase(XmlElement DatabaseConfig)
        {
            if (CommonTypes.TryParse(DatabaseConfig.Attributes["encrypted"].Value, out bool Encrypted) && Encrypted)
            {
                throw new Exception("Encrypted database storage not supported on this platform.");
            }

            FilesProvider Result = await FilesProvider.CreateAsync(Gateway.AppDataFolder + DatabaseConfig.Attributes["folder"].Value,
                                                                   DatabaseConfig.Attributes["defaultCollectionName"].Value,
                                                                   int.Parse(DatabaseConfig.Attributes["blockSize"].Value),
                                                                   int.Parse(DatabaseConfig.Attributes["blocksInCache"].Value),
                                                                   int.Parse(DatabaseConfig.Attributes["blobBlockSize"].Value), Encoding.UTF8,
                                                                   int.Parse(DatabaseConfig.Attributes["timeoutMs"].Value));

            return(Result);
        }
示例#13
0
        public static async Task AssemblyInitialize(TestContext _)
        {
            Waher.Runtime.Inventory.Types.Initialize(
                typeof(MarkdownPlainTextTests).Assembly,
                typeof(Expression).Assembly,
                typeof(Graph).Assembly,
                typeof(MarkdownDocument).Assembly,
                typeof(CommonTypes).Assembly,
                typeof(Database).Assembly,
                typeof(FilesProvider).Assembly,
                typeof(ObjectSerializer).Assembly,
                typeof(ImageCodec).Assembly);

            filesProvider = await FilesProvider.CreateAsync("Data", "Default", 8192, 10000, 8192, Encoding.UTF8, 10000, true);

            Database.Register(filesProvider);
        }
示例#14
0
        public static async Task AssemblyInitialize(TestContext Context)
        {
            Types.Initialize(
                typeof(IContentDecoder).Assembly,
                typeof(Waher.Content.Xml.Text.XmlCodec).Assembly,
                typeof(CoapEndpoint).Assembly,
                typeof(Lwm2mClient).Assembly,
                typeof(Database).Assembly,
                typeof(FilesProvider).Assembly,
                typeof(ObjectSerializer).Assembly,
                typeof(ICipher).Assembly);

            Log.Register(consoleEventSink = new ConsoleEventSink());

            filesProvider = await FilesProvider.CreateAsync("Data", "Default", 8192, 10000, 8192, Encoding.UTF8, 10000);

            Database.Register(filesProvider);
        }
示例#15
0
        public static async Task AssemblyInitialize(TestContext _)
        {
            Types.Initialize(
                typeof(Database).Assembly,
                typeof(FilesProvider).Assembly,
                typeof(ObjectSerializer).Assembly,
                typeof(LoginAuditor).Assembly);

            filesProvider = await FilesProvider.CreateAsync("Data", "Default", 8192, 10000, 8192, Encoding.UTF8, 10000, true);

            Database.Register(filesProvider);

            auditor = new LoginAuditor("Login Auditor",
                                       new LoginInterval(5, TimeSpan.FromHours(1)), // Maximum 5 failed login attempts in an hour
                                       new LoginInterval(2, TimeSpan.FromDays(1)),  // Maximum 2x5 failed login attempts in a day
                                       new LoginInterval(2, TimeSpan.FromDays(7)),  // Maximum 2x2x5 failed login attempts in a week
                                       new LoginInterval(2, TimeSpan.MaxValue));    // Maximum 2x2x2x5 failed login attempts in total, then blocked.
        }
        public async Task TestInitialize()
        {
            if (File.Exists(DBFilesBTreeTests.MasterFileName + ".bak"))
            {
                File.Delete(DBFilesBTreeTests.MasterFileName + ".bak");
            }

            if (File.Exists(DBFilesBTreeTests.MasterFileName))
            {
                File.Copy(DBFilesBTreeTests.MasterFileName, DBFilesBTreeTests.MasterFileName + ".bak");
                File.Delete(DBFilesBTreeTests.MasterFileName);
            }

            if (File.Exists(FileName + ".bak"))
            {
                File.Delete(FileName + ".bak");
            }

            if (File.Exists(FileName))
            {
                File.Copy(FileName, FileName + ".bak");
                File.Delete(FileName);
            }

            if (File.Exists(BlobFileName + ".bak"))
            {
                File.Delete(BlobFileName + ".bak");
            }

            if (File.Exists(BlobFileName))
            {
                File.Copy(BlobFileName, BlobFileName + ".bak");
                File.Delete(BlobFileName);
            }

#if LW
            this.provider = await FilesProvider.CreateAsync(Folder, CollectionName, 8192, BlocksInCache, 8192, Encoding.UTF8, 10000);
#else
            this.provider = await FilesProvider.CreateAsync(Folder, CollectionName, 8192, BlocksInCache, 8192, Encoding.UTF8, 10000, true);
#endif
            this.file = await StringDictionary.Create(FileName, BlobFileName, CollectionName, this.provider, false);

            this.start = DateTime.Now;
        }
        async void init()
        {
            Types.Initialize(
                typeof(FilesProvider).GetTypeInfo().Assembly,
                typeof(ObjectSerializer).GetTypeInfo().Assembly,
                typeof(RuntimeSettings).GetTypeInfo().Assembly,
                typeof(Waher.Content.IContentEncoder).GetTypeInfo().Assembly,
                typeof(XmppClient).GetTypeInfo().Assembly,
                typeof(Waher.Content.Markdown.MarkdownDocument).GetTypeInfo().Assembly,
                typeof(XML).GetTypeInfo().Assembly,
                typeof(Waher.Script.Expression).GetTypeInfo().Assembly,
                typeof(Waher.Script.Graphs.Graph).GetTypeInfo().Assembly,
                typeof(Waher.Script.Persistence.SQL.Select).GetTypeInfo().Assembly,
                typeof(TheClientV).Assembly);
            db = await FilesProvider.CreateAsync(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
                                                 Path.DirectorySeparatorChar + "IoT-DEMO-APP", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);

            Database.Register(db);

            await db.RepairIfInproperShutdown(null);

            await db.Start();

            this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

            if (string.IsNullOrEmpty(this.deviceId))
            {
                this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
            }

            Console.WriteLine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
                              Path.DirectorySeparatorChar + "IoT-DEMO-APP");
            Console.WriteLine(this.deviceId);

            this.xmppClient = new XmppClient(this.Host, this.Port, this.UserName, this.PasswordHash, "en", typeof(TheClientV).Assembly);
            this.xmppClient.AllowRegistration(Key, Secret);
            this.xmppClient.OnConnectionError   += this.ConnectionError;
            this.xmppClient.OnStateChanged      += this.OnStateChanged;
            this.xmppClient.OnRosterItemAdded   += OnRosterItemAdded;
            this.xmppClient.OnRosterItemUpdated += OnRosterItemUpdated;
            this.xmppClient.OnRosterItemRemoved += OnRosterItemRemoved;
            this.xmppClient.Connect();
        }
示例#18
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(ObjectSerializer).GetTypeInfo().Assembly,                        // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(ICoapContentFormat).GetTypeInfo().Assembly,
                    typeof(IDtlsCredentials).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = await FilesProvider.CreateAsync(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                     Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);

                Database.Register(db);
                await db.RepairIfInproperShutdown(null);

                await db.Start();

#if GPIO
                gpio = GpioController.GetDefault();
                if (gpio != null)
                {
                    if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
                        Status == GpioOpenStatus.PinOpened)
                    {
                        if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
                        {
                            this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.gpioPin.Write(this.output.Value ? GpioPinValue.High : GpioPinValue.Low);

                            await MainPage.Instance.OutputSet(this.output.Value);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output.Value));
                        }
                        else
                        {
                            Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
                        }
                    }
                    else
                    {
                        Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
                    }
                }
#else
                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += async() =>
                    {
                        try
                        {
                            Log.Informational("Device ready.");

                            this.arduino.pinMode(13, PinMode.OUTPUT);                                // Onboard LED.
                            this.arduino.digitalWrite(13, PinState.HIGH);

                            this.arduino.pinMode(8, PinMode.INPUT);                                  // PIR sensor (motion detection).

                            this.arduino.pinMode(9, PinMode.OUTPUT);                                 // Relay.

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW);

                            await MainPage.Instance.OutputSet(this.output.Value);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output.Value));

                            this.arduino.pinMode("A0", PinMode.ANALOG);                             // Light sensor.
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }
#endif
                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                /************************************************************************************
                * To create an unencrypted CoAP Endpoint on the default CoAP port:
                *
                *    this.coapEndpoint = new CoapEndpoint();
                *
                * To create an unencrypted CoAP Endpoint on the default CoAP port,
                * with a sniffer that outputs communication to the window:
                *
                *    this.coapEndpoint = new CoapEndpoint(new LogSniffer());
                *
                * To create a DTLS encrypted CoAP endpoint, on the default CoAPS port, using
                * the users defined in the IUserSource users:
                *
                *    this.coapEndpoint = new CoapEndpoint(CoapEndpoint.DefaultCoapsPort, this.users);
                *
                * To create a CoAP endpoint, that listens to both the default CoAP port, for
                * unencrypted communication, and the default CoAPS port, for encrypted,
                * authenticated and authorized communication, using
                * the users defined in the IUserSource users. Only users having the given
                * privilege (if not empty) will be authorized to access resources on the endpoint:
                *
                *    this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                *       new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, "PRIVILEGE", false, false);
                *
                ************************************************************************************/

                this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                                                     new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, string.Empty, false, false);

                this.outputResource = this.coapEndpoint.Register("/Output", (req, resp) =>
                {
                    string s;

                    if (this.output.HasValue)
                    {
                        s = this.output.Value ? "true" : "false";
                    }
                    else
                    {
                        s = "-";
                    }

                    resp.Respond(CoapCode.Content, s, 64);
                }, async(req, resp) =>
                {
                    try
                    {
                        string s = req.Decode() as string;
                        if (s is null && req.Payload != null)
                        {
                            s = Encoding.UTF8.GetString(req.Payload);
                        }

                        if (s is null || !CommonTypes.TryParse(s, out bool Output))
                        {
                            resp.RST(CoapCode.BadRequest);
                        }
                        else
                        {
                            resp.Respond(CoapCode.Changed);
                            await this.SetOutput(Output, req.From.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                }, Notifications.Acknowledged, "Digital Output.", null, null,
示例#19
0
        static int Main(string[] args)
        {
            FilesProvider FilesProvider     = null;
            Encoding      Encoding          = Encoding.UTF8;
            string        ProgramDataFolder = null;
            string        ScriptFile        = null;
            string        s;
            int           BlockSize     = 8192;
            int           BlobBlockSize = 8192;
            int           i             = 0;
            int           c             = args.Length;
            bool          Help          = false;
            bool          Encryption    = false;

            try
            {
                while (i < c)
                {
                    s = args[i++].ToLower();

                    switch (s)
                    {
                    case "-i":
                        if (i >= c)
                        {
                            throw new Exception("Missing script file.");
                        }

                        if (string.IsNullOrEmpty(ScriptFile))
                        {
                            ScriptFile = args[i++];
                        }
                        else
                        {
                            throw new Exception("Only one script file allowed.");
                        }
                        break;

                    case "-d":
                        if (i >= c)
                        {
                            throw new Exception("Missing program data folder.");
                        }

                        if (string.IsNullOrEmpty(ProgramDataFolder))
                        {
                            ProgramDataFolder = args[i++];
                        }
                        else
                        {
                            throw new Exception("Only one program data folder allowed.");
                        }
                        break;

                    case "-bs":
                        if (i >= c)
                        {
                            throw new Exception("Block size missing.");
                        }

                        if (!int.TryParse(args[i++], out BlockSize))
                        {
                            throw new Exception("Invalid block size");
                        }

                        break;

                    case "-bbs":
                        if (i >= c)
                        {
                            throw new Exception("Blob Block size missing.");
                        }

                        if (!int.TryParse(args[i++], out BlobBlockSize))
                        {
                            throw new Exception("Invalid blob block size");
                        }

                        break;

                    case "-enc":
                        if (i >= c)
                        {
                            throw new Exception("Text encoding missing.");
                        }

                        Encoding = Encoding.GetEncoding(args[i++]);
                        break;

                    case "-e":
                        Encryption = true;
                        break;

                    case "-?":
                        Help = true;
                        break;

                    default:
                        throw new Exception("Unrecognized switch: " + s);
                    }
                }

                if (Help || c == 0)
                {
                    Console.Out.WriteLine("Allows you to execute script.");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Command line switches:");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("-i SCRIPT_FILE        Points to the script file to execute.");
                    Console.Out.WriteLine("-d APP_DATA_FOLDER    Points to the application data folder.");
                    Console.Out.WriteLine("                      If specified, a connection to a files");
                    Console.Out.WriteLine("                      object database (Waher.Persistence.Files)");
                    Console.Out.WriteLine("                      will be established.");
                    Console.Out.WriteLine("-e                    If encryption is used by the database.");
                    Console.Out.WriteLine("-bs BLOCK_SIZE        Block size, in bytes. Default=8192.");
                    Console.Out.WriteLine("-bbs BLOB_BLOCK_SIZE  BLOB block size, in bytes. Default=8192.");
                    Console.Out.WriteLine("-?                    Help.");
                    return(0);
                }

                if (string.IsNullOrEmpty(ScriptFile))
                {
                    throw new Exception("No script file provided.");
                }

                Types.Initialize(
                    typeof(Log).Assembly,
                    typeof(Expression).Assembly,
                    typeof(Database).Assembly,
                    typeof(FilesProvider).Assembly,
                    typeof(ObjectSerializer).Assembly,
                    typeof(Content.InternetContent).Assembly,
                    typeof(Content.Html.HtmlDocument).Assembly,
                    typeof(Content.Images.ImageCodec).Assembly,
                    typeof(Content.Xml.XML).Assembly,
                    typeof(Content.Xsl.XSL).Assembly,
                    typeof(Events.Console.ConsoleEventSink).Assembly,
                    typeof(Script.Content.Functions.Encoding.Base64Decode).Assembly,
                    typeof(Script.Cryptography.Functions.RandomBytes).Assembly,
                    typeof(Script.Fractals.FractalGraph).Assembly,
                    typeof(Script.Graphs.Graph).Assembly,
                    typeof(Script.Graphs3D.Canvas3D).Assembly,
                    typeof(Script.Networking.Functions.Dns).Assembly,
                    typeof(Script.Persistence.Functions.DeleteObject).Assembly,
                    typeof(Script.Statistics.StatMath).Assembly,
                    typeof(Script.Xml.XmlOutput).Assembly);

                string     Script = File.ReadAllText(ScriptFile);
                Expression Parsed = new Expression(Script);

                Log.Register(new Events.Console.ConsoleEventSink());

                if (!string.IsNullOrEmpty(ProgramDataFolder))
                {
                    if (!Directory.Exists(ProgramDataFolder))
                    {
                        throw new Exception("Program data folder does not exist.");
                    }

                    FilesProvider = FilesProvider.CreateAsync(ProgramDataFolder, "Default", BlockSize, 10000, BlobBlockSize, Encoding, 3600000, Encryption, false).Result;
                    Database.Register(FilesProvider);

                    FilesProvider.RepairIfInproperShutdown(string.Empty).Wait();
                    FilesProvider.Start().Wait();
                }

                Variables Variables = new Variables();
                Variables.ConsoleOut = Console.Out;

                object Result = Parsed.Evaluate(Variables);

                Console.Out.WriteLine(Expression.ToString(Result));

                return(0);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                return(-1);
            }
            finally
            {
                Log.Terminate();

                if (!(FilesProvider is null))
                {
                    FilesProvider.Stop().Wait();
                    FilesProvider?.Dispose();
                }
            }
        }
示例#20
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(ObjectSerializer).GetTypeInfo().Assembly,                        // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(ICoapContentFormat).GetTypeInfo().Assembly,
                    typeof(IDtlsCredentials).GetTypeInfo().Assembly,
                    typeof(Lwm2mClient).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = await FilesProvider.CreateAsync(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                     Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);

                Database.Register(db);
                await db.RepairIfInproperShutdown(null);

                await db.Start();

                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += () =>
                    {
                        Log.Informational("Device ready.");

                        this.arduino.pinMode(13, PinMode.OUTPUT);                            // Onboard LED.
                        this.arduino.digitalWrite(13, PinState.HIGH);

                        this.arduino.pinMode(8, PinMode.INPUT);                              // PIR sensor (motion detection).
                        PinState Pin8 = this.arduino.digitalRead(8);
                        this.lastMotion = Pin8 == PinState.HIGH;
                        MainPage.Instance.DigitalPinUpdated(8, Pin8);

                        this.arduino.pinMode(9, PinMode.OUTPUT);                            // Relay.
                        this.arduino.digitalWrite(9, 0);                                    // Relay set to 0

                        this.arduino.pinMode("A0", PinMode.ANALOG);                         // Light sensor.
                        MainPage.Instance.AnalogPinUpdated("A0", this.arduino.analogRead("A0"));

                        this.sampleTimer = new Timer(this.SampleValues, null, 1000 - DateTime.Now.Millisecond, 1000);
                    };

                    this.arduino.AnalogPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.AnalogPinUpdated(pin, value);
                    };

                    this.arduino.DigitalPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.DigitalPinUpdated(pin, value);

                        if (pin == 8)
                        {
                            bool Input = (value == PinState.HIGH);
                            this.lastMotion = Input;
                            this.digitalInput0?.Set(Input);
                            this.presenceSensor0?.Set(Input);
                            this.genericSensor0?.Set(Input ? 1.0 : 0.0);
                            this.motionResource?.TriggerAll();
                            this.momentaryResource?.TriggerAll();
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }

                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                /************************************************************************************
                * To create an unencrypted CoAP Endpoint on the default CoAP port:
                *
                *    this.coapEndpoint = new CoapEndpoint();
                *
                * To create an unencrypted CoAP Endpoint on the default CoAP port,
                * with a sniffer that outputs communication to the window:
                *
                *    this.coapEndpoint = new CoapEndpoint(new LogSniffer());
                *
                * To create a DTLS encrypted CoAP endpoint, on the default CoAPS port, using
                * the users defined in the IUserSource users:
                *
                *    this.coapEndpoint = new CoapEndpoint(CoapEndpoint.DefaultCoapsPort, this.users);
                *
                * To create a CoAP endpoint, that listens to both the default CoAP port, for
                * unencrypted communication, and the default CoAPS port, for encrypted,
                * authenticated and authorized communication, using
                * the users defined in the IUserSource users. Only users having the given
                * privilege (if not empty) will be authorized to access resources on the endpoint:
                *
                *    this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                *       new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, "PRIVILEGE", false, false);
                *
                ************************************************************************************/

                //this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                //	new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, string.Empty, false, false);

                this.coapEndpoint = new CoapEndpoint(new int[] { 5783 }, new int[] { 5784 }, null, null,
                                                     false, false);

                this.lightResource = this.coapEndpoint.Register("/Light", (req, resp) =>
                {
                    string s;

                    if (this.lastLight.HasValue)
                    {
                        s = ToString(this.lastLight.Value, 2) + " %";
                    }
                    else
                    {
                        s = "-";
                    }

                    resp.Respond(CoapCode.Content, s, 64);
                }, Notifications.Unacknowledged, "Light, in %.", null, null,
                                                                new int[] { PlainText.ContentFormatCode });

                this.lightResource?.TriggerAll(new TimeSpan(0, 0, 5));

                this.motionResource = this.coapEndpoint.Register("/Motion", (req, resp) =>
                {
                    string s;

                    if (this.lastMotion.HasValue)
                    {
                        s = this.lastMotion.Value ? "true" : "false";
                    }
                    else
                    {
                        s = "-";
                    }

                    resp.Respond(CoapCode.Content, s, 64);
                }, Notifications.Acknowledged, "Motion detector.", null, null,
                                                                 new int[] { PlainText.ContentFormatCode });

                this.motionResource?.TriggerAll(new TimeSpan(0, 1, 0));

                this.momentaryResource = this.coapEndpoint.Register("/Momentary", (req, resp) =>
                {
                    if (req.IsAcceptable(Xml.ContentFormatCode))
                    {
                        this.ReturnMomentaryAsXml(req, resp);
                    }
                    else if (req.IsAcceptable(Json.ContentFormatCode))
                    {
                        this.ReturnMomentaryAsJson(req, resp);
                    }
                    else if (req.IsAcceptable(PlainText.ContentFormatCode))
                    {
                        this.ReturnMomentaryAsPlainText(req, resp);
                    }
                    else if (req.Accept.HasValue)
                    {
                        throw new CoapException(CoapCode.NotAcceptable);
                    }
                    else
                    {
                        this.ReturnMomentaryAsPlainText(req, resp);
                    }
                }, Notifications.Acknowledged, "Momentary values.", null, null,
                                                                    new int[] { Xml.ContentFormatCode, Json.ContentFormatCode, PlainText.ContentFormatCode });

                this.momentaryResource?.TriggerAll(new TimeSpan(0, 0, 5));

                this.lwm2mClient = new Lwm2mClient("MIoT:Sensor:" + this.deviceId, this.coapEndpoint,
                                                   new Lwm2mSecurityObject(),
                                                   new Lwm2mServerObject(),
                                                   new Lwm2mAccessControlObject(),
                                                   new Lwm2mDeviceObject("Waher Data AB", "SensorLwm2m", this.deviceId, "1.0", "Sensor", "1.0", "1.0"),
                                                   new DigitalInput(this.digitalInput0           = new DigitalInputInstance(0, this.lastMotion, "Motion Detector", "PIR")),
                                                   new AnalogInput(this.analogInput0             = new AnalogInputInstance(0, this.lastLight, 0, 100, "Ambient Light Sensor", "%")),
                                                   new GenericSensor(this.genericSensor0         = new GenericSensorInstance(0, null, string.Empty, 0, 1, "Motion Detector", "PIR"),
                                                                     this.genericSensor1         = new GenericSensorInstance(1, this.lastLight, "%", 0, 100, "Ambient Light Sensor", "%")),
                                                   new IlluminanceSensor(this.illuminanceSensor0 = new IlluminanceSensorInstance(0, this.lastLight, "%", 0, 100)),
                                                   new PresenceSensor(this.presenceSensor0       = new PresenceSensorInstance(0, this.lastMotion, "PIR")),
                                                   new PercentageSensor(this.percentageSensor0   = new PercentageSensorInstance(0, this.lastLight, 0, 100, "Ambient Light Sensor")));

                await this.lwm2mClient.LoadBootstrapInfo();

                this.lwm2mClient.OnStateChanged += (sender, e) =>
                {
                    Log.Informational("LWM2M state changed to " + this.lwm2mClient.State.ToString() + ".");
                };

                this.lwm2mClient.OnBootstrapCompleted += (sender, e) =>
                {
                    Log.Informational("Bootstrap procedure completed.");
                };

                this.lwm2mClient.OnBootstrapFailed += (sender, e) =>
                {
                    Log.Error("Bootstrap procedure failed.");

                    this.coapEndpoint.ScheduleEvent(async(P) =>
                    {
                        try
                        {
                            await this.RequestBootstrap();
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    }, DateTime.Now.AddMinutes(15), null);
                };

                this.lwm2mClient.OnRegistrationSuccessful += (sender, e) =>
                {
                    Log.Informational("Server registration completed.");
                };

                this.lwm2mClient.OnRegistrationFailed += (sender, e) =>
                {
                    Log.Error("Server registration failed.");
                };

                this.lwm2mClient.OnDeregistrationSuccessful += (sender, e) =>
                {
                    Log.Informational("Server deregistration completed.");
                };

                this.lwm2mClient.OnDeregistrationFailed += (sender, e) =>
                {
                    Log.Error("Server deregistration failed.");
                };

                this.lwm2mClient.OnRebootRequest += async(sender, e) =>
                {
                    Log.Warning("Reboot is requested.");

                    try
                    {
                        await this.RequestBootstrap();
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                };

                await this.RequestBootstrap();
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
示例#21
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");
                instance = this;

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(ObjectSerializer).GetTypeInfo().Assembly,                        // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(ImageCodec).GetTypeInfo().Assembly,
                    typeof(MarkdownDocument).GetTypeInfo().Assembly,
                    typeof(MarkdownToHtmlConverter).GetTypeInfo().Assembly,
                    typeof(JwsAlgorithm).GetTypeInfo().Assembly,
                    typeof(Expression).GetTypeInfo().Assembly,
                    typeof(Graph).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = await FilesProvider.CreateAsync(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                     Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);

                Database.Register(db);
                await db.RepairIfInproperShutdown(null);

                await db.Start();

                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += () =>
                    {
                        Log.Informational("Device ready.");

                        this.arduino.pinMode(13, PinMode.OUTPUT);                            // Onboard LED.
                        this.arduino.digitalWrite(13, PinState.HIGH);

                        this.arduino.pinMode(8, PinMode.INPUT);                              // PIR sensor (motion detection).
                        PinState Pin8 = this.arduino.digitalRead(8);
                        this.lastMotion = Pin8 == PinState.HIGH;
                        MainPage.Instance.DigitalPinUpdated(8, Pin8);

                        this.arduino.pinMode(9, PinMode.OUTPUT);                            // Relay.
                        this.arduino.digitalWrite(9, 0);                                    // Relay set to 0

                        this.arduino.pinMode("A0", PinMode.ANALOG);                         // Light sensor.
                        MainPage.Instance.AnalogPinUpdated("A0", this.arduino.analogRead("A0"));

                        this.sampleTimer = new Timer(this.SampleValues, null, 1000 - DateTime.Now.Millisecond, 1000);
                    };

                    this.arduino.AnalogPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.AnalogPinUpdated(pin, value);
                    };

                    this.arduino.DigitalPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.DigitalPinUpdated(pin, value);

                        if (pin == 8)
                        {
                            this.lastMotion = (value == PinState.HIGH);
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }

                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                this.tokenAuthentication = new JwtAuthentication(this.deviceId, this.users, this.tokenFactory);

                this.httpServer = new HttpServer();
                //this.httpServer = new HttpServer(new LogSniffer());

                StorageFile File = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Root/favicon.ico"));

                string Root = File.Path;
                Root = Root.Substring(0, Root.Length - 11);
                this.httpServer.Register(new HttpFolderResource(string.Empty, Root, false, false, true, true));

                this.httpServer.Register("/", (req, resp) =>
                {
                    throw new TemporaryRedirectException("/Index.md");
                });

                this.httpServer.Register("/Momentary", (req, resp) =>
                {
                    resp.SetHeader("Cache-Control", "max-age=0, no-cache, no-store");

                    if (req.Header.Accept != null)
                    {
                        switch (req.Header.Accept.GetBestAlternative("text/xml", "application/xml", "application/json", "image/png", "image/jpeg", "image/webp"))
                        {
                        case "text/xml":
                        case "application/xml":
                            this.ReturnMomentaryAsXml(req, resp);
                            break;

                        case "application/json":
                            this.ReturnMomentaryAsJson(req, resp);
                            break;

                        case "image/png":
                            this.ReturnMomentaryAsPng(req, resp);
                            break;

                        case "image/jpg":
                            this.ReturnMomentaryAsJpg(req, resp);
                            break;

                        case "image/webp":
                            this.ReturnMomentaryAsWebp(req, resp);
                            break;

                        default:
                            throw new NotAcceptableException();
                        }
                    }
                    else
                    {
                        this.ReturnMomentaryAsXml(req, resp);
                    }

                    return(Task.CompletedTask);
                }, this.tokenAuthentication);

                this.httpServer.Register("/MomentaryPng", (req, resp) =>
                {
                    if (!req.Session.TryGetVariable("User", out Variable v) ||
                        !(v.ValueObject is IUser User))
                    {
                        throw new ForbiddenException();
                    }

                    resp.SetHeader("Cache-Control", "max-age=0, no-cache, no-store");
                    this.ReturnMomentaryAsPng(req, resp);

                    return(Task.CompletedTask);
                }, true, false, true);

                this.httpServer.Register("/Login", null, async(req, resp) =>
                {
                    if (!req.HasData || req.Session is null)
                    {
                        throw new BadRequestException();
                    }

                    object Obj = req.DecodeData();

                    if (!(Obj is Dictionary <string, string> Form) ||
                        !Form.TryGetValue("UserName", out string UserName) ||
                        !Form.TryGetValue("Password", out string Password))
                    {
                        throw new BadRequestException();
                    }

                    string From = null;

                    if (req.Session.TryGetVariable("from", out Variable v))
                    {
                        From = v.ValueObject as string;
                    }

                    if (string.IsNullOrEmpty(From))
                    {
                        From = "/Index.md";
                    }

                    IUser User = await this.Login(UserName, Password);
                    if (User != null)
                    {
                        Log.Informational("User logged in.", UserName, req.RemoteEndPoint, "LoginSuccessful", EventLevel.Minor);

                        req.Session["User"] = User;
                        req.Session.Remove("LoginError");

                        throw new SeeOtherException(From);
                    }
                    else
                    {
                        Log.Warning("Invalid login attempt.", UserName, req.RemoteEndPoint, "LoginFailure", EventLevel.Minor);
                        req.Session["LoginError"] = "Invalid login credentials provided.";
                    }

                    throw new SeeOtherException(req.Header.Referer.Value);
                }, true, false, true);

                this.httpServer.Register("/GetSessionToken", null, (req, resp) =>
                {
                    if (!req.Session.TryGetVariable("User", out Variable v) ||
                        !(v.ValueObject is IUser User))
                    {
                        throw new ForbiddenException();
                    }

                    string Token = this.tokenFactory.Create(new KeyValuePair <string, object>("sub", User.UserName));

                    resp.ContentType = JwtCodec.ContentType;
                    resp.Write(Token);

                    return(Task.CompletedTask);
                }, true, false, true);
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
示例#22
0
 private Task <FilesProvider> CreateDatabaseFile()
 {
     return(FilesProvider.CreateAsync(dataFolder, "Default", 8192, 10000, 8192, Encoding.UTF8, (int)Constants.Timeouts.Database.TotalMilliseconds, this.cryptoService.GetCustomKey));
 }
示例#23
0
        static int Main(string[] args)
        {
            try
            {
                Encoding Encoding          = Encoding.UTF8;
                string   ProgramDataFolder = null;
                string   OutputFileName    = null;
                string   XsltPath          = null;
                string   s;
                int      BlockSize     = 8192;
                int      BlobBlockSize = 8192;
                int      i             = 0;
                int      c             = args.Length;
                bool     Help          = false;
                bool     Encryption    = false;
                bool     Export        = false;

                while (i < c)
                {
                    s = args[i++].ToLower();

                    switch (s)
                    {
                    case "-d":
                        if (i >= c)
                        {
                            throw new Exception("Missing program data folder.");
                        }

                        if (string.IsNullOrEmpty(ProgramDataFolder))
                        {
                            ProgramDataFolder = args[i++];
                        }
                        else
                        {
                            throw new Exception("Only one program data folder allowed.");
                        }
                        break;

                    case "-o":
                        if (i >= c)
                        {
                            throw new Exception("Missing output file name.");
                        }

                        if (string.IsNullOrEmpty(OutputFileName))
                        {
                            OutputFileName = args[i++];
                        }
                        else
                        {
                            throw new Exception("Only one output file name allowed.");
                        }
                        break;

                    case "-bs":
                        if (i >= c)
                        {
                            throw new Exception("Block size missing.");
                        }

                        if (!int.TryParse(args[i++], out BlockSize))
                        {
                            throw new Exception("Invalid block size");
                        }

                        break;

                    case "-bbs":
                        if (i >= c)
                        {
                            throw new Exception("Blob Block size missing.");
                        }

                        if (!int.TryParse(args[i++], out BlobBlockSize))
                        {
                            throw new Exception("Invalid blob block size");
                        }

                        break;

                    case "-enc":
                        if (i >= c)
                        {
                            throw new Exception("Text encoding missing.");
                        }

                        Encoding = Encoding.GetEncoding(args[i++]);
                        break;

                    case "-t":
                        if (i >= c)
                        {
                            throw new Exception("XSLT transform missing.");
                        }

                        XsltPath = args[i++];
                        break;

                    case "-e":
                        Encryption = true;
                        break;

                    case "-x":
                        Export = true;
                        break;

                    case "-?":
                        Help = true;
                        break;

                    default:
                        throw new Exception("Unrecognized switch: " + s);
                    }
                }

                if (Help || c == 0)
                {
                    Console.Out.WriteLine("Analyzes an object database created by the Waher.Persistence.Files or");
                    Console.Out.WriteLine("Waher.Persistence.FilesLW libraries, such as the IoT Gateway database.");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("Command line switches:");
                    Console.Out.WriteLine();
                    Console.Out.WriteLine("-d APP_DATA_FOLDER    Points to the application data folder.");
                    Console.Out.WriteLine("-o OUTPUT_FILE        File name of report file.");
                    Console.Out.WriteLine("-e                    If encryption is used by the database.");
                    Console.Out.WriteLine("-bs BLOCK_SIZE        Block size, in bytes. Default=8192.");
                    Console.Out.WriteLine("-bbs BLOB_BLOCK_SIZE  BLOB block size, in bytes. Default=8192.");
                    Console.Out.WriteLine("-enc ENCODING         Text encoding. Default=UTF-8");
                    Console.Out.WriteLine("-t TRANSFORM_FILE     XSLT transform to use.");
                    Console.Out.WriteLine("-x                    Export contents of each collection.");
                    Console.Out.WriteLine("-?                    Help.");
                    return(0);
                }

                if (string.IsNullOrEmpty(ProgramDataFolder))
                {
                    throw new Exception("No program data folder set");
                }

                if (!Directory.Exists(ProgramDataFolder))
                {
                    throw new Exception("Program data folder does not exist.");
                }

                if (string.IsNullOrEmpty(OutputFileName))
                {
                    throw new Exception("No output filename specified.");
                }

                Types.Initialize(
                    typeof(Database).Assembly,
                    typeof(FilesProvider).Assembly,
                    typeof(ObjectSerializer).Assembly);

                using (FilesProvider FilesProvider = FilesProvider.CreateAsync(ProgramDataFolder, "Default", BlockSize, 10000, BlobBlockSize, Encoding, 3600000, Encryption, false).Result)
                {
                    Database.Register(FilesProvider);

                    using (StreamWriter f = File.CreateText(OutputFileName))
                    {
                        XmlWriterSettings Settings = new XmlWriterSettings()
                        {
                            Encoding                = Encoding,
                            Indent                  = true,
                            IndentChars             = "\t",
                            NewLineChars            = Console.Out.NewLine,
                            OmitXmlDeclaration      = false,
                            WriteEndDocumentOnClose = true
                        };

                        using (XmlWriter w = XmlWriter.Create(f, Settings))
                        {
                            if (string.IsNullOrEmpty(XsltPath))
                            {
                                i = ProgramDataFolder.LastIndexOf(Path.DirectorySeparatorChar);
                                if (i > 0)
                                {
                                    s = Path.Combine(ProgramDataFolder.Substring(0, i), "Transforms", "DbStatXmlToHtml.xslt");
                                    if (File.Exists(s))
                                    {
                                        XsltPath = s;
                                    }
                                }
                            }

                            Database.Analyze(w, XsltPath, ProgramDataFolder, Export);
                        }
                    }
                }

                return(0);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                return(-1);
            }
        }
示例#24
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(ObjectSerializer).GetTypeInfo().Assembly,                        // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = await FilesProvider.CreateAsync(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                     Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);

                Database.Register(db);
                await db.RepairIfInproperShutdown(null);

                await db.Start();

#if GPIO
                gpio = GpioController.GetDefault();
                if (gpio != null)
                {
                    if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
                        Status == GpioOpenStatus.PinOpened)
                    {
                        if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
                        {
                            this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);

                            bool LastOn = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.gpioPin.Write(LastOn ? GpioPinValue.High : GpioPinValue.Low);

                            await MainPage.Instance.OutputSet(LastOn);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", LastOn));
                        }
                        else
                        {
                            Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
                        }
                    }
                    else
                    {
                        Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
                    }
                }
#else
                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += async() =>
                    {
                        try
                        {
                            Log.Informational("Device ready.");

                            this.arduino.pinMode(13, PinMode.OUTPUT);                                // Onboard LED.
                            this.arduino.digitalWrite(13, PinState.HIGH);

                            this.arduino.pinMode(8, PinMode.INPUT);                                  // PIR sensor (motion detection).

                            this.arduino.pinMode(9, PinMode.OUTPUT);                                 // Relay.

                            bool LastOn = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.arduino.digitalWrite(9, LastOn ? PinState.HIGH : PinState.LOW);

                            await MainPage.Instance.OutputSet(LastOn);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", LastOn));

                            this.arduino.pinMode("A0", PinMode.ANALOG);                             // Light sensor.
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }
#endif
                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                this.mqttClient = new MqttClient("iot.eclipse.org", 8883, true, this.deviceId, string.Empty);
                //this.mqttClient = new MqttClient("iot.eclipse.org", 8883, true, this.deviceId, string.Empty, new LogSniffer());
                this.mqttClient.OnStateChanged += (sender, state) =>
                {
                    Log.Informational("MQTT client state changed: " + state.ToString());

                    if (state == MqttState.Connected)
                    {
                        this.mqttClient.SUBSCRIBE("Waher/MIOT/" + this.deviceId + "/Set/+", MqttQualityOfService.AtLeastOnce);
                    }

                    return(Task.CompletedTask);
                };

                this.mqttClient.OnContentReceived += async(sender, e) =>
                {
                    try
                    {
                        if (e.Topic.EndsWith("/On"))
                        {
                            string s = Encoding.UTF8.GetString(e.Data);
                            s = s.Substring(0, 1).ToUpper() + s.Substring(1).ToLower();

                            if (bool.TryParse(s, out bool On))
                            {
                                await this.SetOutput(On, "MQTT");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                };

                DateTime Now = DateTime.Now;
                this.reconnectionTimer = new Timer(this.CheckConnection, null, 120000 - Now.Millisecond - Now.Second * 1000, 60000);
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
示例#25
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(ObjectSerializer).GetTypeInfo().Assembly,                        // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = await FilesProvider.CreateAsync(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                     Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);

                Database.Register(db);
                await db.RepairIfInproperShutdown(null);

                await db.Start();

#if GPIO
                gpio = GpioController.GetDefault();
                if (gpio != null)
                {
                    if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
                        Status == GpioOpenStatus.PinOpened)
                    {
                        if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
                        {
                            this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);

                            bool LastOn = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.gpioPin.Write(LastOn ? GpioPinValue.High : GpioPinValue.Low);

                            await MainPage.Instance.OutputSet(LastOn);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", LastOn));
                        }
                        else
                        {
                            Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
                        }
                    }
                    else
                    {
                        Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
                    }
                }
#else
                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += async() =>
                    {
                        try
                        {
                            Log.Informational("Device ready.");

                            this.arduino.pinMode(13, PinMode.OUTPUT);                                // Onboard LED.
                            this.arduino.digitalWrite(13, PinState.HIGH);

                            this.arduino.pinMode(8, PinMode.INPUT);                                  // PIR sensor (motion detection).

                            this.arduino.pinMode(9, PinMode.OUTPUT);                                 // Relay.

                            bool LastOn = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.arduino.digitalWrite(9, LastOn ? PinState.HIGH : PinState.LOW);

                            await MainPage.Instance.OutputSet(LastOn);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", LastOn));

                            this.arduino.pinMode("A0", PinMode.ANALOG);                             // Light sensor.
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }
#endif
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
示例#26
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(ObjectSerializer).GetTypeInfo().Assembly,                        // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(XmppClient).GetTypeInfo().Assembly,
                    typeof(Waher.Content.Markdown.MarkdownDocument).GetTypeInfo().Assembly,
                    typeof(XML).GetTypeInfo().Assembly,
                    typeof(Waher.Script.Expression).GetTypeInfo().Assembly,
                    typeof(Waher.Script.Graphs.Graph).GetTypeInfo().Assembly,
                    typeof(Waher.Script.Persistence.SQL.Select).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = await FilesProvider.CreateAsync(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                     Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);

                Database.Register(db);
                await db.RepairIfInproperShutdown(null);

                await db.Start();

#if GPIO
                gpio = GpioController.GetDefault();
                if (gpio != null)
                {
                    if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
                        Status == GpioOpenStatus.PinOpened)
                    {
                        if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
                        {
                            this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.gpioPin.Write(this.output ? GpioPinValue.High : GpioPinValue.Low);

                            await MainPage.Instance.OutputSet(this.output);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output));
                        }
                        else
                        {
                            Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
                        }
                    }
                    else
                    {
                        Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
                    }
                }
#else
                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += async() =>
                    {
                        try
                        {
                            Log.Informational("Device ready.");

                            this.arduino.pinMode(13, PinMode.OUTPUT);                                // Onboard LED.
                            this.arduino.digitalWrite(13, PinState.HIGH);

                            this.arduino.pinMode(8, PinMode.INPUT);                                  // PIR sensor (motion detection).

                            this.arduino.pinMode(9, PinMode.OUTPUT);                                 // Relay.

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW);

                            await MainPage.Instance.OutputSet(this.output.Value);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output));

                            this.arduino.pinMode("A0", PinMode.ANALOG);                             // Light sensor.
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }
#endif
                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                string Host = await RuntimeSettings.GetAsync("XmppHost", "waher.se");

                int Port = (int)await RuntimeSettings.GetAsync("XmppPort", 5222);

                string UserName = await RuntimeSettings.GetAsync("XmppUserName", string.Empty);

                string PasswordHash = await RuntimeSettings.GetAsync("XmppPasswordHash", string.Empty);

                string PasswordHashMethod = await RuntimeSettings.GetAsync("XmppPasswordHashMethod", string.Empty);

                if (string.IsNullOrEmpty(Host) ||
                    Port <= 0 || Port > ushort.MaxValue ||
                    string.IsNullOrEmpty(UserName) ||
                    string.IsNullOrEmpty(PasswordHash) ||
                    string.IsNullOrEmpty(PasswordHashMethod))
                {
                    await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                async() => await this.ShowConnectionDialog(Host, Port, UserName));
                }
                else
                {
                    this.xmppClient = new XmppClient(Host, Port, UserName, PasswordHash, PasswordHashMethod, "en",
                                                     typeof(App).GetTypeInfo().Assembly) // Add "new LogSniffer()" to the end, to output communication to the log.
                    {
                        AllowCramMD5     = false,
                        AllowDigestMD5   = false,
                        AllowPlain       = false,
                        AllowScramSHA1   = true,
                        AllowScramSHA256 = true
                    };
                    this.xmppClient.OnStateChanged    += this.StateChanged;
                    this.xmppClient.OnConnectionError += this.ConnectionError;
                    this.AttachFeatures();

                    Log.Informational("Connecting to " + this.xmppClient.Host + ":" + this.xmppClient.Port.ToString());
                    this.xmppClient.Connect();
                }

                this.minuteTimer = new Timer((State) =>
                {
                    if (this.xmppClient != null &&
                        (this.xmppClient.State == XmppState.Error || this.xmppClient.State == XmppState.Offline))
                    {
                        this.xmppClient.Reconnect();
                    }
                }, null, 60000, 60000);
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
示例#27
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");
                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(ObjectSerializer).GetTypeInfo().Assembly,                        // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
                    typeof(App).GetTypeInfo().Assembly);

                db = await FilesProvider.CreateAsync(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                     Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);

                Database.Register(db);
                await db.RepairIfInproperShutdown(null);

                await db.Start();

                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += () =>
                    {
                        Log.Informational("Device ready.");

                        this.arduino.pinMode(13, PinMode.OUTPUT);                            // Onboard LED.
                        this.arduino.digitalWrite(13, PinState.HIGH);

                        this.arduino.pinMode(8, PinMode.INPUT);                              // PIR sensor (motion detection).
                        MainPage.Instance.DigitalPinUpdated(8, this.arduino.digitalRead(8));

                        this.arduino.pinMode(9, PinMode.OUTPUT);                            // Relay.
                        this.arduino.digitalWrite(9, 0);                                    // Relay set to 0

                        this.arduino.pinMode("A0", PinMode.ANALOG);                         // Light sensor.
                        MainPage.Instance.AnalogPinUpdated("A0", this.arduino.analogRead("A0"));

                        this.sampleTimer = new Timer(this.SampleValues, null, 1000 - DateTime.Now.Millisecond, 1000);
                    };

                    this.arduino.AnalogPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.AnalogPinUpdated(pin, value);
                    };

                    this.arduino.DigitalPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.DigitalPinUpdated(pin, value);
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
示例#28
0
        private static async Task <bool> Run(XmlDocument ModelXml, TaskCompletionSource <bool> Done,
                                             string SnifferFolder, string SnifferTransformFileName, string MarkdownOutputFileName, string XmlOutputFileName,
                                             string CommandLine, IEnumerable <string> Master, IEnumerable <string> Css, bool EmitDots,
                                             string ProgramDataFolder, int BlockSize, int BlobBlockSize, Encoding Encoding, bool Encryption)
        {
            using (FilesProvider DB = await FilesProvider.CreateAsync(ProgramDataFolder, "Default", BlockSize, 10000, BlobBlockSize, Encoding, 3600000, Encryption, false))
            {
                try
                {
                    Console.Out.WriteLine("Starting database...");
                    Database.Register(DB);
                    await DB.RepairIfInproperShutdown(null);

                    await Database.Clear("EventLog");

                    Log.Register(new PersistedEventLog(int.MaxValue));

                    Console.Out.WriteLine("Starting modules...");
                    await Types.StartAllModules(60000);

                    Console.Out.WriteLine("Running simulation...");
                    Model Model = (Model)await Factory.Create(ModelXml.DocumentElement, null, null);

                    Model.CommandLine              = CommandLine;
                    Model.SnifferFolder            = SnifferFolder;
                    Model.SnifferTransformFileName = SnifferTransformFileName;
                    Model.OnGetKey         += Model_OnGetKey;
                    Model.OnGetThreadCount += Model_OnGetThreadCount;

                    bool Result = await Model.Run(Done, EmitDots);

                    if (!string.IsNullOrEmpty(MarkdownOutputFileName))
                    {
                        Console.Out.WriteLine("Generating Markdown report: " + MarkdownOutputFileName);

                        string Folder = Path.GetDirectoryName(MarkdownOutputFileName);
                        if (!string.IsNullOrEmpty(Folder) && !Directory.Exists(Folder))
                        {
                            Directory.CreateDirectory(Folder);
                        }

                        using (StreamWriter Output = File.CreateText(MarkdownOutputFileName))
                        {
                            foreach (string s in Master)
                            {
                                Output.Write("Master: ");
                                Output.WriteLine(s);
                            }

                            foreach (string s in Css)
                            {
                                Output.Write("CSS: ");
                                Output.WriteLine(s);
                            }

                            await Model.ExportMarkdown(Output);
                        }
                    }

                    if (!string.IsNullOrEmpty(XmlOutputFileName))
                    {
                        Console.Out.WriteLine("Generating XML report: " + XmlOutputFileName);

                        XmlWriterSettings Settings = new XmlWriterSettings()
                        {
                            Encoding                = Encoding.UTF8,
                            Indent                  = true,
                            IndentChars             = "\t",
                            NewLineChars            = "\r\n",
                            NewLineOnAttributes     = false,
                            WriteEndDocumentOnClose = true
                        };

                        string Folder = Path.GetDirectoryName(XmlOutputFileName);
                        if (!string.IsNullOrEmpty(Folder) && !Directory.Exists(Folder))
                        {
                            Directory.CreateDirectory(Folder);
                        }

                        using (XmlWriter Output = XmlWriter.Create(XmlOutputFileName, Settings))
                        {
                            Output.WriteStartDocument();
                            Output.WriteStartElement("Report", "http://trustanchorgroup.com/Schema/ComSimReport.xsd");

                            await Model.ExportXml(Output);

                            Output.WriteEndElement();
                        }
                    }

                    return(Result);
                }
                finally
                {
                    Console.Out.WriteLine("Stopping modules...");
                    await Types.StopAllModules();

                    await DB.Flush();

                    Log.Terminate();
                }
            }
        }
示例#29
0
        public static async Task AssemblyInitialize(TestContext _)
        {
            Types.Initialize(typeof(Expression).Assembly,
                             typeof(Graphs.Graph).Assembly,
                             typeof(Graphs3D.Graph3D).Assembly,
                             typeof(Statistics.StatMath).Assembly,
                             typeof(XmlParser).Assembly,
                             typeof(System.Text.RegularExpressions.Regex).Assembly,
                             typeof(Persistence.SQL.Select).Assembly,
                             typeof(ScriptSqlTests).Assembly,
                             typeof(Database).Assembly,
                             typeof(FilesProvider).Assembly,
                             typeof(ObjectSerializer).Assembly);

            filesProvider = await FilesProvider.CreateAsync("Data", "Default", 8192, 10000, 8192, Encoding.UTF8, 10000);

            Database.Register(filesProvider);

            await Database.Clear("Orders");

            await Database.Clear("WebUsers");

            await Database.Insert(new Data.Order()
            {
                OrderID    = 1,
                CustomerID = 2,
                OrderDate  = new DateTime(2020, 04, 30)
            });

            await Database.Insert(new Data.Order()
            {
                OrderID    = 2,
                CustomerID = 3,
                OrderDate  = new DateTime(2020, 05, 1)
            });

            await Database.Insert(new Data.Order()
            {
                OrderID    = 3,
                CustomerID = 4,
                OrderDate  = new DateTime(2020, 05, 2)
            });

            await Database.Clear("Customers");

            await Database.Insert(new Data.Customer()
            {
                CustomerID   = 1,
                CustomerName = "P1",
                ContactName  = "CP1",
                Country      = "C1"
            });

            await Database.Insert(new Data.Customer()
            {
                CustomerID   = 2,
                CustomerName = "P2",
                ContactName  = "CP2",
                Country      = "C2"
            });

            await Database.Insert(new Data.Customer()
            {
                CustomerID   = 3,
                CustomerName = "P3",
                ContactName  = "CP3",
                Country      = "C2"
            });
        }