/// <summary>
        /// Annotates the property form.
        /// </summary>
        /// <param name="Form">Form being built.</param>
        public virtual async Task AnnotatePropertyForm(FormState Form)
        {
            if (this.provisioned && string.IsNullOrEmpty(this.owner))
            {
                string Uri = await RuntimeSettings.GetAsync("IoTDisco.KEY." + this.NodeId + "." + this.SourceId + "." + this.Partition, string.Empty);

                if (!string.IsNullOrEmpty(Uri))
                {
                    Language Language = await Translator.GetLanguageAsync(Form.LanguageCode);

                    Namespace Namespace = await Language.GetNamespaceAsync(typeof(MeteringTopology).Namespace);

                    Field Field;

                    Field = new TextMultiField(Form.Form, "IoTDiscoUri", await Namespace.GetStringAsync(94, "URI to claim node:"), false,
                                               new string[] { Uri }, null, await Namespace.GetStringAsync(95, "The owner can use this URI to claim ownership of the node."),
                                               null, null, null, false, true, false)
                    {
                        Priority = HeaderAttribute.DefaultPriority,
                        Ordinal  = Form.FieldOrdinal++
                    };

                    Form.Fields.Add(Field);

                    if (Form.PageByLabel.TryGetValue(await Namespace.GetStringAsync(18, "Provisioning"), out Page Page))
                    {
                        Page.Add(new FieldReference(Form.Form, Field.Var));
                    }
                }
            }
        }
Пример #2
0
        private async Task LoadAvatar()
        {
            this.includeAvatarInPresence = await RuntimeSettings.GetAsync("IncludeAvatarInPresence", true);

            this.localAvatar = await Database.FindFirstDeleteRest <Avatar>(
                new FilterFieldEqualTo("BareJid", this.client.BareJID.ToLower()));
        }
Пример #3
0
        private async Task RegisterDevice(MetaDataTag[] MetaInfo)
        {
            string Key = await RuntimeSettings.GetAsync("ThingRegistry.Key", string.Empty);

            if (string.IsNullOrEmpty(Key))
            {
                byte[] Bin = new byte[32];
                using (RandomNumberGenerator Rnd = RandomNumberGenerator.Create())
                {
                    Rnd.GetBytes(Bin);
                }

                Key = Hashes.BinaryToString(Bin);
                await RuntimeSettings.SetAsync("ThingRegistry.Key", Key);
            }

            int c = MetaInfo.Length;

            Array.Resize <MetaDataTag>(ref MetaInfo, c + 1);
            MetaInfo[c] = new MetaDataStringTag("KEY", Key);

            this.registryClient.RegisterThing(false, MetaInfo, async(sender, e) =>
            {
                try
                {
                    if (e.Ok)
                    {
                        await RuntimeSettings.SetAsync("ThingRegistry.Location", true);
                        await RuntimeSettings.SetAsync("ThingRegistry.Owner", e.OwnerJid);

                        if (string.IsNullOrEmpty(e.OwnerJid))
                        {
                            string ClaimUrl = registryClient.EncodeAsIoTDiscoURI(MetaInfo);
                            string FilePath = ApplicationData.Current.LocalFolder.Path + Path.DirectorySeparatorChar + "Actuator.iotdisco";

                            Log.Informational("Registration successful.");
                            Log.Informational(ClaimUrl, new KeyValuePair <string, object>("Path", FilePath));

                            File.WriteAllText(FilePath, ClaimUrl);
                        }
                        else
                        {
                            await RuntimeSettings.SetAsync("ThingRegistry.Key", string.Empty);
                            Log.Informational("Registration updated. Device has an owner.", new KeyValuePair <string, object>("Owner", e.OwnerJid));
                        }
                    }
                    else
                    {
                        Log.Error("Registration failed.");
                        await this.RegisterDevice();
                    }
                }
                catch (Exception ex)
                {
                    Log.Critical(ex);
                }
            }, null);
        }
Пример #4
0
        /// <summary>
        /// If automatic backups is activated
        /// </summary>
        public static async Task <bool> GetAutomaticBackupsAsync()
        {
            if (!automaticBackups.HasValue)
            {
                automaticBackups = await RuntimeSettings.GetAsync("AutomaticBackups", true);
            }

            return(automaticBackups.Value);
        }
Пример #5
0
        /// <summary>
        /// Loads the value of the resource, from persisted storage.
        /// </summary>
        public override async Task ReadPersistedValue()
        {
            this.value = await RuntimeSettings.GetAsync(this.Path, this.value.HasValue?this.value.Value : DateTime.MinValue);

            if (this.value == DateTime.MinValue)
            {
                this.value = null;
            }
        }
