Example #1
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();
        }
Example #2
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);
            }
        }
        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();
        }
Example #4
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(ImageCodec).GetTypeInfo().Assembly,
                    typeof(MarkdownDocument).GetTypeInfo().Assembly,
                    typeof(MarkdownToHtmlConverter).GetTypeInfo().Assembly,
                    typeof(IJwsAlgorithm).GetTypeInfo().Assembly,
                    typeof(Expression).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = new FilesProvider(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);

                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"))
                        {
                        case "text/xml":
                        case "application/xml":
                            this.ReturnMomentaryAsXml(req, resp);
                            break;

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

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

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

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

                        if (!(req.DecodeData() is string s) || !CommonTypes.TryParse(s, out bool OutputValue))
                        {
                            throw new BadRequestException();
                        }

                        if (req.Header.Accept != null)
                        {
                            switch (req.Header.Accept.GetBestAlternative("text/xml", "application/xml", "application/json"))
                            {
                            case "text/xml":
                            case "application/xml":
                                await this.SetOutput(OutputValue, req.RemoteEndPoint);
                                this.ReturnMomentaryAsXml(req, resp);
                                break;

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

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

                        await resp.SendResponse();
                    }
                    catch (Exception ex)
                    {
                        await resp.SendResponse(ex);
                    }
                }, false, this.tokenAuthentication);

                this.httpServer.Register("/Login", null, (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 = 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);
            }
Example #5
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();
                }
            }
        }
Example #6
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 = new FilesProvider(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());
            }
        }
Example #7
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());
            }
        }
Example #8
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();
                }
            }
        }
Example #9
0
        public MainWindow()
        {
            if (currentInstance is null)
            {
                currentInstance = this;
            }

            Types.Initialize(typeof(MainWindow).Assembly,
                             typeof(Content.InternetContent).Assembly,
                             typeof(Content.Images.ImageCodec).Assembly,
                             typeof(Content.Markdown.MarkdownDocument).Assembly,
                             typeof(XML).Assembly,
                             typeof(Content.Xsl.XSL).Assembly,
                             typeof(SensorData).Assembly,
                             typeof(Networking.XMPP.BOSH.HttpBinding).Assembly,
                             typeof(Networking.XMPP.P2P.EndpointSecurity).Assembly,
                             typeof(Networking.XMPP.Provisioning.ProvisioningClient).Assembly,
                             typeof(Networking.XMPP.WebSocket.WebSocketBinding).Assembly,
                             typeof(Database).Assembly,
                             typeof(FilesProvider).Assembly,
                             typeof(Script.Expression).Assembly,
                             typeof(Script.Content.Functions.Encoding.Decode).Assembly,
                             typeof(Script.Graphs.Graph).Assembly,
                             typeof(Script.Fractals.FractalGraph).Assembly,
                             typeof(Script.Persistence.Functions.FindObjects).Assembly,
                             typeof(Script.Statistics.Functions.Beta).Assembly,
                             typeof(Security.IUser).Assembly,
                             typeof(Security.EllipticCurves.CurvePrimeField).Assembly);

            appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            if (!appDataFolder.EndsWith(new string(Path.DirectorySeparatorChar, 1)))
            {
                appDataFolder += Path.DirectorySeparatorChar;
            }

            appDataFolder += "IoT Client" + Path.DirectorySeparatorChar;

            if (!Directory.Exists(appDataFolder))
            {
                Directory.CreateDirectory(appDataFolder);
            }

            Task.Run(() =>
            {
                try
                {
                    databaseProvider = new FilesProvider(appDataFolder + "Data", "Default", 8192, 10000, 8192, Encoding.UTF8, 3600000);
                    databaseProvider.RepairIfInproperShutdown(appDataFolder + "Transforms" + Path.DirectorySeparatorChar + "DbStatXmlToHtml.xslt").Wait();
                    databaseProvider.Start().Wait();
                    Database.Register(databaseProvider);

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

                    ChatView.InitEmojis();
                }
                catch (Exception ex)
                {
                    ex = Log.UnnestException(ex);
                    ErrorBox(ex.Message);
                }
            });

            InitializeComponent();

            this.MainView.Load(this);
        }
Example #10
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 = new FilesProvider(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.PublishMotion(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.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());
                    return(Task.CompletedTask);
                };
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
Example #11
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());
            }
        }
Example #12
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 = new FilesProvider(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();

				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.xmppClient.OnRosterItemAdded += XmppClient_OnRosterItemAdded;
					this.xmppClient.OnRosterItemUpdated += XmppClient_OnRosterItemUpdated;
					this.xmppClient.OnRosterItemRemoved += XmppClient_OnRosterItemRemoved;
					this.AttachFeatures();

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

				this.secondTimer = new Timer(SecondTimerCallback, null, 1000, 1000);
			}
			catch (Exception ex)
			{
				Log.Emergency(ex);

				MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
				await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
					async () => await Dialog.ShowAsync());
			}
		}
Example #13
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());
            }
        }
Example #14
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());
            }
        }
Example #15
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(ICoapContentFormat).GetTypeInfo().Assembly,
                    typeof(IDtlsCredentials).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = new FilesProvider(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.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.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));
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

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

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    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 = new FilesProvider(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);

                            this.digitalOutput0?.Set(this.output.Value);
                            this.actuation0?.Set(this.output.Value);
                            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);

                            this.digitalOutput0?.Set(this.output.Value);
                            this.actuation0?.Set(this.output.Value);
                            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,
Example #17
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());
            }
        }