internal async Task SetOutput(bool On, string Actor) { #if GPIO if (this.gpioPin != null) { this.gpioPin.Write(On ? GpioPinValue.High : GpioPinValue.Low); #else if (this.arduino != null) { this.arduino.digitalWrite(9, On ? PinState.HIGH : PinState.LOW); #endif await RuntimeSettings.SetAsync("Actuator.Output", On); Log.Informational("Setting Control Parameter.", string.Empty, Actor ?? "Windows user", new KeyValuePair <string, object>("Output", On)); if (Actor != null) { await MainPage.Instance.OutputSet(On); } } } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); }
/// <summary> /// Saves the value of the resource, to persisted storage. /// </summary> /// <returns></returns> public override async Task WritePersistedValue() { if (this.value.HasValue) { await RuntimeSettings.SetAsync(this.Path, this.value.Value); } }
private async Task TestConnectionStateChanged(object Sender, XmppState State) { Log.Informational("Changing state: " + State.ToString()); switch (State) { case XmppState.Connected: await RuntimeSettings.SetAsync("XmppHost", this.xmppClient.Host); await RuntimeSettings.SetAsync("XmppPort", this.xmppClient.Port); await RuntimeSettings.SetAsync("XmppUserName", this.xmppClient.UserName); await RuntimeSettings.SetAsync("XmppPasswordHash", this.xmppClient.PasswordHash); await RuntimeSettings.SetAsync("XmppPasswordHashMethod", this.xmppClient.PasswordHashMethod); this.xmppClient.OnStateChanged -= this.TestConnectionStateChanged; this.xmppClient.OnStateChanged += this.StateChanged; await this.SetVCard(); await this.RegisterDevice(); break; case XmppState.Error: case XmppState.Offline: if (!(this.xmppClient is null)) { await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => await this.ShowConnectionDialog(this.xmppClient.Host, this.xmppClient.Port, this.xmppClient.UserName)); } break; } }
private async Task Unpack() { try { Log.Informational("Starting unpacking file.", new KeyValuePair <string, object>("FileName", this.zipFileName), new KeyValuePair <string, object>("Destination", this.programDataFolder)); ZipFile.ExtractToDirectory(this.zipFileName, this.programDataFolder); DateTime TP = File.GetLastWriteTime(this.zipFileName); await RuntimeSettings.SetAsync(this.zipFileName, TP); try { File.Delete(this.zipFileName); Log.Informational("File unpacked and deleted.", new KeyValuePair <string, object>("FileName", this.zipFileName)); } catch (Exception) { Log.Informational("File unpacked.", new KeyValuePair <string, object>("FileName", this.zipFileName)); } } catch (Exception ex) { Log.Critical(ex); } finally { this.initialized.Set(); } }
/// <summary> /// Saves the value of the resource, to persisted storage. /// </summary> /// <returns></returns> public override async Task WritePersistedValue() { if (this.value != null) { await RuntimeSettings.SetAsync(this.Path, Hashes.BinaryToString(this.value)); } }
internal async Task SetOutput(bool On, string Actor) { #if GPIO if (this.gpioPin != null) { this.gpioPin.Write(On ? GpioPinValue.High : GpioPinValue.Low); #else if (this.arduino != null) { this.arduino.digitalWrite(9, On ? PinState.HIGH : PinState.LOW); #endif await RuntimeSettings.SetAsync("Actuator.Output", On); this.output = On; this.sensorServer?.NewMomentaryValues(new BooleanField(ThingReference.Empty, DateTime.Now, "Output", On, FieldType.Momentary, FieldQoS.AutomaticReadout)); Log.Informational("Setting Control Parameter.", string.Empty, Actor ?? "Windows user", new KeyValuePair <string, object>("Output", On)); if (Actor != null) { await MainPage.Instance.OutputSet(On); } } }
private void RegisterDevice(MetaDataTag[] MetaInfo) { Console.WriteLine("Registering device."); this.registryClient.RegisterThing(true, MetaInfo, async(sender, e) => { try { if (e.Ok) { Console.WriteLine("Registration successful."); await RuntimeSettings.SetAsync("ThingRegistry.Location", true); this.FindFriends(MetaInfo); } else { Console.WriteLine("Registration failed."); await this.RegisterDevice(); } } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error While Registering"); } }, null); }
private void RegisterDevice(MetaDataTag[] MetaInfo) { Log.Informational("Registering device."); this.registryClient.RegisterThing(true, MetaInfo, async(sender, e) => { try { if (e.Ok) { Log.Informational("Registration successful."); await RuntimeSettings.SetAsync("ThingRegistry.Location", true); } else { Log.Error("Registration failed."); await this.RegisterDevice(); } } catch (Exception ex) { Log.Critical(ex); } }, null); }
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); }
public async Task SaveState(string key, TimeSpan state) { try { await RuntimeSettings.SetAsync(key, state); } catch (Exception e) { this.logService.LogException(e); } }
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); } }
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); } }
internal async Task SetOutput(bool On, string Actor) { #if GPIO if (this.gpioPin != null) { this.gpioPin.Write(On ? GpioPinValue.High : GpioPinValue.Low); #else if (this.arduino != null) { this.arduino.digitalWrite(9, On ? PinState.HIGH : PinState.LOW); #endif await RuntimeSettings.SetAsync("Actuator.Output", On); Log.Informational("Setting Control Parameter.", string.Empty, Actor ?? "Windows user", new KeyValuePair <string, object>("Output", On)); if (Actor != null) { await MainPage.Instance.OutputSet(On); } if (this.mqttClient != null && this.mqttClient.State == MqttState.Connected) { this.mqttClient.PUBLISH("Waher/MIOT/" + this.deviceId + "/On", MqttQualityOfService.AtLeastOnce, true, Encoding.UTF8.GetBytes(On.ToString())); StringBuilder Json = new StringBuilder(); Json.Append("{\"ts\":\""); Json.Append(DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")); Json.Append("\",\"on\":"); Json.Append(On ? "true" : "false"); Json.Append('}'); byte[] Data = Encoding.UTF8.GetBytes(Json.ToString()); this.mqttClient.PUBLISH("Waher/MIOT/" + this.deviceId + "/JSON", MqttQualityOfService.AtLeastOnce, true, Data); } } } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); }
/// <summary> /// Sets if a folder should be exported or not. /// </summary> /// <param name="FolderName">Name of folder.</param> /// <param name="Export">If folder should be exported or not.</param> public static async Task SetExportFolderAsync(string FolderName, bool Export) { string Key = "Export." + FolderName; lock (exportFolder) { if (exportFolder.TryGetValue(Key, out bool b) && b == Export) { return; } exportFolder[Key] = Export; } await RuntimeSettings.SetAsync(Key, Export); }
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(); }
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); } }
private async void TestConnectionStateChanged(object Sender, XmppState State) { try { this.StateChanged(Sender, State); switch (State) { case XmppState.Connected: await RuntimeSettings.SetAsync("XmppHost", this.xmppClient.Host); await RuntimeSettings.SetAsync("XmppPort", this.xmppClient.Port); await RuntimeSettings.SetAsync("XmppUserName", this.xmppClient.UserName); await RuntimeSettings.SetAsync("XmppPasswordHash", this.xmppClient.PasswordHash); await RuntimeSettings.SetAsync("XmppPasswordHashMethod", this.xmppClient.PasswordHashMethod); this.xmppClient.OnStateChanged -= this.TestConnectionStateChanged; this.xmppClient.OnStateChanged += this.StateChanged; this.AttachFeatures(); await this.SetVCard(); await this.RegisterDevice(); break; case XmppState.Error: case XmppState.Offline: await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => await this.ShowConnectionDialog(this.xmppClient.Host, this.xmppClient.Port, this.xmppClient.UserName)); break; } } catch (Exception ex) { Log.Critical(ex); } }
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); } }
private async Task UpdateRegistration(MetaDataTag[] MetaInfo, string OwnerJid) { if (string.IsNullOrEmpty(OwnerJid)) { await this.RegisterDevice(MetaInfo); } else { Log.Informational("Updating registration of device.", new KeyValuePair <string, object>("Owner", OwnerJid)); this.registryClient.UpdateThing(MetaInfo, async(sender, e) => { try { if (e.Disowned) { await RuntimeSettings.SetAsync("ThingRegistry.Owner", string.Empty); await this.RegisterDevice(MetaInfo); } else if (e.Ok) { Log.Informational("Registration update successful."); } else { Log.Error("Registration update failed."); await this.RegisterDevice(MetaInfo); } } catch (Exception ex) { Log.Critical(ex); } }, null); } }
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,
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); } } }
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()); } }
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()); } }
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); }
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()); }
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()); } }
/// <summary> /// Saves the value of the resource, to persisted storage. /// </summary> /// <returns></returns> public override async Task WritePersistedValue() { await RuntimeSettings.SetAsync(this.Path, this.StringValue); }
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()); } }
/// <summary> /// Set Timestamp of last backup. /// </summary> public static async Task SetLastBackupAsync(DateTime Value) { lastBackup = Value; await RuntimeSettings.SetAsync("LastBackup", Value); }
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()); } }