Пример #6
0
        /// <summary>
        /// For how many years the yearly backups are kept.
        /// </summary>
        public static async Task <long> GetKeepYearsAsync()
        {
            if (!backupKeepYears.HasValue)
            {
                backupKeepYears = await RuntimeSettings.GetAsync("BackupKeepYears", 3);
            }

            return(backupKeepYears.Value);
        }
Пример #7
0
        private static async Task XmppCredentialsUpdated(string XmppConfigFileName, XmppCredentials Credentials)
        {
            bool StorePassword = await RuntimeSettings.GetAsync("XmppStorePassword", false);

            if (!StorePassword)
            {
                await RuntimeSettings.SetAsync("XmppPasswordHash", Credentials.Password);

                await RuntimeSettings.SetAsync("XmppPasswordHashMethod", Credentials.PasswordType);
            }
        }
Пример #8
0
        private async Task RegisterDevice()
        {
            string ThingRegistryJid = await RuntimeSettings.GetAsync("ThingRegistry.JID", string.Empty);

            string ProvisioningJid = await RuntimeSettings.GetAsync("ProvisioningServer.JID", ThingRegistryJid);

            string OwnerJid = await RuntimeSettings.GetAsync("ThingRegistry.Owner", string.Empty);

            if (!string.IsNullOrEmpty(ThingRegistryJid) && !string.IsNullOrEmpty(ProvisioningJid))
            {
                this.UseProvisioningServer(ProvisioningJid, OwnerJid);
                await this.RegisterDevice(ThingRegistryJid, OwnerJid);
            }
            else
            {
                Log.Informational("Searching for Thing Registry and Provisioning Server.");

                this.xmppClient.SendServiceItemsDiscoveryRequest(this.xmppClient.Domain, (sender, e) =>
                {
                    foreach (Item Item in e.Items)
                    {
                        this.xmppClient.SendServiceDiscoveryRequest(Item.JID, async(sender2, e2) =>
                        {
                            try
                            {
                                Item Item2 = (Item)e2.State;

                                if (e2.HasFeature(ProvisioningClient.NamespaceProvisioningDevice))
                                {
                                    Log.Informational("Provisioning server found.", Item2.JID);
                                    this.UseProvisioningServer(Item2.JID, OwnerJid);
                                    await RuntimeSettings.SetAsync("ProvisioningServer.JID", Item2.JID);
                                }

                                if (e2.HasFeature(ThingRegistryClient.NamespaceDiscovery))
                                {
                                    Log.Informational("Thing registry found.", Item2.JID);

                                    await RuntimeSettings.SetAsync("ThingRegistry.JID", Item2.JID);
                                    await this.RegisterDevice(Item2.JID, OwnerJid);
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.Critical(ex);
                            }
                        }, Item);
                    }

                    return(Task.CompletedTask);
                }, null);
            }
        }
Пример #9
0
        /// <summary>
        /// Loads the value of the resource, from persisted storage.
        /// </summary>
        public override async Task ReadPersistedValue()
        {
            double d = await RuntimeSettings.GetAsync(this.Path, this.value.HasValue?(double)this.value : double.MinValue);

            if (d == double.MinValue)
            {
                this.value = null;
            }
            else
            {
                this.value = (float)d;
            }
        }
Пример #10
0
        /// <summary>
        /// Loads the value of the resource, from persisted storage.
        /// </summary>
        public override async Task ReadPersistedValue()
        {
            string s = this.value == null ? string.Empty :
                       await RuntimeSettings.GetAsync(this.Path, Hashes.BinaryToString(this.value));

            if (s == null)
            {
                this.value = null;
            }
            else
            {
                this.value = Hashes.StringToBinary(s);
            }
        }
Пример #11
0
        /// <summary>
        /// Loads the value of the resource, from persisted storage.
        /// </summary>
        public override async Task ReadPersistedValue()
        {
            string s = await RuntimeSettings.GetAsync(this.Path, this.StringValue);

            string[] Parts = s.Split(':');

            if (Parts.Length == 2 && ushort.TryParse(Parts[0], out ushort s1) &&
                ushort.TryParse(Parts[1], out ushort s2))
            {
                this.refId         = s1;
                this.refInstanceId = s2;
            }
            else
            {
                this.refId         = null;
                this.refInstanceId = null;
            }
        }
Пример #12
0
        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();
        }
Пример #13
0
        private async Task RegisterDevice()
        {
            string ThingRegistryJid = await RuntimeSettings.GetAsync("ThingRegistry.JID", string.Empty);

            if (!string.IsNullOrEmpty(ThingRegistryJid))
            {
                Console.WriteLine("Things Already Registered");
                await this.RegisterDevice(ThingRegistryJid);
            }
            else
            {
                Console.Write("Searching for Thing Registry.");

                this.xmppClient.SendServiceItemsDiscoveryRequest(this.xmppClient.Domain, (sender, e) =>
                {
                    foreach (Item Item in e.Items)
                    {
                        this.xmppClient.SendServiceDiscoveryRequest(Item.JID, async(sender2, e2) =>
                        {
                            try
                            {
                                Item Item2 = (Item)e2.State;

                                if (e2.HasFeature(ThingRegistryClient.NamespaceDiscovery))
                                {
                                    Console.WriteLine("Thing registry found.: " + Item2.JID);

                                    await RuntimeSettings.SetAsync("ThingRegistry.JID", Item2.JID);
                                    await this.RegisterDevice(Item2.JID);
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.ToString(), "Error Accessing Things Registry");
                            }
                        }, Item);
                    }

                    return(Task.CompletedTask);
                }, null);
            }
        }
Пример #14
0
        private async Task <RoomNode> GetRoomNode(string RoomId, string Domain)
        {
            RoomNode Result;
            string   Jid = RoomId + "@" + Domain;

            lock (this.roomByJid)
            {
                if (this.roomByJid.TryGetValue(Jid, out Result))
                {
                    return(Result);
                }
            }

            string Prefix   = this.mucClient.Client.BareJID + "." + Jid;
            string NickName = await RuntimeSettings.GetAsync(Prefix + ".Nick", string.Empty);

            string Password = await RuntimeSettings.GetAsync(Prefix + ".Pwd", string.Empty);

            Result = this.AddRoomNode(RoomId, Domain, NickName, Password, string.Empty, false);

            return(Result);
        }
Пример #15
0
        /// <summary>
        /// Gets if a folder should be exported or not.
        /// </summary>
        /// <param name="FolderName">Name of folder.</param>
        /// <returns>If folder should be exported.</returns>
        public static async Task <bool> GetExportFolderAsync(string FolderName)
        {
            string Key = "Export." + FolderName;
            bool   Result;

            lock (exportFolder)
            {
                if (exportFolder.TryGetValue(Key, out Result))
                {
                    return(Result);
                }
            }

            Result = await RuntimeSettings.GetAsync(Key, true);

            lock (exportFolder)
            {
                exportFolder[Key] = Result;
            }

            return(Result);
        }
Пример #16
0
        private async Task RegisterDevice()
        {
            string ThingRegistryJid = await RuntimeSettings.GetAsync("ThingRegistry.JID", string.Empty);

            if (!string.IsNullOrEmpty(ThingRegistryJid))
            {
                await this.RegisterDevice(ThingRegistryJid);
            }
            else
            {
                Log.Informational("Searching for Thing Registry.");

                this.xmppClient.SendServiceItemsDiscoveryRequest(this.xmppClient.Domain, (sender, e) =>
                {
                    foreach (Item Item in e.Items)
                    {
                        this.xmppClient.SendServiceDiscoveryRequest(Item.JID, async(sender2, e2) =>
                        {
                            try
                            {
                                Item Item2 = (Item)e2.State;

                                if (e2.HasFeature(ThingRegistryClient.NamespaceDiscovery))
                                {
                                    Log.Informational("Thing registry found.", Item2.JID);

                                    await RuntimeSettings.SetAsync("ThingRegistry.JID", Item2.JID);
                                    await this.RegisterDevice(Item2.JID);
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.Critical(ex);
                            }
                        }, Item);
                    }
                }, null);
            }
        }
Пример #17
0
 /// <summary>
 /// Loads the value of the resource, from persisted storage.
 /// </summary>
 public override async Task ReadPersistedValue()
 {
     this.value = await RuntimeSettings.GetAsync(this.Path, this.value);
 }
Пример #18
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,
Пример #19
0
        private async Task RegisterDevice(string RegistryJid)
        {
            if (this.registryClient == null || this.registryClient.ThingRegistryAddress != RegistryJid)
            {
                if (this.registryClient != null)
                {
                    this.registryClient.Dispose();
                    this.registryClient = null;
                }

                this.registryClient = new ThingRegistryClient(this.xmppClient, RegistryJid);
            }

            string             s;
            List <MetaDataTag> MetaInfo = new List <MetaDataTag>()
            {
                new MetaDataStringTag("CLASS", "Actuator"),
                new MetaDataStringTag("TYPE", "MIoT Actuator"),
                new MetaDataStringTag("MAN", "waher.se"),
                new MetaDataStringTag("MODEL", "MIoT ActuatorXmpp"),
                new MetaDataStringTag("PURL", "https://github.com/PeterWaher/MIoT"),
                new MetaDataStringTag("SN", this.deviceId),
                new MetaDataNumericTag("V", 1.0)
            };

            if (await RuntimeSettings.GetAsync("ThingRegistry.Location", false))
            {
                s = await RuntimeSettings.GetAsync("ThingRegistry.Country", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("COUNTRY", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Region", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("REGION", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.City", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("CITY", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Area", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("AREA", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Street", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("STREET", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.StreetNr", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("STREETNR", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Building", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("BLD", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Apartment", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("APT", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Room", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("ROOM", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Name", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("NAME", s));
                }

                this.UpdateRegistration(MetaInfo.ToArray());
            }
            else
            {
                try
                {
                    await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                    {
                        try
                        {
                            RegistrationDialog Dialog = new RegistrationDialog();

                            switch (await Dialog.ShowAsync())
                            {
                            case ContentDialogResult.Primary:
                                await RuntimeSettings.SetAsync("ThingRegistry.Country", s = Dialog.Reg_Country);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("COUNTRY", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.Region", s = Dialog.Reg_Region);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("REGION", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.City", s = Dialog.Reg_City);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("CITY", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.Area", s = Dialog.Reg_Area);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("AREA", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.Street", s = Dialog.Reg_Street);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("STREET", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.StreetNr", s = Dialog.Reg_StreetNr);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("STREETNR", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.Building", s = Dialog.Reg_Building);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("BLD", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.Apartment", s = Dialog.Reg_Apartment);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("APT", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.Room", s = Dialog.Reg_Room);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("ROOM", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.Name", s = Dialog.Name);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("NAME", s));
                                }

                                this.RegisterDevice(MetaInfo.ToArray());
                                break;

                            case ContentDialogResult.Secondary:
                                await this.RegisterDevice();
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    });
                }
                catch (Exception ex)
                {
                    Log.Critical(ex);
                }
            }
        }
Пример #20
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());
            }
        }
Пример #21
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(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(App).GetTypeInfo().Assembly);

                Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                    Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000));

#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 == 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
                    };
                    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());
            }
        }
Пример #22
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);
            }
Пример #23
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

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

                Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                    Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000));

                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo == 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());
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

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

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

                Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                    Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000));

#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 == 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);
                    }
                };

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

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

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

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
Пример #25
0
        private async Task <MetaDataTag[]> GetMetaData(MetaDataTag[] MetaData)
        {
            List <MetaDataTag> Result = new List <MetaDataTag>(MetaData);
            string             s;

            if (await RuntimeSettings.GetAsync("ThingRegistry.Location", false))
            {
                s = await RuntimeSettings.GetAsync("ThingRegistry.Country", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("COUNTRY", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Region", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("REGION", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.City", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("CITY", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Area", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("AREA", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Street", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("STREET", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.StreetNr", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("STREETNR", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Building", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("BLD", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Apartment", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("APT", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Room", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("ROOM", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Name", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("NAME", s));
                }
            }
            else
            {
                TaskCompletionSource <bool> UserInput = new TaskCompletionSource <bool>();

                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    try
                    {
                        RegistrationDialog Dialog = new RegistrationDialog();

                        switch (await Dialog.ShowAsync())
                        {
                        case ContentDialogResult.Primary:
                            await RuntimeSettings.SetAsync("ThingRegistry.Country", s = Dialog.Reg_Country);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("COUNTRY", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Region", s = Dialog.Reg_Region);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("REGION", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.City", s = Dialog.Reg_City);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("CITY", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Area", s = Dialog.Reg_Area);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("AREA", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Street", s = Dialog.Reg_Street);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("STREET", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.StreetNr", s = Dialog.Reg_StreetNr);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("STREETNR", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Building", s = Dialog.Reg_Building);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("BLD", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Apartment", s = Dialog.Reg_Apartment);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("APT", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Room", s = Dialog.Reg_Room);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("ROOM", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Name", s = Dialog.Name);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("NAME", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Location", true);

                            UserInput.SetResult(true);
                            break;

                        case ContentDialogResult.Secondary:
                            UserInput.SetResult(false);
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                });

                await UserInput.Task;
            }

            return(Result.ToArray());
        }
Пример #26
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);

                Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                    Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000));

#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();

                foreach (DeviceInformation DeviceInfo in Devices)
                {
                    if (DeviceInfo.IsEnabled && DeviceInfo.Name.StartsWith("Arduino"))
                    {
                        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);
                        break;
                    }
                }
#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 == null && req.Payload != null)
                        {
                            s = Encoding.UTF8.GetString(req.Payload);
                        }

                        if (s == 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,
                                                                 new int[] { PlainText.ContentFormatCode });

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

                this.lwm2mClient = new Lwm2mClient("MIoT:Actuator:" + this.deviceId, this.coapEndpoint,
                                                   new Lwm2mSecurityObject(),
                                                   new Lwm2mServerObject(),
                                                   new Lwm2mAccessControlObject(),
                                                   new Lwm2mDeviceObject("Waher Data AB", "ActuatorLwm2m", this.deviceId, "1.0", "Actuator", "1.0", "1.0"),
                                                   new DigitalOutput(this.digitalOutput0 = new DigitalOutputInstance(0, this.output.HasValue && this.output.Value, "Relay")),
                                                   new Actuation(this.actuation0         = new ActuationInstance(0, this.output.HasValue && this.output.Value, "Relay")));

                this.digitalOutput0.OnRemoteUpdate += async(Sender, e) =>
                {
                    try
                    {
                        await this.SetOutput(((DigitalOutputInstance)Sender).Value, e.Request.From.ToString());
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                };

                this.actuation0.OnRemoteUpdate += async(Sender, e) =>
                {
                    try
                    {
                        await this.SetOutput(((ActuationInstance)Sender).Value, e.Request.From.ToString());
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                };

                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());
            }
        }
Пример #27
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(ObjectSerializer).GetTypeInfo().Assembly,                        // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
                    typeof(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());
            }
        }
Пример #28
0
        /// <summary>
        /// Starts the gateway.
        /// </summary>
        /// <param name="ConsoleOutput">If console output is permitted.</param>
        public static bool Start(bool ConsoleOutput)
        {
            gatewayRunning = new Semaphore(1, 1, "Waher.IoTGateway.Running");
            if (!gatewayRunning.WaitOne(1000))
            {
                return(false);                // Is running in another process.
            }
            Semaphore StartingServer = new Semaphore(1, 1, "Waher.IoTGateway.Starting");

            if (!StartingServer.WaitOne(1000))
            {
                gatewayRunning.Release();
                gatewayRunning.Dispose();
                gatewayRunning = null;

                StartingServer.Dispose();
                return(false);                // Being started in another process.
            }

            try
            {
                Initialize();

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

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

                Log.Register(new XmlFileEventSink("XML File Event Sink",
                                                  appDataFolder + "Events" + Path.DirectorySeparatorChar + "Event Log %YEAR%-%MONTH%-%DAY%T%HOUR%.xml",
                                                  appDataFolder + "Transforms" + Path.DirectorySeparatorChar + "EventXmlToHtml.xslt", 7));

                Log.Informational("Server starting up.");

                beforeUninstallCommandNr = Gateway.RegisterServiceCommand(BeforeUninstall);

                rootFolder = appDataFolder + "Root" + Path.DirectorySeparatorChar;
                if (!Directory.Exists(rootFolder))
                {
                    appDataFolder = string.Empty;
                    rootFolder    = "Root" + Path.DirectorySeparatorChar;
                }

                Types.SetModuleParameter("AppData", appDataFolder);
                Types.SetModuleParameter("Root", rootFolder);

                scheduler = new Scheduler();
                rnd       = RandomNumberGenerator.Create();

                Task.Run(() => CodeContent.GraphViz.Init());

                XmlDocument Config = new XmlDocument();

                string GatewayConfigFileName = appDataFolder + "Gateway.config";
                if (!File.Exists(GatewayConfigFileName))
                {
                    GatewayConfigFileName = "Gateway.config";
                }

                Config.Load(GatewayConfigFileName);
                XSL.Validate("Gateway.config", Config, "GatewayConfiguration", "http://waher.se/Schema/GatewayConfiguration.xsd",
                             XSL.LoadSchema(typeof(Gateway).Namespace + ".Schema.GatewayConfiguration.xsd", typeof(Gateway).Assembly));

                domain = Config.DocumentElement["Domain"].InnerText;

                XmlElement DatabaseConfig = Config.DocumentElement["Database"];
                if (!CommonTypes.TryParse(DatabaseConfig.Attributes["encrypted"].Value, out bool Encrypted))
                {
                    Encrypted = true;
                }

                databaseProvider = new FilesProvider(appDataFolder + DatabaseConfig.Attributes["folder"].Value,
                                                     DatabaseConfig.Attributes["defaultCollectionName"].Value,
                                                     int.Parse(DatabaseConfig.Attributes["blockSize"].Value),
                                                     int.Parse(DatabaseConfig.Attributes["blocksInCache"].Value),
                                                     int.Parse(DatabaseConfig.Attributes["blobBlockSize"].Value), Encoding.UTF8,
                                                     int.Parse(DatabaseConfig.Attributes["timeoutMs"].Value),
                                                     Encrypted, false);
                Database.Register(databaseProvider);

                PersistedEventLog PersistedEventLog = new PersistedEventLog(7, new TimeSpan(4, 15, 0));
                Log.Register(PersistedEventLog);
                PersistedEventLog.Queue(new Event(EventType.Informational, "Server starting up.", string.Empty, string.Empty, string.Empty, EventLevel.Minor, string.Empty, string.Empty, string.Empty));

                xmppConfigFileName = Config.DocumentElement["XmppClient"].Attributes["configFileName"].Value;
                if (!File.Exists(xmppConfigFileName))
                {
                    xmppConfigFileName = appDataFolder + xmppConfigFileName;
                }

                if (ConsoleOutput)
                {
                    xmppConfiguration = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog(xmppConfigFileName,
                                                                                                  Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name.
                                                                                                  Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password.
                                                                                                  FormSignatureKey, FormSignatureSecret, typeof(Gateway).Assembly);
                }
                else if (File.Exists(xmppConfigFileName))
                {
                    xmppConfiguration = new SimpleXmppConfiguration(xmppConfigFileName);
                    RuntimeSettings.Set("XMPP.CONFIG", xmppConfiguration.ExportSimpleXmppConfiguration());
                }
                else
                {
                    string      XmppConfig = RuntimeSettings.Get("XMPP.CONFIG", string.Empty);
                    XmlDocument Doc        = new XmlDocument();
                    Doc.LoadXml(XmppConfig);
                    xmppConfiguration = new SimpleXmppConfiguration(Doc);
                }

                xmppClient = xmppConfiguration.GetClient("en", typeof(Gateway).Assembly, false);
                xmppClient.AllowRegistration(FormSignatureKey, FormSignatureSecret);
                xmppClient.OnValidateSender += XmppClient_OnValidateSender;
                Types.SetModuleParameter("XMPP", xmppClient);

                if (xmppConfiguration.Sniffer)
                {
                    ISniffer Sniffer;

                    if (ConsoleOutput)
                    {
                        Sniffer = new ConsoleOutSniffer(BinaryPresentationMethod.ByteCount, LineEnding.PadWithSpaces);
                        xmppClient.Add(Sniffer);
                    }

                    Sniffer = new XmlFileSniffer(appDataFolder + "XMPP" + Path.DirectorySeparatorChar +
                                                 "XMPP Log %YEAR%-%MONTH%-%DAY%T%HOUR%.xml",
                                                 appDataFolder + "Transforms" + Path.DirectorySeparatorChar + "SnifferXmlToHtml.xslt",
                                                 7, BinaryPresentationMethod.ByteCount);
                    xmppClient.Add(Sniffer);
                }

                if (!string.IsNullOrEmpty(xmppConfiguration.Events))
                {
                    Log.Register(new XmppEventSink("XMPP Event Sink", xmppClient, xmppConfiguration.Events, false));
                }

                if (!string.IsNullOrEmpty(xmppConfiguration.ThingRegistry))
                {
                    thingRegistryClient           = new ThingRegistryClient(xmppClient, xmppConfiguration.ThingRegistry);
                    thingRegistryClient.Claimed  += ThingRegistryClient_Claimed;
                    thingRegistryClient.Disowned += ThingRegistryClient_Disowned;
                    thingRegistryClient.Removed  += ThingRegistryClient_Removed;
                }

                if (!string.IsNullOrEmpty(xmppConfiguration.Provisioning))
                {
                    provisioningClient = new ProvisioningClient(xmppClient, xmppConfiguration.Provisioning);
                }

                DateTime Now      = DateTime.Now;
                int      MsToNext = 60000 - (Now.Second * 1000 + Now.Millisecond);

                connectionTimer                   = new Timer(CheckConnection, null, MsToNext, 60000);
                xmppClient.OnStateChanged        += XmppClient_OnStateChanged;
                xmppClient.OnPresenceSubscribe   += XmppClient_OnPresenceSubscribe;
                xmppClient.OnPresenceUnsubscribe += XmppClient_OnPresenceUnsubscribe;
                xmppClient.OnRosterItemUpdated   += XmppClient_OnRosterItemUpdated;

                ibbClient = new Networking.XMPP.InBandBytestreams.IbbClient(xmppClient, MaxChunkSize);
                Types.SetModuleParameter("IBB", ibbClient);

                socksProxy = new Networking.XMPP.P2P.SOCKS5.Socks5Proxy(xmppClient);
                Types.SetModuleParameter("SOCKS5", socksProxy);

                string CertificateLocalFileName = Config.DocumentElement["Certificate"].Attributes["configFileName"].Value;
                string CertificateFileName;
                string CertificateXml;
                string CertificatePassword;
                byte[] CertificateRaw;

                try
                {
                    CertificateRaw      = Convert.FromBase64String(RuntimeSettings.Get("CERTIFICATE.BASE64", string.Empty));
                    CertificatePassword = RuntimeSettings.Get("CERTIFICATE.PWD", string.Empty);

                    certificate = new X509Certificate2(CertificateRaw, CertificatePassword);
                }
                catch (Exception)
                {
                    certificate = null;
                }

                if (File.Exists(CertificateFileName = appDataFolder + CertificateLocalFileName))
                {
                    CertificateXml = File.ReadAllText(CertificateFileName);
                }
                else if (File.Exists(CertificateFileName = CertificateLocalFileName) && certificate == null)
                {
                    CertificateXml = File.ReadAllText(CertificateFileName);
                }
                else
                {
                    CertificateFileName = null;
                    CertificateXml      = null;
                }

                if (CertificateXml != null)
                {
                    XmlDocument CertificateConfig = new XmlDocument();
                    CertificateConfig.LoadXml(CertificateXml);

                    XSL.Validate(CertificateLocalFileName, CertificateConfig, "CertificateConfiguration", "http://waher.se/Schema/CertificateConfiguration.xsd",
                                 XSL.LoadSchema(typeof(Gateway).Namespace + ".Schema.CertificateConfiguration.xsd", typeof(Gateway).Assembly));

                    CertificateLocalFileName = CertificateConfig.DocumentElement["FileName"].InnerText;

                    if (File.Exists(appDataFolder + CertificateLocalFileName))
                    {
                        CertificateLocalFileName = appDataFolder + CertificateLocalFileName;
                    }

                    CertificateRaw      = File.ReadAllBytes(CertificateLocalFileName);
                    CertificatePassword = CertificateConfig.DocumentElement["Password"].InnerText;

                    certificate = new X509Certificate2(CertificateRaw, CertificatePassword);

                    RuntimeSettings.Set("CERTIFICATE.BASE64", Convert.ToBase64String(CertificateRaw));
                    RuntimeSettings.Set("CERTIFICATE.PWD", CertificatePassword);

                    if (CertificateLocalFileName != "certificate.pfx" || CertificatePassword != "testexamplecom")
                    {
                        try
                        {
                            File.Delete(CertificateLocalFileName);
                        }
                        catch (Exception)
                        {
                            Log.Warning("Unable to delete " + CertificateLocalFileName + " after importing it into the encrypted database.");
                        }

                        try
                        {
                            File.Delete(CertificateFileName);
                        }
                        catch (Exception)
                        {
                            Log.Warning("Unable to delete " + CertificateFileName + " after importing it into the encrypted database.");
                        }
                    }
                }

                foreach (XmlNode N in Config.DocumentElement["Ports"].ChildNodes)
                {
                    if (N.LocalName == "Port")
                    {
                        XmlElement E        = (XmlElement)N;
                        string     Protocol = XML.Attribute(E, "protocol");
                        if (!string.IsNullOrEmpty(Protocol) && int.TryParse(E.InnerText, out int Port))
                        {
                            ports.AddLast(new KeyValuePair <string, int>(Protocol, Port));
                        }
                    }
                }

                webServer = new HttpServer(GetConfigPorts("HTTP"), GetConfigPorts("HTTPS"), certificate);
                Types.SetModuleParameter("HTTP", webServer);

                StringBuilder sb = new StringBuilder();

                foreach (int Port in webServer.OpenPorts)
                {
                    sb.AppendLine(Port.ToString());
                }

                try
                {
                    File.WriteAllText(appDataFolder + "Ports.txt", sb.ToString());
                }
                catch (Exception ex)
                {
                    Log.Critical(ex);
                }

                HttpFolderResource HttpFolderResource;
                HttpxProxy         HttpxProxy;

                webServer.Register(new HttpFolderResource("/Graphics", "Graphics", false, false, true, false));                      // TODO: Add authentication mechanisms for PUT & DELETE.
                webServer.Register(new HttpFolderResource("/highlight", "Highlight", false, false, true, false));                    // Syntax highlighting library, provided by http://highlightjs.org
                webServer.Register(HttpFolderResource = new HttpFolderResource(string.Empty, rootFolder, false, false, true, true)); // TODO: Add authentication mechanisms for PUT & DELETE.
                webServer.Register(HttpxProxy         = new HttpxProxy("/HttpxProxy", xmppClient, MaxChunkSize));
                webServer.Register("/", (req, resp) =>
                {
                    throw new TemporaryRedirectException(Config.DocumentElement["DefaultPage"].InnerText);
                });
                webServer.Register(clientEvents = new ClientEvents());

                HttpFolderResource.AllowTypeConversion();
                MarkdownToHtmlConverter.EmojiSource = Emoji1_24x24;

                XmlElement FileFolders = Config.DocumentElement["FileFolders"];
                if (FileFolders != null)
                {
                    foreach (XmlNode N in FileFolders.ChildNodes)
                    {
                        if (N is XmlElement E && E.LocalName == "FileFolder")
                        {
                            string WebFolder  = XML.Attribute(E, "webFolder");
                            string FolderPath = XML.Attribute(E, "folderPath");

                            webServer.Register(new HttpFolderResource(WebFolder, FolderPath, false, false, true, true));
                        }
                    }
                }

                httpxServer = new HttpxServer(xmppClient, webServer, MaxChunkSize);
                Types.SetModuleParameter("HTTPX", HttpxProxy);
                Types.SetModuleParameter("HTTPXS", httpxServer);

                HttpxProxy.IbbClient  = ibbClient;
                httpxServer.IbbClient = ibbClient;

                HttpxProxy.Socks5Proxy  = socksProxy;
                httpxServer.Socks5Proxy = socksProxy;

                if (xmppConfiguration.Sniffer)
                {
                    ISniffer Sniffer;

                    Sniffer = new XmlFileSniffer(appDataFolder + "HTTP" + Path.DirectorySeparatorChar +
                                                 "HTTP Log %YEAR%-%MONTH%-%DAY%T%HOUR%.xml",
                                                 appDataFolder + "Transforms" + Path.DirectorySeparatorChar + "SnifferXmlToHtml.xslt",
                                                 7, BinaryPresentationMethod.ByteCount);
                    webServer.Add(Sniffer);
                }

                coapEndpoint = new CoapEndpoint();
                Types.SetModuleParameter("CoAP", coapEndpoint);

                concentratorServer = new ConcentratorServer(xmppClient, provisioningClient, new MeteringTopology());
                Types.SetModuleParameter("Concentrator", concentratorServer);
                Types.SetModuleParameter("Sensor", concentratorServer.SensorServer);
                Types.SetModuleParameter("Control", concentratorServer.ControlServer);
            }
            catch (Exception ex)
            {
                Log.Critical(ex);

                gatewayRunning.Release();
                gatewayRunning.Dispose();
                gatewayRunning = null;

                StartingServer.Release();
                StartingServer.Dispose();

                ExceptionDispatchInfo.Capture(ex).Throw();
            }

            Task.Run(async() =>
            {
                try
                {
                    try
                    {
                        string BinaryFolder    = AppDomain.CurrentDomain.BaseDirectory;
                        string[] LanguageFiles = Directory.GetFiles(BinaryFolder, "*.lng", SearchOption.AllDirectories);
                        string FileName;

                        if (LanguageFiles.Length > 0)
                        {
                            XmlSchema Schema = XSL.LoadSchema(Translator.SchemaResource, typeof(Translator).Assembly);

                            foreach (string LanguageFile in LanguageFiles)
                            {
                                try
                                {
                                    FileName = LanguageFile;
                                    if (FileName.StartsWith(BinaryFolder))
                                    {
                                        FileName = FileName.Substring(BinaryFolder.Length);
                                    }

                                    DateTime LastWriteTime    = File.GetLastWriteTime(LanguageFile);
                                    DateTime LastImportedTime = await RuntimeSettings.GetAsync(FileName, DateTime.MinValue);

                                    if (LastWriteTime > LastImportedTime)
                                    {
                                        Log.Informational("Importing language file.", FileName);

                                        string Xml      = File.ReadAllText(LanguageFile);
                                        XmlDocument Doc = new XmlDocument();
                                        Doc.LoadXml(Xml);

                                        XSL.Validate(FileName, Doc, Translator.SchemaRoot, Translator.SchemaNamespace, Schema);

                                        using (XmlReader r = new XmlNodeReader(Doc))
                                        {
                                            await Translator.ImportAsync(r);
                                        }

                                        RuntimeSettings.Set(FileName, LastWriteTime);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log.Critical(ex, LanguageFile);
                                }
                            }
                        }

                        Types.StartAllModules(int.MaxValue);
                    }
                    finally
                    {
                        StartingServer.Release();
                        StartingServer.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    Log.Critical(ex);
                }
                finally
                {
                    xmppClient.Connect();
                }
            });

            return(true);
        }