/// <summary> /// Gets XMPP credentials for the instance. /// </summary> /// <returns>XMPP Credentials</returns> protected async override Task <XmppCredentials> GetInstanceCredentials() { XmppCredentials Result = await base.GetInstanceCredentials(); Result.UriEndpoint = this.endpoint; return(Result); }
/// <summary> /// Gets connection credentials. /// </summary> /// <returns>Connection credentials.</returns> public XmppCredentials GetCredentials() { XmppCredentials Credentials = new XmppCredentials() { Host = this.host, Port = this.port, Account = this.account, Password = this.password, PasswordType = this.passwordType, TrustServer = this.trustServer, Sniffer = this.sniffer, AllowEncryption = true, AllowCramMD5 = this.allowInsecureMechanisms, AllowDigestMD5 = this.allowInsecureMechanisms, AllowPlain = this.allowInsecureMechanisms, AllowRegistration = this.createAccount, AllowScramSHA1 = true, RequestRosterOnStartup = true }; if (this.createAccount && clp.TryGetValue(this.host, out KeyValuePair <string, string> P)) { Credentials.FormSignatureKey = P.Key; Credentials.FormSignatureSecret = P.Value; } switch (this.transportMethod) { case XmppTransportMethod.BOSH: Credentials.HttpEndpoint = this.boshUrl; break; } return(Credentials); }
/// <summary> /// Initializes an instance of an actor. /// </summary> public override async Task InitializeInstance() { this.xmppCredentials = await this.GetInstanceCredentials(); this.sniffer = this.Model.GetSniffer(this.userName); if (this.sniffer is null) { this.client = new XmppClient(this.xmppCredentials, "en", typeof(XmppActor).GetTypeInfo().Assembly); } else { this.client = new XmppClient(this.xmppCredentials, "en", typeof(XmppActor).GetTypeInfo().Assembly, this.sniffer); } this.client.OnStateChanged += this.Client_OnStateChanged; this.client.OnChatMessage += Client_OnChatMessage; this.client.OnConnectionError += Client_OnConnectionError; this.client.OnError += Client_OnError; this.client.OnErrorMessage += Client_OnErrorMessage; this.client.OnGroupChatMessage += Client_OnGroupChatMessage; this.client.OnHeadlineMessage += Client_OnHeadlineMessage; this.client.OnNormalMessage += Client_OnNormalMessage; this.client.OnPresence += Client_OnPresence; this.client.OnPresenceSubscribe += Client_OnPresenceSubscribe; this.client.OnRosterItemAdded += Client_OnRosterItemAdded; this.client.OnRosterItemRemoved += Client_OnRosterItemRemoved; this.client.OnRosterItemUpdated += Client_OnRosterItemUpdated; this.client.CustomPresenceXml += Client_CustomPresenceXml; if (this.Parent is IActor ParentActor) { foreach (ISimulationNode Node in ParentActor.Children) { if (Node is HandlerNode HandlerNode) { HandlerNode.RegisterHandlers(this, this.client); } if (Node is Extensions.IXmppExtension Extension) { await Extension.Add(this, Client); } } } this.connected = new TaskCompletionSource <bool>(); if (this.alwaysConnected) { this.client.Connect(this.domain); if (this.xmppCredentials.AllowRegistration && !(await this.connected.Task)) { throw new Exception("Unable to create account for " + this.userName + "@" + this.domain); } } }
private static Task <XmppCredentials> GetXmppClientCredentials(string XmppConfigFileName) { XmppCredentials Result = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog(XmppConfigFileName, Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name. Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password. typeof(Gateway).Assembly); return(Task.FromResult <XmppCredentials>(Result)); }
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); } }
/// <summary> /// Gets a new XMPP client using the settings provided in the current object. /// </summary> /// <param name="Credentials">XMPP Client credentials.</param> /// <param name="Language">Primary language.</param> /// <param name="AppAssembly">Application assembly.</param> /// <param name="Connect">If a connection should be initiated directly.</param> /// <returns>XMPP Client object.</returns> public static XmppClient GetClient(XmppCredentials Credentials, string Language, Assembly AppAssembly, bool Connect) { XmppClient Client = new XmppClient(Credentials, Language, AppAssembly); if (Connect) { Client.Connect(); } return(Client); }
public void Connect(string user, string password, string domain) { XmppCredentials credentials = new XmppCredentials(); credentials.Password = password; credentials.Host = domain; credentials.Account = user; credentials.Port = 5222; XmppClient client = new XmppClient(credentials, "en", null, null); client.Connect(); Console.WriteLine("Conectado..."); }
/// <summary> /// Gets XMPP credentials for the instance. /// </summary> /// <returns>XMPP Credentials</returns> protected async virtual Task <XmppCredentials> GetInstanceCredentials() { this.credentials = await Database.FindFirstIgnoreRest <AccountCredentials>(new FilterAnd( new FilterFieldEqualTo("Domain", this.domain), new FilterFieldEqualTo("UserName", this.userName))); if (!(this.credentials is null) && string.IsNullOrEmpty(this.credentials.PasswordHash)) { await Database.Delete(this.credentials); this.credentials = null; } XmppCredentials Result = new XmppCredentials() { Account = this.userName, AllowCramMD5 = this.allowCramMD5, AllowDigestMD5 = this.allowDigestMD5, AllowEncryption = this.allowEncryption, AllowPlain = this.allowPlain, AllowRegistration = false, AllowScramSHA1 = this.allowScramSHA1, AllowScramSHA256 = this.allowScramSHA256, Host = this.host, Port = this.port.Value, RequestRosterOnStartup = this.requestRosterOnStartup, TrustServer = this.trustServer }; if (this.credentials is null) { Result.AllowRegistration = true; Result.FormSignatureKey = await this.Model.GetKey(this.apiKey, string.Empty); Result.FormSignatureSecret = await this.Model.GetKey(this.secret, string.Empty); Result.Password = Convert.ToBase64String(this.Model.GetRandomBytes(32)); } else { Result.Password = this.credentials.PasswordHash; Result.PasswordType = this.credentials.PasswordHashMethod; } return(Result); }
private async void StartActuator() { try { Log.Informational("Starting application."); XmppCredentials Credentials = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config", Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name. Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password. typeof(App).GetTypeInfo().Assembly); Log.Informational("Connecting to XMPP server."); xmppClient = new XmppClient(Credentials, "en", typeof(App).GetTypeInfo().Assembly); if (Credentials.Sniffer && MainPage.Sniffer != null) { xmppClient.Add(MainPage.Sniffer); } if (!string.IsNullOrEmpty(Credentials.Events)) { Log.Register(new XmppEventSink("XMPP Event Sink", xmppClient, Credentials.Events, false)); } if (!string.IsNullOrEmpty(Credentials.ThingRegistry)) { thingRegistryClient = new ThingRegistryClient(xmppClient, Credentials.ThingRegistry); thingRegistryClient.Claimed += (sender, e) => { ownerJid = e.JID; Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair <string, object>("Public", e.IsPublic)); this.RaiseOwnershipChanged(); }; thingRegistryClient.Disowned += (sender, e) => { Log.Informational("Thing has been disowned.", ownerJid); ownerJid = string.Empty; this.Register(); // Will call this.OwnershipChanged() after successful registration. }; thingRegistryClient.Removed += (sender, e) => { Log.Informational("Thing has been removed from the public registry.", ownerJid); }; } if (!string.IsNullOrEmpty(Credentials.Provisioning)) { provisioningClient = new ProvisioningClient(xmppClient, Credentials.Provisioning); } Timer ConnectionTimer = new Timer((P) => { if (xmppClient.State == XmppState.Offline || xmppClient.State == XmppState.Error || xmppClient.State == XmppState.Authenticating) { try { Log.Informational("Reconnecting."); xmppClient.Reconnect(); } catch (Exception ex) { Log.Critical(ex); } } }, null, 60000, 60000); xmppClient.OnStateChanged += (sender, NewState) => { Log.Informational(NewState.ToString()); switch (NewState) { case XmppState.Connected: connected = true; if (!registered && thingRegistryClient != null) { Register(); } break; case XmppState.Offline: immediateReconnect = connected; connected = false; if (immediateReconnect) { xmppClient.Reconnect(); } break; } }; xmppClient.OnPresenceSubscribe += (sender, e) => { Log.Informational("Subscription request received from " + e.From + "."); e.Accept(); // TODO: Provisioning RosterItem Item = xmppClient.GetRosterItem(e.FromBareJID); if (Item == null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From) { xmppClient.RequestPresenceSubscription(e.FromBareJID); } xmppClient.SetPresence(Availability.Chat); }; xmppClient.OnPresenceUnsubscribe += (sender, e) => { Log.Informational("Unsubscription request received from " + e.From + "."); e.Accept(); }; xmppClient.OnRosterItemUpdated += (sender, e) => { if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe) { xmppClient.RemoveRosterItem(e.BareJid); } }; bool SwitchOn = false; sensorServer = new SensorServer(xmppClient, provisioningClient, false); sensorServer.OnExecuteReadoutRequest += (Sender, Request) => { DateTime Now = DateTime.Now; Log.Informational("Readout requested", string.Empty, Request.Actor); Request.ReportFields(true, new BooleanField(ThingReference.Empty, Now, "Lamp", SwitchOn, FieldType.Momentary, FieldQoS.AutomaticReadout)); }; controlServer = new ControlServer(xmppClient, new BooleanControlParameter("Lamp", "Control", "Lamp switch on.", "If checked, lamp is turned on.", (Node) => SwitchOn, (Node, Value) => { SwitchOn = Value; Log.Informational("Lamp turned " + (SwitchOn ? "ON" : "OFF")); UpdateMainWindow(SwitchOn); })); this.bobClient = new BobClient(this.xmppClient, Path.Combine(Path.GetTempPath(), "BitsOfBinary")); this.chatServer = new ChatServer(xmppClient, this.bobClient, this.sensorServer, this.controlServer, this.provisioningClient); interoperabilityServer = new InteroperabilityServer(xmppClient); interoperabilityServer.OnGetInterfaces += (sender, e) => { e.Add("XMPP.IoT.Actuator.Lamp"); }; xmppClient.Connect(); } catch (Exception ex) { Log.Emergency(ex); MessageDialog Dialog = new MessageDialog(ex.Message, "Error"); await Dialog.ShowAsync(); } }
/// <summary> /// Analyzes the difference between the clock on the local machine with the clock on /// another machine, connected to the XMPP network, and compatible with the IEEE /// XMPP IoT extensions. /// /// Command line switches: /// /// -h HOST XMPP Server host name. /// -p PORT XMPP Port number, if different from 5222 /// -a ACCOUNT XMPP Account name to use when connecting to the server. /// -pwd PASSWORD PASSWORD to use when authenticating with the server. /// -i INTERVAL Interval (in milliseconds) used to check clocks. /// -j JID JID of clock source to monitor. /// Default=5000. /// -r RECORDS Number of measurements to collect. /// -n HISTORY Number of records in history. Averages are calculated /// on records in this history. Default=100 /// -w WINDOW Filter window size. The window is used to detect /// and eliminate bad measurements. Default=16 /// -s SPIKE_POS Spike position. Where spikes are detected, in /// window. Default=6 /// -sw SPIKE_WIDTH Spike width. Number of measurements in a row that can /// constitute a spike. Default=3 /// -o OUTPUT_FILE File name of report file. /// -enc ENCODING Text encoding. Default=UTF-8 /// -t TRANSFORM_FILE XSLT transform to use. /// -? Help. /// </summary> static int Main(string[] args) { try { Encoding Encoding = Encoding.UTF8; string OutputFileName = null; string XsltPath = null; string Host = null; string Account = null; string Password = null; string Jid = null; string s; int Port = 5222; int Records = 0; int Interval = 5000; int History = 100; int Window = 16; int SpikePos = 6; int SpikeWidth = 3; int i = 0; int c = args.Length; bool Help = false; while (i < c) { s = args[i++].ToLower(); switch (s) { case "-o": if (i >= c) { throw new Exception("Missing output file name."); } if (string.IsNullOrEmpty(OutputFileName)) { OutputFileName = args[i++]; } else { throw new Exception("Only one output file name allowed."); } break; case "-h": if (i >= c) { throw new Exception("Missing host name."); } if (string.IsNullOrEmpty(Host)) { Host = args[i++]; } else { throw new Exception("Only one host name allowed."); } break; case "-p": if (i >= c) { throw new Exception("Missing port number."); } if (!int.TryParse(args[i++], out Port) || Port <= 0 || Port > 65535) { throw new Exception("Invalid port number."); } break; case "-j": if (i >= c) { throw new Exception("Missing JID."); } if (string.IsNullOrEmpty(Jid)) { Jid = args[i++]; } else { throw new Exception("Only one JID allowed."); } break; case "-i": if (i >= c) { throw new Exception("Missing interval."); } if (!int.TryParse(args[i++], out Interval) || Interval < 1000) { throw new Exception("Invalid interval."); } break; case "-r": if (i >= c) { throw new Exception("Missing number of records to collect."); } if (!int.TryParse(args[i++], out Records) || Records <= 0) { throw new Exception("Invalid number of records to collect."); } break; case "-n": if (i >= c) { throw new Exception("Missing number of history records."); } if (!int.TryParse(args[i++], out History) || History <= 0) { throw new Exception("Invalid number of history records."); } break; case "-w": if (i >= c) { throw new Exception("Missing window size."); } if (!int.TryParse(args[i++], out Window) || Window <= 0) { throw new Exception("Invalid window size."); } break; case "-s": if (i >= c) { throw new Exception("Missing spike position."); } if (!int.TryParse(args[i++], out SpikePos) || SpikePos <= 0) { throw new Exception("Invalid spike position."); } break; case "-sw": if (i >= c) { throw new Exception("Missing spike width."); } if (!int.TryParse(args[i++], out SpikeWidth) || SpikeWidth <= 0) { throw new Exception("Invalid spike width."); } break; case "-a": if (i >= c) { throw new Exception("Missing account name."); } if (string.IsNullOrEmpty(Account)) { Account = args[i++]; } else { throw new Exception("Only one account name allowed."); } break; case "-pwd": if (i >= c) { throw new Exception("Missing password."); } if (string.IsNullOrEmpty(Password)) { Password = args[i++]; } else { throw new Exception("Only one password allowed."); } break; case "-enc": if (i >= c) { throw new Exception("Text encoding missing."); } Encoding = Encoding.GetEncoding(args[i++]); break; case "-t": if (i >= c) { throw new Exception("XSLT transform missing."); } XsltPath = args[i++]; break; case "-?": Help = true; break; default: throw new Exception("Unrecognized switch: " + s); } } if (Help || c == 0) { Console.Out.WriteLine("Analyzes the difference between the clock on the local machine with the clock on"); Console.Out.WriteLine("another machine, connected to the XMPP network, and compatible with the IEEE"); Console.Out.WriteLine("XMPP IoT extensions."); Console.Out.WriteLine(); Console.Out.WriteLine("Command line switches:"); Console.Out.WriteLine(); Console.Out.WriteLine("-h HOST XMPP Server host name."); Console.Out.WriteLine("-p PORT XMPP Port number, if different from 5222"); Console.Out.WriteLine("-a ACCOUNT XMPP Account name to use when connecting to the server."); Console.Out.WriteLine("-pwd PASSWORD PASSWORD to use when authenticating with the server."); Console.Out.WriteLine("-j JID JID of clock source to monitor."); Console.Out.WriteLine("-i INTERVAL Interval (in milliseconds) used to check clocks."); Console.Out.WriteLine(" Default=5000."); Console.Out.WriteLine("-r RECORDS Number of measurements to collect."); Console.Out.WriteLine("-n HISTORY Number of records in history. Averages are calculated"); Console.Out.WriteLine(" on records in this history. Default=100"); Console.Out.WriteLine("-w WINDOW Filter window size. The window is used to detect"); Console.Out.WriteLine(" and eliminate bad measurements. Default=16"); Console.Out.WriteLine("-s SPIKE_POS Spike position. Where spikes are detected, in"); Console.Out.WriteLine(" window. Default=6"); Console.Out.WriteLine("-sw SPIKE_WIDTH Spike width. Number of measurements in a row that can"); Console.Out.WriteLine(" constitute a spike. Default=3"); Console.Out.WriteLine("-o OUTPUT_FILE File name of report file."); Console.Out.WriteLine("-enc ENCODING Text encoding. Default=UTF-8"); Console.Out.WriteLine("-t TRANSFORM_FILE XSLT transform to use."); Console.Out.WriteLine("-? Help."); return(0); } if (string.IsNullOrEmpty(Host)) { throw new Exception("No host name specified."); } if (string.IsNullOrEmpty(Account)) { throw new Exception("No account name specified."); } if (string.IsNullOrEmpty(Password)) { throw new Exception("No password specified."); } if (string.IsNullOrEmpty(Jid)) { throw new Exception("No clock source JID specified."); } if (Records <= 0) { throw new Exception("Number of records to collect not specified."); } if (string.IsNullOrEmpty(OutputFileName)) { throw new Exception("No output filename specified."); } XmppCredentials Credentials = new XmppCredentials() { Host = Host, Port = Port, Account = Account, Password = Password, AllowCramMD5 = true, AllowEncryption = true, AllowDigestMD5 = true, AllowPlain = true, AllowScramSHA1 = true, AllowScramSHA256 = true, AllowRegistration = false }; using (XmppClient Client = new XmppClient(Credentials, "en", typeof(Program).Assembly)) { ManualResetEvent Done = new ManualResetEvent(false); ManualResetEvent Error = new ManualResetEvent(false); Client.OnStateChanged += (sender, NewState) => { switch (NewState) { case XmppState.Connected: Done.Set(); break; case XmppState.Error: case XmppState.Offline: Error.Set(); break; } }; Client.Connect(); i = WaitHandle.WaitAny(new WaitHandle[] { Done, Error }); if (i == 1) { throw new Exception("Unable to connect to broker."); } if (Jid.Contains("@") && !Jid.Contains("/")) { RosterItem Contact = Client.GetRosterItem(Jid); if (Contact is null || (Contact.State != SubscriptionState.Both && Contact.State != SubscriptionState.To)) { Done.Reset(); Client.OnPresenceSubscribed += (sender, e) => { if (string.Compare(e.FromBareJID, Jid, true) == 0) { Done.Set(); } }; Client.OnPresenceUnsubscribed += (sender, e) => { if (string.Compare(e.FromBareJID, Jid, true) == 0) { Error.Set(); } }; Console.WriteLine("Requesting presence subscription to " + Jid); Client.RequestPresenceSubscription(Jid); i = WaitHandle.WaitAny(new WaitHandle[] { Done, Error }); if (i == 1) { throw new Exception("Unable to obtain presence subscription."); } Console.WriteLine("Presence subscription obtained."); } } ManualResetEvent Done2 = new ManualResetEvent(false); using (StreamWriter f = File.CreateText(OutputFileName)) { XmlWriterSettings Settings = new XmlWriterSettings() { Encoding = Encoding, Indent = true, IndentChars = "\t", NewLineChars = Console.Out.NewLine, OmitXmlDeclaration = false, WriteEndDocumentOnClose = true }; using (XmlWriter w = XmlWriter.Create(f, Settings)) { w.WriteStartDocument(); if (!string.IsNullOrEmpty(XsltPath)) { w.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + XML.Encode(XsltPath) + "\""); } w.WriteStartElement("ClockStatistics", "http://waher.se/Schema/Networking/ClockStatistics.xsd"); w.WriteStartElement("Parameters"); w.WriteAttributeString("clientJid", Client.BareJID); w.WriteAttributeString("sourceJid", Jid); w.WriteAttributeString("records", Records.ToString()); w.WriteAttributeString("interval", Interval.ToString()); w.WriteAttributeString("history", History.ToString()); w.WriteAttributeString("window", Window.ToString()); w.WriteAttributeString("spikePos", SpikePos.ToString()); w.WriteAttributeString("spikeWidth", SpikeWidth.ToString()); w.WriteAttributeString("hfFreq", System.Diagnostics.Stopwatch.Frequency.ToString()); w.WriteEndElement(); w.WriteStartElement("Samples"); using (SynchronizationClient SynchClient = new SynchronizationClient(Client)) { SynchClient.OnUpdated += (sender, e) => { DateTime TP = DateTime.Now; double? StdDev; w.WriteStartElement("Sample"); w.WriteAttributeString("timestamp", XML.Encode(TP)); if (SynchClient.RawLatency100Ns.HasValue) { w.WriteAttributeString("rawLatencyMs", CommonTypes.Encode(SynchClient.RawLatency100Ns.Value * 1e-4)); } if (SynchClient.LatencySpikeRemoved.HasValue) { w.WriteAttributeString("spikeLatencyRemoved", CommonTypes.Encode(SynchClient.LatencySpikeRemoved.Value)); } if (SynchClient.RawClockDifference100Ns.HasValue) { w.WriteAttributeString("rawDifferenceMs", CommonTypes.Encode(SynchClient.RawClockDifference100Ns.Value * 1e-4)); } if (SynchClient.ClockDifferenceSpikeRemoved.HasValue) { w.WriteAttributeString("spikeDifferenceRemoved", CommonTypes.Encode(SynchClient.ClockDifferenceSpikeRemoved.Value)); } if (SynchClient.FilteredLatency100Ns.HasValue) { w.WriteAttributeString("filteredLatencyMs", CommonTypes.Encode(SynchClient.FilteredLatency100Ns.Value * 1e-4)); } if (SynchClient.FilteredClockDifference100Ns.HasValue) { w.WriteAttributeString("filteredDifferenceMs", CommonTypes.Encode(SynchClient.FilteredClockDifference100Ns.Value * 1e-4)); } if (SynchClient.AvgLatency100Ns.HasValue) { w.WriteAttributeString("avgLatencyMs", CommonTypes.Encode(SynchClient.AvgLatency100Ns.Value * 1e-4)); } if (SynchClient.AvgClockDifference100Ns.HasValue) { w.WriteAttributeString("avgDifferenceMs", CommonTypes.Encode(SynchClient.AvgClockDifference100Ns.Value * 1e-4)); } StdDev = SynchClient.CalcStdDevLatency100Ns(); if (StdDev.HasValue) { w.WriteAttributeString("stdDevLatencyMs", CommonTypes.Encode(StdDev.Value * 1e-4)); } StdDev = SynchClient.CalcStdDevClockDifference100Ns(); if (StdDev.HasValue) { w.WriteAttributeString("stdDevDifferenceMs", CommonTypes.Encode(StdDev.Value * 1e-4)); } if (SynchClient.RawLatencyHf.HasValue) { w.WriteAttributeString("rawLatencyHf", SynchClient.RawLatencyHf.Value.ToString()); } if (SynchClient.LatencyHfSpikeRemoved.HasValue) { w.WriteAttributeString("spikeLatencyHfRemoved", CommonTypes.Encode(SynchClient.LatencyHfSpikeRemoved.Value)); } if (SynchClient.RawClockDifferenceHf.HasValue) { w.WriteAttributeString("rawDifferenceHf", SynchClient.RawClockDifferenceHf.Value.ToString()); } if (SynchClient.ClockDifferenceHfSpikeRemoved.HasValue) { w.WriteAttributeString("spikeDifferenceHfRemoved", CommonTypes.Encode(SynchClient.ClockDifferenceHfSpikeRemoved.Value)); } if (SynchClient.FilteredLatencyHf.HasValue) { w.WriteAttributeString("filteredLatencyHf", SynchClient.FilteredLatencyHf.ToString()); } if (SynchClient.FilteredClockDifferenceHf.HasValue) { w.WriteAttributeString("filteredDifferenceHf", SynchClient.FilteredClockDifferenceHf.ToString()); } if (SynchClient.AvgLatencyHf.HasValue) { w.WriteAttributeString("avgLatencyHf", SynchClient.AvgLatencyHf.ToString()); } if (SynchClient.AvgClockDifferenceHf.HasValue) { w.WriteAttributeString("avgDifferenceHf", SynchClient.AvgClockDifferenceHf.ToString()); } StdDev = SynchClient.CalcStdDevLatencyHf(); if (StdDev.HasValue) { w.WriteAttributeString("stdDevLatencyHf", CommonTypes.Encode(StdDev.Value)); } StdDev = SynchClient.CalcStdDevClockDifferenceHf(); if (StdDev.HasValue) { w.WriteAttributeString("stdDevDifferenceHf", CommonTypes.Encode(StdDev.Value)); } w.WriteEndElement(); Console.Out.Write("."); if (--Records <= 0) { Done2.Set(); } }; SynchClient.MonitorClockDifference(Jid, Interval, History, Window, SpikePos, SpikeWidth, true); Done2.WaitOne(); } w.WriteEndElement(); w.WriteEndElement(); w.WriteEndDocument(); w.Flush(); Console.Out.WriteLine(); } } } return(0); } catch (Exception ex) { Console.Out.WriteLine(ex.Message); return(-1); } }
/// <summary> /// Saves the settings to a file. /// </summary> /// <param name="FileName">File name.</param> /// <param name="Credentials">XMPP Client credentials.</param> public static void SaveSimpleXmppConfiguration(string FileName, XmppCredentials Credentials) { File.WriteAllText(FileName, ExportSimpleXmppConfiguration(Credentials), Encoding.UTF8); }
/// <summary> /// Exports the settings to XML. /// </summary> /// <param name="Credentials">XMPP Client credentials.</param> /// <returns>XML</returns> public static string ExportSimpleXmppConfiguration(XmppCredentials Credentials) { StringBuilder Xml = new StringBuilder(); Xml.AppendLine("<?xml version='1.0' encoding='utf-8'?>"); Xml.AppendLine("<SimpleXmppConfiguration xmlns='http://waher.se/Schema/SimpleXmppConfiguration.xsd'>"); Xml.Append("\t<Host>"); Xml.Append(XML.Encode(Credentials.Host)); Xml.AppendLine("</Host>"); Xml.Append("\t<Port>"); Xml.Append(Credentials.Port.ToString()); Xml.AppendLine("</Port>"); Xml.Append("\t<Account>"); Xml.Append(XML.Encode(Credentials.Account)); Xml.AppendLine("</Account>"); Xml.Append("\t<Password type=\""); Xml.Append(XML.Encode(Credentials.PasswordType)); Xml.Append("\">"); Xml.Append(XML.Encode(Credentials.Password)); Xml.AppendLine("</Password>"); Xml.Append("\t<ThingRegistry>"); Xml.Append(XML.Encode(Credentials.ThingRegistry)); Xml.AppendLine("</ThingRegistry>"); Xml.Append("\t<Provisioning>"); Xml.Append(XML.Encode(Credentials.Provisioning)); Xml.AppendLine("</Provisioning>"); Xml.Append("\t<Events>"); Xml.Append(XML.Encode(Credentials.Events)); Xml.AppendLine("</Events>"); Xml.Append("\t<Sniffer>"); Xml.Append(CommonTypes.Encode(Credentials.Sniffer)); Xml.AppendLine("</Sniffer>"); Xml.Append("\t<TrustServer>"); Xml.Append(CommonTypes.Encode(Credentials.TrustServer)); Xml.AppendLine("</TrustServer>"); Xml.Append("\t<AllowCramMD5>"); Xml.Append(CommonTypes.Encode(Credentials.AllowCramMD5)); Xml.AppendLine("</AllowCramMD5>"); Xml.Append("\t<AllowDigestMD5>"); Xml.Append(CommonTypes.Encode(Credentials.AllowDigestMD5)); Xml.AppendLine("</AllowDigestMD5>"); Xml.Append("\t<AllowPlain>"); Xml.Append(CommonTypes.Encode(Credentials.AllowPlain)); Xml.AppendLine("</AllowPlain>"); Xml.Append("\t<AllowScramSHA1>"); Xml.Append(CommonTypes.Encode(Credentials.AllowScramSHA1)); Xml.AppendLine("</AllowScramSHA1>"); Xml.Append("\t<AllowScramSHA256>"); Xml.Append(CommonTypes.Encode(Credentials.AllowScramSHA256)); Xml.AppendLine("</AllowScramSHA256>"); Xml.Append("\t<AllowEncryption>"); Xml.Append(CommonTypes.Encode(Credentials.AllowEncryption)); Xml.AppendLine("</AllowEncryption>"); Xml.Append("\t<RequestRosterOnStartup>"); Xml.Append(CommonTypes.Encode(Credentials.RequestRosterOnStartup)); Xml.AppendLine("</RequestRosterOnStartup>"); Xml.Append("\t<AllowRegistration>"); Xml.Append(CommonTypes.Encode(Credentials.AllowRegistration)); Xml.AppendLine("</AllowRegistration>"); Xml.Append("\t<FormSignatureKey>"); Xml.Append(XML.Encode(Credentials.FormSignatureKey)); Xml.AppendLine("</FormSignatureKey>"); Xml.Append("\t<FormSignatureSecret>"); Xml.Append(XML.Encode(Credentials.FormSignatureSecret)); Xml.AppendLine("</FormSignatureSecret>"); Xml.AppendLine("</SimpleXmppConfiguration>"); return(Xml.ToString()); }
/// <summary> /// Loads simple XMPP configuration from an XML file. If file does not exist, or is not valid, a console dialog with the user is performed, /// to get the relevant information, test it, and create the corresponding XML file for later use. /// </summary> /// <param name="FileName">Name of configuration file.</param> /// <param name="DefaultAccountName">Default account name.</param> /// <param name="DefaultPassword">Default password.</param> /// <param name="AppAssembly">Application assembly.</param> /// <returns>Simple XMPP configuration.</returns> public static XmppCredentials GetConfigUsingSimpleConsoleDialog(string FileName, string DefaultAccountName, string DefaultPassword, Assembly AppAssembly) { try { return(Load(FileName)); } catch (Exception #if WINDOWS_UWP ex #endif ) { XmppCredentials Credentials = new XmppCredentials(); bool Ok; Credentials.Host = DefaultXmppServer; Credentials.Port = XmppCredentials.DefaultPort; Credentials.Account = DefaultAccountName; Credentials.Password = DefaultPassword; #if WINDOWS_UWP using (XmppClient Client = new XmppClient(Credentials, "en", AppAssembly)) { Client.Connect(); ManualResetEvent Connected = new ManualResetEvent(false); ManualResetEvent Failure = new ManualResetEvent(false); Client.OnStateChanged += (sender, NewState) => { switch (NewState) { case XmppState.Connected: Credentials.Password = Client.PasswordHash; Credentials.PasswordType = Client.PasswordHashMethod; Connected.Set(); break; case XmppState.Error: Failure.Set(); break; } }; switch (WaitHandle.WaitAny(new WaitHandle[] { Connected, Failure }, 20000)) { case 0: Ok = true; break; case 1: default: Ok = false; break; } if (Ok) { ServiceItemsDiscoveryEventArgs e = Client.ServiceItemsDiscovery(Client.Domain, 10000); foreach (Item Item in e.Items) { ServiceDiscoveryEventArgs e2 = Client.ServiceDiscovery(Item.JID, 10000); if (e2.Features.ContainsKey("urn:ieee:iot:disco:1.0") && string.IsNullOrEmpty(Credentials.ThingRegistry)) { Credentials.ThingRegistry = Item.JID; } else { Credentials.ThingRegistry = string.Empty; } if (e2.Features.ContainsKey("urn:ieee:iot:prov:d:1.0") && string.IsNullOrEmpty(Credentials.Provisioning)) { Credentials.Provisioning = Item.JID; } else { Credentials.Provisioning = string.Empty; } if (e2.Features.ContainsKey("urn:xmpp:eventlog") && string.IsNullOrEmpty(Credentials.Events)) { Credentials.Events = Item.JID; } else { Credentials.Events = string.Empty; } } } else { System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex).Throw(); } } #else ConsoleColor FgBak = Console.ForegroundColor; string s; string Default; do { Console.ForegroundColor = ConsoleColor.Yellow; Console.Out.WriteLine(); Console.Out.WriteLine("To setup a connection to the XMPP network, please answer the following"); Console.Out.WriteLine("questions:"); Default = Credentials.Host; Console.Out.WriteLine(); Console.Out.WriteLine("What XMPP server do you want to use? Press ENTER to use " + Default); do { Console.ForegroundColor = ConsoleColor.White; Console.Out.Write("XMPP Server: "); Credentials.Host = Console.In.ReadLine(); if (string.IsNullOrEmpty(Credentials.Host)) { Credentials.Host = Default; } Console.ForegroundColor = ConsoleColor.Green; Console.Out.WriteLine(); Console.Out.WriteLine("You've selected to use '" + Credentials.Host + "'. Is this correct? [y/n]"); s = Console.In.ReadLine(); Console.Out.WriteLine(); }while (!s.StartsWith("y", StringComparison.InvariantCultureIgnoreCase)); Default = Credentials.Port.ToString(); Console.ForegroundColor = ConsoleColor.Yellow; Console.Out.WriteLine("What port do you want to connect to? Press ENTER to use " + Default); do { Console.ForegroundColor = ConsoleColor.White; int Port; do { Console.Out.Write("Port Number: "); s = Console.In.ReadLine(); if (string.IsNullOrEmpty(s)) { s = Default; } }while (!int.TryParse(s, out Port) || Port < 1 || Port > 65535); Credentials.Port = Port; Console.ForegroundColor = ConsoleColor.Green; Console.Out.WriteLine(); Console.Out.WriteLine("You've selected to use '" + Credentials.Port.ToString() + "'. Is this correct? [y/n]"); s = Console.In.ReadLine(); Console.Out.WriteLine(); }while (!s.StartsWith("y", StringComparison.InvariantCultureIgnoreCase)); Default = Credentials.Account; Console.ForegroundColor = ConsoleColor.Yellow; Console.Out.WriteLine("What account to you want to connect with? If the account does not exist,"); Console.Out.WriteLine("but the server supports In-band registration, the account will be created."); if (!string.IsNullOrEmpty(Default)) { Console.Out.WriteLine("Press ENTER to use " + Default); } do { Console.ForegroundColor = ConsoleColor.White; do { Console.Out.Write("Account: "); Credentials.Account = Console.In.ReadLine(); if (string.IsNullOrEmpty(Credentials.Account)) { Credentials.Account = Default; } }while (string.IsNullOrEmpty(Credentials.Account)); Console.ForegroundColor = ConsoleColor.Green; Console.Out.WriteLine(); Console.Out.WriteLine("You've selected to use '" + Credentials.Account + "'. Is this correct? [y/n]"); s = Console.In.ReadLine(); Console.Out.WriteLine(); }while (!s.StartsWith("y", StringComparison.InvariantCultureIgnoreCase)); Default = Credentials.Password; Console.ForegroundColor = ConsoleColor.Yellow; Console.Out.WriteLine("What password goes with the account? Remember that the configuration will,"); Console.Out.Write("be stored in a simple text file along with the application. "); if (!string.IsNullOrEmpty(Default)) { Console.Out.WriteLine("Press ENTER to use " + Default); } do { Console.ForegroundColor = ConsoleColor.White; do { Console.Out.Write("Password: "******"You've selected to use '" + Credentials.Password + "'. Is this correct? [y/n]"); s = Console.In.ReadLine(); Console.Out.WriteLine(); }while (!s.StartsWith("y", StringComparison.InvariantCultureIgnoreCase)); Console.ForegroundColor = ConsoleColor.Yellow; Console.Out.WriteLine("Do you want to trust the server? It's better not to trust the server."); Console.Out.WriteLine("This will force the server certificate to be validated, and the server"); Console.Out.WriteLine("trusted only if the certificate is valid. If there's a valid problem with"); Console.Out.WriteLine("the server certificate however, you might need to trust the server to"); Console.Out.WriteLine("be able to proceed."); do { Console.ForegroundColor = ConsoleColor.White; Console.Out.Write("Trust server [y/n]? "); s = Console.In.ReadLine(); Credentials.TrustServer = s.StartsWith("y", StringComparison.InvariantCultureIgnoreCase); }while (!Credentials.TrustServer && !s.StartsWith("n", StringComparison.InvariantCultureIgnoreCase)); Console.ForegroundColor = ConsoleColor.Yellow; Console.Out.WriteLine("Do you want to create an account on the server?"); do { Console.ForegroundColor = ConsoleColor.White; Console.Out.Write("Create account [y/n]? "); s = Console.In.ReadLine(); Credentials.AllowRegistration = s.StartsWith("y", StringComparison.InvariantCultureIgnoreCase); }while (!Credentials.AllowRegistration && !s.StartsWith("n", StringComparison.InvariantCultureIgnoreCase)); if (Credentials.AllowRegistration) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Out.WriteLine(); Console.Out.WriteLine("Some servers require an API key to allow account creation."); Console.Out.WriteLine("If so, please enter an API key below."); Default = Credentials.FormSignatureKey; Console.Out.WriteLine(); Console.Out.WriteLine("What API Key do you want to use? Press ENTER to use " + Default); do { Console.ForegroundColor = ConsoleColor.White; Console.Out.Write("API Key: "); Credentials.FormSignatureKey = Console.In.ReadLine(); if (string.IsNullOrEmpty(Credentials.FormSignatureKey)) { Credentials.FormSignatureKey = Default; } Console.ForegroundColor = ConsoleColor.Green; Console.Out.WriteLine(); Console.Out.WriteLine("You've selected to use '" + Credentials.FormSignatureKey + "'. Is this correct? [y/n]"); s = Console.In.ReadLine(); Console.Out.WriteLine(); }while (!s.StartsWith("y", StringComparison.InvariantCultureIgnoreCase)); if (!string.IsNullOrEmpty(Credentials.FormSignatureKey)) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Out.WriteLine(); Console.Out.WriteLine("Please provide the corresponding secret below."); Default = Credentials.FormSignatureSecret; Console.Out.WriteLine(); Console.Out.WriteLine("What secret belongs to the API key? Press ENTER to use " + Default); do { Console.ForegroundColor = ConsoleColor.White; Console.Out.Write("Secret: "); Credentials.FormSignatureSecret = Console.In.ReadLine(); if (string.IsNullOrEmpty(Credentials.FormSignatureSecret)) { Credentials.FormSignatureSecret = Default; } Console.ForegroundColor = ConsoleColor.Green; Console.Out.WriteLine(); Console.Out.WriteLine("You've selected to use '" + Credentials.FormSignatureSecret + "'. Is this correct? [y/n]"); s = Console.In.ReadLine(); Console.Out.WriteLine(); }while (!s.StartsWith("y", StringComparison.InvariantCultureIgnoreCase)); } } Console.ForegroundColor = ConsoleColor.Yellow; Console.Out.WriteLine("I will now try to connect to the server to see if the information"); Console.Out.WriteLine("provided is correct."); using (XmppClient Client = new XmppClient(Credentials, "en", AppAssembly)) { Client.Connect(); ManualResetEvent Connected = new ManualResetEvent(false); ManualResetEvent Failure = new ManualResetEvent(false); Client.OnStateChanged += (sender, NewState) => { Console.Out.WriteLine(NewState.ToString()); switch (NewState) { case XmppState.Connected: Console.ForegroundColor = ConsoleColor.Green; Console.Out.WriteLine("Connection successful."); Credentials.Password = Client.PasswordHash; Credentials.PasswordType = Client.PasswordHashMethod; Credentials.AllowRegistration = false; Credentials.FormSignatureKey = string.Empty; Credentials.FormSignatureSecret = string.Empty; Connected.Set(); break; case XmppState.Error: Console.ForegroundColor = ConsoleColor.Red; Console.Out.WriteLine("Connection failed. Please update connection information."); Failure.Set(); break; } }; switch (WaitHandle.WaitAny(new WaitHandle[] { Connected, Failure }, 20000)) { case 0: Ok = true; break; case 1: default: Ok = false; break; } if (Ok) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Out.WriteLine("Checking server capabilities."); ServiceItemsDiscoveryEventArgs e = Client.ServiceItemsDiscovery(Client.Domain, 10000); foreach (Item Item in e.Items) { Console.Out.WriteLine("Checking " + Item.JID + "."); ServiceDiscoveryEventArgs e2 = Client.ServiceDiscovery(Item.JID, 10000); if (e2.Features.ContainsKey("urn:ieee:iot:disco:1.0") && string.IsNullOrEmpty(Credentials.ThingRegistry)) { Console.Out.WriteLine("Thing registry found."); Credentials.ThingRegistry = Item.JID; } else { Credentials.ThingRegistry = string.Empty; } if (e2.Features.ContainsKey("urn:ieee:iot:prov:d:1.0") && string.IsNullOrEmpty(Credentials.Provisioning)) { Console.Out.WriteLine("Provisioning server found."); Credentials.Provisioning = Item.JID; } else { Credentials.Provisioning = string.Empty; } if (e2.Features.ContainsKey("urn:xmpp:eventlog") && string.IsNullOrEmpty(Credentials.Events)) { Console.Out.WriteLine("Event log found."); Credentials.Events = Item.JID; } else { Credentials.Events = string.Empty; } } } } }while (!Ok); Default = Credentials.ThingRegistry; Console.ForegroundColor = ConsoleColor.Yellow; Console.Out.WriteLine("What thing registry do you want to use? The use of a thing registry is optional."); if (string.IsNullOrEmpty(Default)) { Console.Out.WriteLine("Press ENTER to not use a thing registry."); } else { Console.Out.WriteLine("Press ENTER to use " + Default); } do { Console.ForegroundColor = ConsoleColor.White; Console.Out.Write("Thing Registry: "); Credentials.ThingRegistry = Console.In.ReadLine(); if (string.IsNullOrEmpty(Credentials.ThingRegistry)) { Credentials.ThingRegistry = Default; } Console.ForegroundColor = ConsoleColor.Green; Console.Out.WriteLine(); if (string.IsNullOrEmpty(Credentials.ThingRegistry)) { Console.Out.WriteLine("You've selected to not use a thing registry. Is this correct? [y/n]"); } else { Console.Out.WriteLine("You've selected to use '" + Credentials.ThingRegistry + "'. Is this correct? [y/n]"); } s = Console.In.ReadLine(); Console.Out.WriteLine(); }while (!s.StartsWith("y", StringComparison.InvariantCultureIgnoreCase)); Default = Credentials.Provisioning; Console.ForegroundColor = ConsoleColor.Yellow; Console.Out.WriteLine("What provisioning server do you want to use? The use of a provisioning server"); Console.Out.WriteLine("is optional."); if (string.IsNullOrEmpty(Default)) { Console.Out.WriteLine("Press ENTER to not use a provisioning server."); } else { Console.Out.WriteLine("Press ENTER to use " + Default); } do { Console.ForegroundColor = ConsoleColor.White; Console.Out.Write("Provisioning Server: "); Credentials.Provisioning = Console.In.ReadLine(); if (string.IsNullOrEmpty(Credentials.Provisioning)) { Credentials.Provisioning = Default; } Console.ForegroundColor = ConsoleColor.Green; Console.Out.WriteLine(); if (string.IsNullOrEmpty(Credentials.Provisioning)) { Console.Out.WriteLine("You've selected to not use a provisioning server. Is this correct? [y/n]"); } else { Console.Out.WriteLine("You've selected to use '" + Credentials.Provisioning + "'. Is this correct? [y/n]"); } s = Console.In.ReadLine(); Console.Out.WriteLine(); }while (!s.StartsWith("y", StringComparison.InvariantCultureIgnoreCase)); Default = Credentials.Events; Console.ForegroundColor = ConsoleColor.Yellow; Console.Out.WriteLine("What event log do you want to use? The use of a event logs is optional."); if (string.IsNullOrEmpty(Default)) { Console.Out.WriteLine("Press ENTER to not use an event log."); } else { Console.Out.WriteLine("Press ENTER to use " + Default); } do { Console.ForegroundColor = ConsoleColor.White; Console.Out.Write("Event Log: "); Credentials.Events = Console.In.ReadLine(); if (string.IsNullOrEmpty(Credentials.Events)) { Credentials.Events = Default; } Console.ForegroundColor = ConsoleColor.Green; Console.Out.WriteLine(); if (string.IsNullOrEmpty(Credentials.Events)) { Console.Out.WriteLine("You've selected to not use an event log. Is this correct? [y/n]"); } else { Console.Out.WriteLine("You've selected to use '" + Credentials.Events + "'. Is this correct? [y/n]"); } s = Console.In.ReadLine(); Console.Out.WriteLine(); }while (!s.StartsWith("y", StringComparison.InvariantCultureIgnoreCase)); Console.ForegroundColor = ConsoleColor.Yellow; Console.Out.WriteLine("Do you want to use a sniffer? If you use a sniffer, XMPP network"); Console.Out.WriteLine("communication will be Output to the console in real-time. This can"); Console.Out.WriteLine("come in handy when debugging network communication."); do { Console.ForegroundColor = ConsoleColor.White; Console.Out.Write("Sniffer [y/n]? "); s = Console.In.ReadLine(); Credentials.Sniffer = s.StartsWith("y", StringComparison.InvariantCultureIgnoreCase); }while (!Credentials.Sniffer && !s.StartsWith("n", StringComparison.InvariantCultureIgnoreCase)); Console.Out.WriteLine(); Console.ForegroundColor = FgBak; #endif SaveSimpleXmppConfiguration(FileName, Credentials); return(Credentials); } }
public static void Main(string[] args) { try { Console.ForegroundColor = ConsoleColor.White; Console.Out.WriteLine("Welcome to the Mock Temperature sensor application."); Console.Out.WriteLine(new string('-', 79)); Console.Out.WriteLine("This application will simulate an outside temperature sensor."); Console.Out.WriteLine("Values will be published over XMPP using the interface defined in the IEEE XMPP IoT extensions."); Console.Out.WriteLine("You can also chat with the sensor."); Log.Register(new ConsoleEventSink()); Log.RegisterExceptionToUnnest(typeof(System.Runtime.InteropServices.ExternalException)); Log.RegisterExceptionToUnnest(typeof(System.Security.Authentication.AuthenticationException)); credentials = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config", Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name. Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password. typeof(Program).Assembly); using (XmppClient Client = new XmppClient(credentials, "en", typeof(Program).Assembly)) { if (credentials.Sniffer) { Client.Add(new ConsoleOutSniffer(BinaryPresentationMethod.ByteCount, LineEnding.PadWithSpaces)); } if (!string.IsNullOrEmpty(credentials.Events)) { Log.Register(new XmppEventSink("XMPP Event Sink", Client, credentials.Events, false)); } if (!string.IsNullOrEmpty(credentials.ThingRegistry)) { thingRegistryClient = new ThingRegistryClient(Client, credentials.ThingRegistry); thingRegistryClient.Claimed += (sender, e) => { ownerJid = e.JID; Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair <string, object>("Public", e.IsPublic)); }; thingRegistryClient.Disowned += (sender, e) => { Log.Informational("Thing has been disowned.", ownerJid); ownerJid = string.Empty; Register(); }; thingRegistryClient.Removed += (sender, e) => { Log.Informational("Thing has been removed from the public registry.", ownerJid); }; } ProvisioningClient ProvisioningClient = null; if (!string.IsNullOrEmpty(credentials.Provisioning)) { ProvisioningClient = new ProvisioningClient(Client, credentials.Provisioning); } Timer ConnectionTimer = new Timer((P) => { if (Client.State == XmppState.Offline || Client.State == XmppState.Error || Client.State == XmppState.Authenticating) { try { Client.Reconnect(); } catch (Exception ex) { Log.Critical(ex); } } }, null, 60000, 60000); bool Connected = false; bool ImmediateReconnect; Client.OnStateChanged += (sender, NewState) => { switch (NewState) { case XmppState.Connected: Connected = true; if (!registered && thingRegistryClient != null) { Register(); } break; case XmppState.Offline: ImmediateReconnect = Connected; Connected = false; if (ImmediateReconnect) { Client.Reconnect(); } break; } }; Client.OnPresenceSubscribe += (sender, e) => { e.Accept(); // TODO: Provisioning RosterItem Item = Client.GetRosterItem(e.FromBareJID); if (Item is null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From) { Client.RequestPresenceSubscription(e.FromBareJID); } Client.SetPresence(Availability.Chat); }; Client.OnPresenceUnsubscribe += (sender, e) => { e.Accept(); }; Client.OnRosterItemUpdated += (sender, e) => { if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe) { Client.RemoveRosterItem(e.BareJid); } }; LinkedList <DayHistoryRecord> DayHistoricalValues = new LinkedList <DayHistoryRecord>(); LinkedList <MinuteHistoryRecord> MinuteHistoricalValues = new LinkedList <MinuteHistoryRecord>(); DateTime SampleTime = DateTime.Now; DateTime PeriodStart = SampleTime.Date; DateTime Now; DateTime MinTime = SampleTime; DateTime MaxTime = SampleTime; double CurrentTemperature = ReadTemp(); double MinTemp = CurrentTemperature; double MaxTemp = CurrentTemperature; double SumTemp = CurrentTemperature; int NrTemp = 1; int NrDayRecords = 0; int NrMinuteRecords = 0; object SampleSynch = new object(); SensorServer SensorServer = new SensorServer(Client, ProvisioningClient, true); SensorServer.OnExecuteReadoutRequest += (Sender, Request) => { Log.Informational("Readout requested", string.Empty, Request.Actor); List <Field> Fields = new List <Field>(); bool IncludeTemp = Request.IsIncluded("Temperature"); bool IncludeTempMin = Request.IsIncluded("Temperature, Min"); bool IncludeTempMax = Request.IsIncluded("Temperature, Max"); bool IncludeTempAvg = Request.IsIncluded("Temperature, Average"); bool IncludePeak = Request.IsIncluded(FieldType.Peak); bool IncludeComputed = Request.IsIncluded(FieldType.Computed); lock (SampleSynch) { if (IncludeTemp && Request.IsIncluded(FieldType.Momentary)) { Fields.Add(new QuantityField(ThingReference.Empty, SampleTime, "Temperature", CurrentTemperature, 1, "°C", FieldType.Momentary, FieldQoS.AutomaticReadout)); } if (IncludePeak) { if (IncludeTempMin) { Fields.Add(new QuantityField(ThingReference.Empty, MinTime, "Temperature, Min", MinTemp, 1, "°C", FieldType.Peak, FieldQoS.AutomaticReadout)); } if (IncludeTempMax) { Fields.Add(new QuantityField(ThingReference.Empty, MaxTime, "Temperature, Max", MaxTemp, 1, "°C", FieldType.Peak, FieldQoS.AutomaticReadout)); } } if (IncludeTempAvg && IncludeComputed) { Fields.Add(new QuantityField(ThingReference.Empty, SampleTime, "Temperature, Average", SumTemp / NrTemp, 2, "°C", FieldType.Computed, FieldQoS.AutomaticReadout)); } if (Request.IsIncluded(FieldType.Historical)) { foreach (DayHistoryRecord Rec in DayHistoricalValues) { if (!Request.IsIncluded(Rec.PeriodStart)) { continue; } if (Fields.Count >= 100) { Request.ReportFields(false, Fields); Fields.Clear(); } if (IncludePeak) { if (IncludeTempMin) { Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Min", Rec.MinTemperature, 1, "°C", FieldType.Peak | FieldType.Historical, FieldQoS.AutomaticReadout)); } if (IncludeTempMax) { Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Max", Rec.MaxTemperature, 1, "°C", FieldType.Peak | FieldType.Historical, FieldQoS.AutomaticReadout)); } } if (IncludeTempAvg && IncludeComputed) { Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Average", Rec.AverageTemperature, 1, "°C", FieldType.Computed | FieldType.Historical, FieldQoS.AutomaticReadout)); } } foreach (MinuteHistoryRecord Rec in MinuteHistoricalValues) { if (!Request.IsIncluded(Rec.Timestamp)) { continue; } if (IncludeTemp) { if (Fields.Count >= 100) { Request.ReportFields(false, Fields); Fields.Clear(); } Fields.Add(new QuantityField(ThingReference.Empty, Rec.Timestamp, "Temperature", Rec.Temperature, 1, "°C", FieldType.Historical, FieldQoS.AutomaticReadout)); } } } } Request.ReportFields(true, Fields); }; Timer SampleTimer = new Timer((P) => { lock (SampleSynch) { Now = DateTime.Now; if (Now.Date != PeriodStart.Date) { DayHistoryRecord Rec = new DayHistoryRecord(PeriodStart.Date, PeriodStart.Date.AddDays(1).AddMilliseconds(-1), MinTemp, MaxTemp, SumTemp / NrTemp); DayHistoricalValues.AddFirst(Rec); if (NrDayRecords < MaxRecordsPerPeriod) { NrDayRecords++; } else { DayHistoricalValues.RemoveLast(); } // TODO: Persistence PeriodStart = Now.Date; SumTemp = 0; NrTemp = 0; } CurrentTemperature = ReadTemp(); if (Now.Minute != SampleTime.Minute) { MinuteHistoryRecord Rec = new MinuteHistoryRecord(Now, CurrentTemperature); MinuteHistoricalValues.AddFirst(Rec); if (NrMinuteRecords < MaxRecordsPerPeriod) { NrMinuteRecords++; } else { MinuteHistoricalValues.RemoveLast(); } // TODO: Persistence } SampleTime = Now; if (CurrentTemperature < MinTemp) { MinTemp = CurrentTemperature; MinTime = SampleTime; } if (CurrentTemperature > MaxTemp) { MaxTemp = CurrentTemperature; MaxTime = SampleTime; } SumTemp += CurrentTemperature; NrTemp++; } if (SensorServer.HasSubscriptions(ThingReference.Empty)) { SensorServer.NewMomentaryValues(new QuantityField(ThingReference.Empty, SampleTime, "Temperature", CurrentTemperature, 1, "°C", FieldType.Momentary, FieldQoS.AutomaticReadout)); } }, null, 1000 - PeriodStart.Millisecond, 1000); BobClient BobClient = new BobClient(Client, Path.Combine(Path.GetTempPath(), "BitsOfBinary")); ChatServer ChatServer = new ChatServer(Client, BobClient, SensorServer, ProvisioningClient); InteroperabilityServer InteroperabilityServer = new InteroperabilityServer(Client); InteroperabilityServer.OnGetInterfaces += (sender, e) => { e.Add("XMPP.IoT.Sensor.Temperature", "XMPP.IoT.Sensor.Temperature.History", "XMPP.IoT.Sensor.Temperature.Average", "XMPP.IoT.Sensor.Temperature.Average.History", "XMPP.IoT.Sensor.Temperature.Min", "XMPP.IoT.Sensor.Temperature.Min.History", "XMPP.IoT.Sensor.Temperature.Max", "XMPP.IoT.Sensor.Temperature.Max.History"); }; Client.Connect(); while (true) { Thread.Sleep(1000); } } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.Out.WriteLine(ex.Message); } finally { Log.Terminate(); } }
public static void Main(string[] _) { try { Console.ForegroundColor = ConsoleColor.White; Console.Out.WriteLine("Welcome to the PC Sensor application."); Console.Out.WriteLine(new string('-', 79)); Console.Out.WriteLine("This application will publish performace couters as sensor values."); Console.Out.WriteLine("Values will be published over XMPP using the interface defined in the IEEE XMPP IoT extensions."); Log.Register(new ConsoleEventSink(false)); Log.RegisterExceptionToUnnest(typeof(System.Runtime.InteropServices.ExternalException)); Log.RegisterExceptionToUnnest(typeof(System.Security.Authentication.AuthenticationException)); credentials = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config", Environment.MachineName, // Default user name. Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password. typeof(Program).Assembly); using (XmppClient Client = new XmppClient(credentials, "en", typeof(Program).Assembly)) { if (credentials.Sniffer) { Client.Add(new ConsoleOutSniffer(BinaryPresentationMethod.ByteCount, LineEnding.PadWithSpaces)); } if (!string.IsNullOrEmpty(credentials.Events)) { Log.Register(new XmppEventSink("XMPP Event Sink", Client, credentials.Events, false)); } if (!string.IsNullOrEmpty(credentials.ThingRegistry)) { thingRegistryClient = new ThingRegistryClient(Client, credentials.ThingRegistry); thingRegistryClient.Claimed += (sender, e) => { ownerJid = e.JID; Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair <string, object>("Public", e.IsPublic)); return(Task.CompletedTask); }; thingRegistryClient.Disowned += (sender, e) => { Log.Informational("Thing has been disowned.", ownerJid); ownerJid = string.Empty; Register(); return(Task.CompletedTask); }; thingRegistryClient.Removed += (sender, e) => { Log.Informational("Thing has been removed from the public registry.", ownerJid); return(Task.CompletedTask); }; } ProvisioningClient ProvisioningClient = null; if (!string.IsNullOrEmpty(credentials.Provisioning)) { ProvisioningClient = new ProvisioningClient(Client, credentials.Provisioning); } Timer ConnectionTimer = new Timer((P) => { if (Client.State == XmppState.Offline || Client.State == XmppState.Error || Client.State == XmppState.Authenticating) { try { Client.Reconnect(); } catch (Exception ex) { Log.Critical(ex); } } }, null, 60000, 60000); bool Connected = false; bool ImmediateReconnect; Client.OnStateChanged += (sender, NewState) => { switch (NewState) { case XmppState.Connected: Connected = true; if (!registered && thingRegistryClient != null) { Register(); } break; case XmppState.Offline: ImmediateReconnect = Connected; Connected = false; if (ImmediateReconnect) { Client.Reconnect(); } break; } return(Task.CompletedTask); }; Client.OnPresenceSubscribe += (sender, e) => { e.Accept(); // TODO: Provisioning RosterItem Item = Client.GetRosterItem(e.FromBareJID); if (Item is null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From) { Client.RequestPresenceSubscription(e.FromBareJID); } Client.SetPresence(Availability.Chat); return(Task.CompletedTask); }; Client.OnPresenceUnsubscribe += (sender, e) => { e.Accept(); return(Task.CompletedTask); }; Client.OnRosterItemUpdated += (sender, e) => { if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe) { Client.RemoveRosterItem(e.BareJid); } return(Task.CompletedTask); }; SortedDictionary <string, string[]> CategoryIncluded = new SortedDictionary <string, string[]>(); List <string> Instances = new List <string>(); XmlDocument Doc = new XmlDocument() { PreserveWhitespace = true }; Doc.Load("categories.xml"); XSL.Validate("categories.xml", Doc, "Categories", "http://waher.se/Schema/PerformanceCounterCategories.xsd", XSL.LoadSchema("Waher.Service.PcSensor.Schema.PerformanceCounterCategories.xsd")); foreach (XmlNode N in Doc.DocumentElement.ChildNodes) { if (N.LocalName == "Category") { XmlElement E = (XmlElement)N; string Name = XML.Attribute(E, "name"); bool Include = XML.Attribute(E, "include", false); if (Include) { Instances.Clear(); foreach (XmlNode N2 in N.ChildNodes) { if (N2.LocalName == "Instance") { E = (XmlElement)N2; Instances.Add(XML.Attribute(E, "name")); } } CategoryIncluded[Name] = Instances.ToArray(); } else { CategoryIncluded[Name] = null; } } } SensorServer SensorServer = new SensorServer(Client, ProvisioningClient, false); SensorServer.OnExecuteReadoutRequest += (Sender, Request) => { Log.Informational("Readout requested", string.Empty, Request.Actor); List <Field> Fields = new List <Field>(); DateTime Now = DateTime.Now; Fields.Add(new StringField(ThingReference.Empty, Now, "Machine Name", Environment.MachineName, FieldType.Identity, FieldQoS.AutomaticReadout)); Fields.Add(new StringField(ThingReference.Empty, Now, "OS Platform", Environment.OSVersion.Platform.ToString(), FieldType.Identity, FieldQoS.AutomaticReadout)); Fields.Add(new StringField(ThingReference.Empty, Now, "OS Service Pack", Environment.OSVersion.ServicePack, FieldType.Identity, FieldQoS.AutomaticReadout)); Fields.Add(new StringField(ThingReference.Empty, Now, "OS Version", Environment.OSVersion.VersionString, FieldType.Identity, FieldQoS.AutomaticReadout)); Fields.Add(new Int32Field(ThingReference.Empty, Now, "Processor Count", Environment.ProcessorCount, FieldType.Status, FieldQoS.AutomaticReadout)); string[] InstanceNames; string FieldName; string Unit; double Value; byte NrDec; bool Updated = false; foreach (PerformanceCounterCategory Category in PerformanceCounterCategory.GetCategories()) { FieldName = Category.CategoryName; lock (CategoryIncluded) { if (CategoryIncluded.TryGetValue(FieldName, out InstanceNames)) { if (InstanceNames is null) { continue; } } else { CategoryIncluded[FieldName] = null; Updated = true; continue; } } if (Category.CategoryType == PerformanceCounterCategoryType.MultiInstance) { foreach (string InstanceName in Category.GetInstanceNames()) { if (InstanceNames.Length > 0 && Array.IndexOf <string>(InstanceNames, InstanceName) < 0) { continue; } foreach (PerformanceCounter Counter in Category.GetCounters(InstanceName)) { FieldName = Category.CategoryName + ", " + InstanceName + ", " + Counter.CounterName; Value = Counter.NextValue(); GetUnitPrecision(ref FieldName, Value, out NrDec, out Unit); if (Fields.Count >= 100) { Request.ReportFields(false, Fields); Fields.Clear(); } Fields.Add(new QuantityField(ThingReference.Empty, Now, FieldName, Value, NrDec, Unit, FieldType.Momentary, FieldQoS.AutomaticReadout)); } } } else { foreach (PerformanceCounter Counter in Category.GetCounters()) { FieldName = Category.CategoryName + ", " + Counter.CounterName; Value = Counter.NextValue(); GetUnitPrecision(ref FieldName, Value, out NrDec, out Unit); if (Fields.Count >= 100) { Request.ReportFields(false, Fields); Fields.Clear(); } Fields.Add(new QuantityField(ThingReference.Empty, Now, FieldName, Value, NrDec, Unit, FieldType.Momentary, FieldQoS.AutomaticReadout)); } } } Request.ReportFields(true, Fields); if (Updated) { using (StreamWriter s = File.CreateText("categories.xml")) { using (XmlWriter w = XmlWriter.Create(s, XML.WriterSettings(true, false))) { w.WriteStartElement("Categories", "http://waher.se/Schema/PerformanceCounterCategories.xsd"); lock (CategoryIncluded) { foreach (KeyValuePair <string, string[]> P in CategoryIncluded) { w.WriteStartElement("Category"); w.WriteAttributeString("name", P.Key); w.WriteAttributeString("include", CommonTypes.Encode(P.Value != null)); if (P.Value != null) { foreach (string InstanceName in P.Value) { w.WriteStartElement("Instance"); w.WriteAttributeString("name", P.Key); w.WriteEndElement(); } } w.WriteEndElement(); } } w.WriteEndElement(); w.Flush(); } } } return(Task.CompletedTask); }; BobClient BobClient = new BobClient(Client, Path.Combine(Path.GetTempPath(), "BitsOfBinary")); ChatServer ChatServer = new ChatServer(Client, BobClient, SensorServer, ProvisioningClient); Client.Connect(); while (true) { Thread.Sleep(1000); } } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.Out.WriteLine(ex.Message); } finally { Log.Terminate(); } }
/// <summary> /// Initializes an instance of an actor. /// </summary> public override async Task InitializeInstance() { this.xmppCredentials = await this.GetInstanceCredentials(); this.sniffer = this.Model.GetSniffer(this.userName); if (this.sniffer is null) { this.client = new XmppClient(this.xmppCredentials, "en", typeof(XmppActor).GetTypeInfo().Assembly); } else { this.client = new XmppClient(this.xmppCredentials, "en", typeof(XmppActor).GetTypeInfo().Assembly, this.sniffer); } this.client.OnStateChanged += this.Client_OnStateChanged; this.client.OnChatMessage += Client_OnChatMessage; this.client.OnConnectionError += Client_OnConnectionError; this.client.OnError += Client_OnError; this.client.OnErrorMessage += Client_OnErrorMessage; this.client.OnGroupChatMessage += Client_OnGroupChatMessage; this.client.OnHeadlineMessage += Client_OnHeadlineMessage; this.client.OnNormalMessage += Client_OnNormalMessage; this.client.OnPresence += Client_OnPresence; this.client.OnPresenceSubscribe += Client_OnPresenceSubscribe; this.client.OnRosterItemAdded += Client_OnRosterItemAdded; this.client.OnRosterItemRemoved += Client_OnRosterItemRemoved; this.client.OnRosterItemUpdated += Client_OnRosterItemUpdated; this.client.CustomPresenceXml += Client_CustomPresenceXml; string InstanceIndexSuffix = this.InstanceIndex.ToString(); int c = this.N.ToString().Length; int Nr0 = c - InstanceIndexSuffix.Length; if (Nr0 > 0) { InstanceIndexSuffix = new string('0', Nr0) + InstanceIndexSuffix; } if (this.Parent is IActor ParentActor) { foreach (ISimulationNode Node in ParentActor.Children) { if (Node is HandlerNode HandlerNode) { HandlerNode.RegisterHandlers(this, this.client); } if (Node is Extensions.IXmppExtension Extension) { object ExtensionObj = await Extension.Add(this, Client); if (!string.IsNullOrEmpty(Extension.Id)) { this.Model.Variables[Extension.Id + InstanceIndexSuffix] = ExtensionObj; } } } } if (this.alwaysConnected) { this.client.Connect(this.domain); if (this.xmppCredentials.AllowRegistration) { switch (await this.client.WaitStateAsync(30000, XmppState.Connected, XmppState.Error, XmppState.Offline)) { case 0: // Connected break; case 1: // Error case 2: // Offline default: throw new Exception("Unable to create account for " + this.userName + "@" + this.domain); } } } }
internal static Task XmppCredentialsUpdated(string XmppConfigFileName, XmppCredentials Credentials) { SimpleXmppConfiguration.SaveSimpleXmppConfiguration(XmppConfigFileName, Credentials); return(Task.CompletedTask); }
private async void StartActuator() { try { Log.Informational("Starting application."); XmppCredentials Credentials = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config", Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name. Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password. typeof(App).GetTypeInfo().Assembly); Log.Informational("Connecting to XMPP server."); xmppClient = new XmppClient(Credentials, "en", typeof(App).GetTypeInfo().Assembly); if (Credentials.Sniffer && MainPage.Sniffer != null) { xmppClient.Add(MainPage.Sniffer); } if (!string.IsNullOrEmpty(Credentials.Events)) { Log.Register(new XmppEventSink("XMPP Event Sink", xmppClient, Credentials.Events, false)); } if (!string.IsNullOrEmpty(Credentials.ThingRegistry)) { thingRegistryClient = new ThingRegistryClient(xmppClient, Credentials.ThingRegistry); thingRegistryClient.Claimed += (sender, e) => { ownerJid = e.JID; Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair <string, object>("Public", e.IsPublic)); this.RaiseOwnershipChanged(); }; thingRegistryClient.Disowned += (sender, e) => { Log.Informational("Thing has been disowned.", ownerJid); ownerJid = string.Empty; this.Register(); // Will call this.OwnershipChanged() after successful registration. }; thingRegistryClient.Removed += (sender, e) => { Log.Informational("Thing has been removed from the public registry.", ownerJid); }; } if (!string.IsNullOrEmpty(Credentials.Provisioning)) { provisioningClient = new ProvisioningClient(xmppClient, Credentials.Provisioning); } Timer ConnectionTimer = new Timer((P) => { if (xmppClient.State == XmppState.Offline || xmppClient.State == XmppState.Error || xmppClient.State == XmppState.Authenticating) { try { Log.Informational("Reconnecting."); xmppClient.Reconnect(); } catch (Exception ex) { Log.Critical(ex); } } }, null, 60000, 60000); xmppClient.OnStateChanged += (sender, NewState) => { Log.Informational(NewState.ToString()); switch (NewState) { case XmppState.Connected: connected = true; if (!registered && this.thingRegistryClient != null) { this.Register(); } break; case XmppState.Offline: immediateReconnect = connected; connected = false; if (immediateReconnect) { xmppClient.Reconnect(); } break; } }; xmppClient.OnPresenceSubscribe += (sender, e) => { Log.Informational("Subscription request received from " + e.From + "."); e.Accept(); // TODO: Provisioning RosterItem Item = xmppClient.GetRosterItem(e.FromBareJID); if (Item == null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From) { xmppClient.RequestPresenceSubscription(e.FromBareJID); } xmppClient.SetPresence(Availability.Chat); }; xmppClient.OnPresenceUnsubscribe += (sender, e) => { Log.Informational("Unsubscription request received from " + e.From + "."); e.Accept(); }; xmppClient.OnRosterItemUpdated += (sender, e) => { if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe) { xmppClient.RemoveRosterItem(e.BareJid); } }; gpio = GpioController.GetDefault(); if (gpio != null) { int c = gpio.PinCount; int i; for (i = 0; i < c; i++) { if (gpio.TryOpenPin(i, GpioSharingMode.Exclusive, out GpioPin Pin, out GpioOpenStatus Status) && Status == GpioOpenStatus.PinOpened) { gpioPins[i] = new KeyValuePair <GpioPin, KeyValuePair <TextBlock, TextBlock> >(Pin, MainPage.Instance.AddPin("GPIO" + i.ToString(), Pin.GetDriveMode(), Pin.Read().ToString())); Pin.ValueChanged += async(sender, e) => { if (!this.gpioPins.TryGetValue(sender.PinNumber, out KeyValuePair <GpioPin, KeyValuePair <TextBlock, TextBlock> > P)) { return; } PinState Value = e.Edge == GpioPinEdge.FallingEdge ? PinState.LOW : PinState.HIGH; if (this.sensorServer.HasSubscriptions(ThingReference.Empty)) { DateTime TP = DateTime.Now; string s = "GPIO" + sender.PinNumber.ToString(); this.sensorServer.NewMomentaryValues( new EnumField(ThingReference.Empty, TP, s, Value, FieldType.Momentary, FieldQoS.AutomaticReadout)); } await P.Value.Value.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => P.Value.Value.Text = Value.ToString()); }; } } } DeviceInformationCollection Devices = await Microsoft.Maker.Serial.UsbSerial.listAvailableDevicesAsync(); foreach (DeviceInformation DeviceInfo in Devices) { if (DeviceInfo.IsEnabled && DeviceInfo.Name.StartsWith("Arduino")) { Log.Informational("Connecting to " + DeviceInfo.Name); arduinoUsb = new UsbSerial(DeviceInfo); arduinoUsb.ConnectionEstablished += () => { Log.Informational("USB connection established."); }; arduino = new RemoteDevice(arduinoUsb); arduino.DeviceReady += async() => { Log.Informational("Device ready."); Dictionary <int, bool> DisabledPins = new Dictionary <int, bool>(); Dictionary <string, KeyValuePair <Enum, string> > Values = new Dictionary <string, KeyValuePair <Enum, string> >(); PinMode Mode; PinState State; string s; ushort Value; foreach (byte PinNr in arduino.DeviceHardwareProfile.DisabledPins) { DisabledPins[PinNr] = true; } foreach (byte PinNr in arduino.DeviceHardwareProfile.AnalogPins) { if (DisabledPins.ContainsKey(PinNr)) { continue; } s = "A" + (PinNr - arduino.DeviceHardwareProfile.AnalogOffset).ToString(); if (arduino.DeviceHardwareProfile.isAnalogSupported(PinNr)) { arduino.pinMode(s, PinMode.ANALOG); } Mode = arduino.getPinMode(s); Value = arduino.analogRead(s); Values[s] = new KeyValuePair <Enum, string>(Mode, Value.ToString()); } foreach (byte PinNr in arduino.DeviceHardwareProfile.DigitalPins) { if (DisabledPins.ContainsKey(PinNr) || (PinNr > 6 && PinNr != 13)) // Not sure why this limitation is necessary. Without it, my Arduino board (or the Microsoft Firmata library) stops providing me with pin update events. { continue; } if (PinNr == 13) { arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED. arduino.digitalWrite(13, PinState.HIGH); } else { if (arduino.DeviceHardwareProfile.isDigitalInputSupported(PinNr)) { arduino.pinMode(PinNr, PinMode.INPUT); } } s = "D" + PinNr.ToString(); Mode = arduino.getPinMode(PinNr); State = arduino.digitalRead(PinNr); Values[s] = new KeyValuePair <Enum, string>(Mode, State.ToString()); } await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { lock (arduinoPins) { foreach (KeyValuePair <string, KeyValuePair <Enum, string> > P in Values) { arduinoPins[P.Key] = MainPage.Instance.AddPin(P.Key, P.Value.Key, P.Value.Value); } } }); this.SetupControlServer(); }; arduino.AnalogPinUpdated += async(pin, value) => { KeyValuePair <TextBlock, TextBlock> P; DateTime TP = DateTime.Now; lock (this.arduinoPins) { if (!this.arduinoPins.TryGetValue(pin, out P)) { return; } } if (this.sensorServer.HasSubscriptions(ThingReference.Empty)) { this.sensorServer.NewMomentaryValues( new Int32Field(ThingReference.Empty, TP, pin + ", Raw", value, FieldType.Momentary, FieldQoS.AutomaticReadout), new QuantityField(ThingReference.Empty, TP, pin, value / 10.24, 2, "%", FieldType.Momentary, FieldQoS.AutomaticReadout)); } await P.Value.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => P.Value.Text = value.ToString()); }; arduino.DigitalPinUpdated += async(pin, value) => { KeyValuePair <TextBlock, TextBlock> P; DateTime TP = DateTime.Now; string s = "D" + pin.ToString(); lock (this.arduinoPins) { if (!this.arduinoPins.TryGetValue("D" + pin.ToString(), out P)) { return; } } if (this.sensorServer.HasSubscriptions(ThingReference.Empty)) { this.sensorServer.NewMomentaryValues( new EnumField(ThingReference.Empty, TP, s, value, FieldType.Momentary, FieldQoS.AutomaticReadout)); } await P.Value.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => P.Value.Text = value.ToString()); }; arduinoUsb.ConnectionFailed += message => { Log.Error("USB connection failed: " + message); }; arduinoUsb.ConnectionLost += message => { Log.Error("USB connection lost: " + message); }; arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1); break; } } sensorServer = new SensorServer(xmppClient, provisioningClient, true); sensorServer.OnExecuteReadoutRequest += (Sender, Request) => { DateTime Now = DateTime.Now; LinkedList <Field> Fields = new LinkedList <Field>(); DateTime TP = DateTime.Now; string s; bool ReadMomentary = Request.IsIncluded(FieldType.Momentary); bool ReadStatus = Request.IsIncluded(FieldType.Status); Log.Informational("Readout requested", string.Empty, Request.Actor); foreach (KeyValuePair <GpioPin, KeyValuePair <TextBlock, TextBlock> > Pin in gpioPins.Values) { if (ReadMomentary && Request.IsIncluded(s = "GPIO" + Pin.Key.PinNumber.ToString())) { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, Pin.Key.Read(), FieldType.Momentary, FieldQoS.AutomaticReadout)); } if (ReadStatus && Request.IsIncluded(s = "GPIO" + Pin.Key.PinNumber.ToString() + ", Mode")) { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, Pin.Key.GetDriveMode(), FieldType.Status, FieldQoS.AutomaticReadout)); } } if (arduinoPins != null) { foreach (KeyValuePair <string, KeyValuePair <TextBlock, TextBlock> > Pin in arduinoPins) { byte i; if (ReadMomentary && Request.IsIncluded(s = Pin.Key)) { if (s.StartsWith("D") && byte.TryParse(s.Substring(1), out i)) { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, arduino.digitalRead(i), FieldType.Momentary, FieldQoS.AutomaticReadout)); } else { ushort Raw = arduino.analogRead(s); double Percent = Raw / 10.24; Fields.AddLast(new Int32Field(ThingReference.Empty, TP, s + ", Raw", Raw, FieldType.Momentary, FieldQoS.AutomaticReadout)); Fields.AddLast(new QuantityField(ThingReference.Empty, TP, s, Percent, 2, "%", FieldType.Momentary, FieldQoS.AutomaticReadout)); } } if (ReadStatus && Request.IsIncluded(s = Pin.Key + ", Mode")) { if (s.StartsWith("D") && byte.TryParse(s.Substring(1), out i)) { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, arduino.getPinMode(i), FieldType.Status, FieldQoS.AutomaticReadout)); } else { Fields.AddLast(new EnumField(ThingReference.Empty, TP, s, arduino.getPinMode(s), FieldType.Status, FieldQoS.AutomaticReadout)); } } } } Request.ReportFields(true, Fields); }; if (arduino == null) { this.SetupControlServer(); } xmppClient.Connect(); } catch (Exception ex) { Log.Emergency(ex); MessageDialog Dialog = new MessageDialog(ex.Message, "Error"); await Dialog.ShowAsync(); } }
private void ConnectButton_Click(object sender, RoutedEventArgs e) { XmppCredentials Credentials = new XmppCredentials() { Host = this.XmppServer.Text, Account = this.AccountName.Text }; switch ((TransportMethod)this.ConnectionMethod.SelectedIndex) { case TransportMethod.TraditionalSocket: if (!int.TryParse(this.XmppPort.Text, out int Port) || Port <= 0 || Port > 65535) { MessageBox.Show(this, "Invalid port number. Valid port numbers are positive integers between 1 and 65535. The default port number is " + XmppCredentials.DefaultPort.ToString() + ".", "Error", MessageBoxButton.OK, MessageBoxImage.Error); this.XmppPort.Focus(); return; } Credentials.Port = Port; break; case TransportMethod.WS: Uri Uri; try { Uri = new Uri(this.UrlEndpoint.Text); } catch (Exception) { MessageBox.Show(this, "Invalid URI.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); this.UrlEndpoint.Focus(); return; } string Scheme = Uri.Scheme.ToLower(); if (Scheme != "ws" && Scheme != "wss") { MessageBox.Show(this, "Resource must be an WS or WSS URI.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); this.UrlEndpoint.Focus(); return; } if (!Uri.IsAbsoluteUri) { MessageBox.Show(this, "URI must be an absolute URI.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); this.UrlEndpoint.Focus(); return; } Credentials.UriEndpoint = this.UrlEndpoint.Text; break; case TransportMethod.BOSH: try { Uri = new Uri(this.UrlEndpoint.Text); } catch (Exception) { MessageBox.Show(this, "Invalid URI.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); this.UrlEndpoint.Focus(); return; } Scheme = Uri.Scheme.ToLower(); if (Scheme != "http" && Scheme != "https") { MessageBox.Show(this, "Resource must be an HTTP or HTTPS URI.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); this.UrlEndpoint.Focus(); return; } if (!Uri.IsAbsoluteUri) { MessageBox.Show(this, "URI must be an absolute URI.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); this.UrlEndpoint.Focus(); return; } Credentials.UriEndpoint = this.UrlEndpoint.Text; break; } bool Create = this.CreateAccount.IsChecked.HasValue && this.CreateAccount.IsChecked.Value; if (Create && this.Password.Password != this.RetypePassword.Password) { MessageBox.Show(this, "The two passwords must match.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); this.Password.Focus(); return; } this.CloseClient(); this.ConnectButton.IsEnabled = false; this.XmppServer.IsEnabled = false; this.ConnectionMethod.IsEnabled = false; this.XmppPort.IsEnabled = false; this.UrlEndpoint.IsEnabled = false; this.AccountName.IsEnabled = false; this.Password.IsEnabled = false; this.RetypePassword.IsEnabled = false; this.TrustServerCertificate.IsEnabled = false; this.CreateAccount.IsEnabled = false; if (this.Password.Password == this.passwordHash && !string.IsNullOrEmpty(this.passwordHash)) { Credentials.Password = this.passwordHash; Credentials.PasswordType = this.passwordHashMethod; } else { Credentials.Password = this.Password.Password; } if (this.AllowInsecureAuthentication.IsChecked.HasValue && this.AllowInsecureAuthentication.IsChecked.Value) { Credentials.AllowPlain = true; Credentials.AllowCramMD5 = true; Credentials.AllowDigestMD5 = true; } if (this.TrustServerCertificate.IsChecked.HasValue && this.TrustServerCertificate.IsChecked.Value) { Credentials.TrustServer = true; } this.client = new XmppClient(Credentials, "en", typeof(App).Assembly); if (Create) { this.client.AllowRegistration(this.ApiKey.Text, this.Secret.Password); this.client.OnRegistrationForm += Client_OnRegistrationForm; } this.client.OnStateChanged += this.Client_OnStateChanged; this.client.OnConnectionError += this.Client_OnConnectionError; this.client.Connect(); }
static void Main(string[] args) { try { Console.ForegroundColor = ConsoleColor.White; Console.Out.WriteLine("Welcome to the Mock Temperature sensor application."); Console.Out.WriteLine(new string('-', 79)); Console.Out.WriteLine("This application will simulate an outside temperature sensor."); Console.Out.WriteLine("Values will be published over XMPP using the interface defined in the IEEE XMPP IoT extensions."); Console.Out.WriteLine("You can also chat with the sensor."); Log.Register(new ConsoleEventSink()); Log.RegisterExceptionToUnnest(typeof(System.Runtime.InteropServices.ExternalException)); Log.RegisterExceptionToUnnest(typeof(System.Security.Authentication.AuthenticationException)); credentials = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config", Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name. Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password. typeof(Program).Assembly); using (XmppClient Client = new XmppClient(credentials, "en", typeof(Program).Assembly)) { if (credentials.Sniffer) { Client.Add(new ConsoleOutSniffer(BinaryPresentationMethod.ByteCount, LineEnding.PadWithSpaces)); } if (!string.IsNullOrEmpty(credentials.Events)) { Log.Register(new XmppEventSink("XMPP Event Sink", Client, credentials.Events, false)); } if (!string.IsNullOrEmpty(credentials.ThingRegistry)) { thingRegistryClient = new ThingRegistryClient(Client, credentials.ThingRegistry); thingRegistryClient.Claimed += (sender, e) => { ownerJid = e.JID; Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair <string, object>("Public", e.IsPublic)); }; thingRegistryClient.Disowned += (sender, e) => { Log.Informational("Thing has been disowned.", ownerJid); ownerJid = string.Empty; Register(); }; thingRegistryClient.Removed += (sender, e) => { Log.Informational("Thing has been removed from the public registry.", ownerJid); }; } ProvisioningClient ProvisioningClient = null; if (!string.IsNullOrEmpty(credentials.Provisioning)) { ProvisioningClient = new ProvisioningClient(Client, credentials.Provisioning); } Timer ConnectionTimer = new Timer((P) => { if (Client.State == XmppState.Offline || Client.State == XmppState.Error || Client.State == XmppState.Authenticating) { try { Client.Reconnect(); } catch (Exception ex) { Log.Critical(ex); } } }, null, 60000, 60000); bool Connected = false; bool ImmediateReconnect; Client.OnStateChanged += (sender, NewState) => { switch (NewState) { case XmppState.Connected: Connected = true; if (!registered && thingRegistryClient != null) { Register(); } break; case XmppState.Offline: ImmediateReconnect = Connected; Connected = false; if (ImmediateReconnect) { Client.Reconnect(); } break; } }; Client.OnPresenceSubscribe += (sender, e) => { e.Accept(); // TODO: Provisioning RosterItem Item = Client.GetRosterItem(e.FromBareJID); if (Item is null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From) { Client.RequestPresenceSubscription(e.FromBareJID); } Client.SetPresence(Availability.Chat); }; Client.OnPresenceUnsubscribe += (sender, e) => { e.Accept(); }; Client.OnRosterItemUpdated += (sender, e) => { if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe) { Client.RemoveRosterItem(e.BareJid); } }; bool SwitchOn = false; SensorServer SensorServer = new SensorServer(Client, ProvisioningClient, false); SensorServer.OnExecuteReadoutRequest += (Sender, Request) => { DateTime Now = DateTime.Now; Log.Informational("Readout requested", string.Empty, Request.Actor); Request.ReportFields(true, new BooleanField(ThingReference.Empty, Now, "Lamp", SwitchOn, FieldType.Momentary, FieldQoS.AutomaticReadout)); }; ControlServer ControlServer = new ControlServer(Client, new BooleanControlParameter("Lamp", "Control", "Lamp switch on.", "If checked, lamp is turned on.", (Node) => SwitchOn, (Node, Value) => { SwitchOn = Value; Log.Informational(Environment.NewLine + Environment.NewLine + "Lamp turned " + (SwitchOn ? "ON" : "OFF") + Environment.NewLine + Environment.NewLine); })); BobClient BobClient = new BobClient(Client, Path.Combine(Path.GetTempPath(), "BitsOfBinary")); ChatServer ChatServer = new ChatServer(Client, BobClient, SensorServer, ControlServer, ProvisioningClient); InteroperabilityServer InteroperabilityServer = new InteroperabilityServer(Client); InteroperabilityServer.OnGetInterfaces += (sender, e) => { e.Add("XMPP.IoT.Actuator.Lamp"); }; Client.Connect(); while (true) { Thread.Sleep(1000); } } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.Out.WriteLine(ex.Message); } finally { Log.Terminate(); } }
private async void StartSensor() { try { Log.Informational("Starting application."); XmppCredentials Credentials = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config", Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name. Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password. typeof(App).GetTypeInfo().Assembly); Log.Informational("Connecting to XMPP server."); xmppClient = new XmppClient(Credentials, "en", typeof(App).GetTypeInfo().Assembly); if (Credentials.Sniffer && MainPage.Sniffer != null) { xmppClient.Add(MainPage.Sniffer); } if (!string.IsNullOrEmpty(Credentials.Events)) { Log.Register(new XmppEventSink("XMPP Event Sink", xmppClient, Credentials.Events, false)); } if (!string.IsNullOrEmpty(Credentials.ThingRegistry)) { thingRegistryClient = new ThingRegistryClient(xmppClient, Credentials.ThingRegistry); thingRegistryClient.Claimed += (sender, e) => { ownerJid = e.JID; Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair <string, object>("Public", e.IsPublic)); this.RaiseOwnershipChanged(); }; thingRegistryClient.Disowned += (sender, e) => { Log.Informational("Thing has been disowned.", ownerJid); ownerJid = string.Empty; this.Register(); // Will call this.OwnershipChanged() after successful registration. }; thingRegistryClient.Removed += (sender, e) => { Log.Informational("Thing has been removed from the public registry.", ownerJid); }; } if (!string.IsNullOrEmpty(Credentials.Provisioning)) { provisioningClient = new ProvisioningClient(xmppClient, Credentials.Provisioning); } Timer ConnectionTimer = new Timer((P) => { if (xmppClient.State == XmppState.Offline || xmppClient.State == XmppState.Error || xmppClient.State == XmppState.Authenticating) { try { Log.Informational("Reconnecting."); xmppClient.Reconnect(); } catch (Exception ex) { Log.Critical(ex); } } }, null, 60000, 60000); xmppClient.OnStateChanged += (sender, NewState) => { Log.Informational(NewState.ToString()); switch (NewState) { case XmppState.Connected: connected = true; if (!registered && thingRegistryClient != null) { this.Register(); } break; case XmppState.Offline: immediateReconnect = connected; connected = false; if (immediateReconnect) { xmppClient.Reconnect(); } break; } }; xmppClient.OnPresenceSubscribe += (sender, e) => { Log.Informational("Subscription request received from " + e.From + "."); e.Accept(); // TODO: Provisioning RosterItem Item = xmppClient.GetRosterItem(e.FromBareJID); if (Item is null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From) { xmppClient.RequestPresenceSubscription(e.FromBareJID); } xmppClient.SetPresence(Availability.Chat); }; xmppClient.OnPresenceUnsubscribe += (sender, e) => { Log.Informational("Unsubscription request received from " + e.From + "."); e.Accept(); }; xmppClient.OnRosterItemUpdated += (sender, e) => { if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe) { xmppClient.RemoveRosterItem(e.BareJid); } }; LinkedList <DayHistoryRecord> DayHistoricalValues = new LinkedList <DayHistoryRecord>(); LinkedList <MinuteHistoryRecord> MinuteHistoricalValues = new LinkedList <MinuteHistoryRecord>(); DateTime SampleTime = DateTime.Now; DateTime PeriodStart = SampleTime.Date; DateTime Now; DateTime MinTime = SampleTime; DateTime MaxTime = SampleTime; double CurrentTemperature = this.ReadTemp(); double MinTemp = CurrentTemperature; double MaxTemp = CurrentTemperature; double SumTemp = CurrentTemperature; int NrTemp = 1; int NrDayRecords = 0; int NrMinuteRecords = 0; object SampleSynch = new object(); this.sampleTimer = new Timer((P) => { lock (SampleSynch) { Now = DateTime.Now; if (Now.Date != PeriodStart.Date) { DayHistoryRecord Rec = new DayHistoryRecord(PeriodStart.Date, PeriodStart.Date.AddDays(1).AddMilliseconds(-1), MinTemp, MaxTemp, SumTemp / NrTemp); DayHistoricalValues.AddFirst(Rec); if (NrDayRecords < MaxRecordsPerPeriod) { NrDayRecords++; } else { DayHistoricalValues.RemoveLast(); } // TODO: Persistence PeriodStart = Now.Date; SumTemp = 0; NrTemp = 0; } CurrentTemperature = this.ReadTemp(); if (Now.Minute != SampleTime.Minute) { MinuteHistoryRecord Rec = new MinuteHistoryRecord(Now, CurrentTemperature); MinuteHistoricalValues.AddFirst(Rec); if (NrMinuteRecords < MaxRecordsPerPeriod) { NrMinuteRecords++; } else { MinuteHistoricalValues.RemoveLast(); } // TODO: Persistence } SampleTime = Now; if (CurrentTemperature < MinTemp) { MinTemp = CurrentTemperature; MinTime = SampleTime; } if (CurrentTemperature > MaxTemp) { MaxTemp = CurrentTemperature; MaxTime = SampleTime; } SumTemp += CurrentTemperature; NrTemp++; } if (this.sensorServer.HasSubscriptions(ThingReference.Empty)) { this.sensorServer.NewMomentaryValues(new QuantityField(ThingReference.Empty, SampleTime, "Temperature", CurrentTemperature, 1, "°C", FieldType.Momentary, FieldQoS.AutomaticReadout)); } this.UpdateMainWindow(CurrentTemperature, MinTemp, MaxTemp, SumTemp / NrTemp); }, null, 1000 - PeriodStart.Millisecond, 1000); this.sensorServer = new SensorServer(xmppClient, provisioningClient, true); this.sensorServer.OnExecuteReadoutRequest += (Sender, Request) => { Log.Informational("Readout requested by " + Request.From, string.Empty, Request.Actor); List <Field> Fields = new List <Field>(); bool IncludeTemp = Request.IsIncluded("Temperature"); bool IncludeTempMin = Request.IsIncluded("Temperature, Min"); bool IncludeTempMax = Request.IsIncluded("Temperature, Max"); bool IncludeTempAvg = Request.IsIncluded("Temperature, Average"); bool IncludePeak = Request.IsIncluded(FieldType.Peak); bool IncludeComputed = Request.IsIncluded(FieldType.Computed); lock (SampleSynch) { if (IncludeTemp && Request.IsIncluded(FieldType.Momentary)) { Fields.Add(new QuantityField(ThingReference.Empty, SampleTime, "Temperature", CurrentTemperature, 1, "°C", FieldType.Momentary, FieldQoS.AutomaticReadout)); } if (IncludePeak) { if (IncludeTempMin) { Fields.Add(new QuantityField(ThingReference.Empty, MinTime, "Temperature, Min", MinTemp, 1, "°C", FieldType.Peak, FieldQoS.AutomaticReadout)); } if (IncludeTempMax) { Fields.Add(new QuantityField(ThingReference.Empty, MaxTime, "Temperature, Max", MaxTemp, 1, "°C", FieldType.Peak, FieldQoS.AutomaticReadout)); } } if (IncludeTempAvg && IncludeComputed) { Fields.Add(new QuantityField(ThingReference.Empty, SampleTime, "Temperature, Average", SumTemp / NrTemp, 2, "°C", FieldType.Computed, FieldQoS.AutomaticReadout)); } if (Request.IsIncluded(FieldType.Historical)) { foreach (DayHistoryRecord Rec in DayHistoricalValues) { if (!Request.IsIncluded(Rec.PeriodStart)) { continue; } if (Fields.Count >= 100) { Request.ReportFields(false, Fields); Fields.Clear(); } if (IncludePeak) { if (IncludeTempMin) { Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Min", Rec.MinTemperature, 1, "°C", FieldType.Peak | FieldType.Historical, FieldQoS.AutomaticReadout)); } if (IncludeTempMax) { Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Max", Rec.MaxTemperature, 1, "°C", FieldType.Peak | FieldType.Historical, FieldQoS.AutomaticReadout)); } } if (IncludeTempAvg && IncludeComputed) { Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Average", Rec.AverageTemperature, 1, "°C", FieldType.Computed | FieldType.Historical, FieldQoS.AutomaticReadout)); } } foreach (MinuteHistoryRecord Rec in MinuteHistoricalValues) { if (!Request.IsIncluded(Rec.Timestamp)) { continue; } if (IncludeTemp) { if (Fields.Count >= 100) { Request.ReportFields(false, Fields); Fields.Clear(); } Fields.Add(new QuantityField(ThingReference.Empty, Rec.Timestamp, "Temperature", Rec.Temperature, 1, "°C", FieldType.Historical, FieldQoS.AutomaticReadout)); } } } } Request.ReportFields(true, Fields); }; this.bobClient = new BobClient(this.xmppClient, Path.Combine(Path.GetTempPath(), "BitsOfBinary")); this.chatServer = new ChatServer(this.xmppClient, this.bobClient, this.sensorServer, this.provisioningClient); this.interoperabilityServer = new InteroperabilityServer(xmppClient); this.interoperabilityServer.OnGetInterfaces += (sender, e) => { e.Add("XMPP.IoT.Sensor.Temperature", "XMPP.IoT.Sensor.Temperature.History", "XMPP.IoT.Sensor.Temperature.Average", "XMPP.IoT.Sensor.Temperature.Average.History", "XMPP.IoT.Sensor.Temperature.Min", "XMPP.IoT.Sensor.Temperature.Min.History", "XMPP.IoT.Sensor.Temperature.Max", "XMPP.IoT.Sensor.Temperature.Max.History"); }; xmppClient.Connect(); } catch (Exception ex) { Log.Emergency(ex); MessageDialog Dialog = new MessageDialog(ex.Message, "Error"); await Dialog.ShowAsync(); } }
private static XmppCredentials Init(XmlElement E) { XmppCredentials Result = new XmppCredentials(); foreach (XmlNode N in E.ChildNodes) { switch (N.LocalName) { case "Host": Result.Host = AssertNotEnter(N.InnerText); break; case "Port": Result.Port = int.Parse(N.InnerText); break; case "Account": Result.Account = AssertNotEnter(N.InnerText); break; case "Password": Result.Password = AssertNotEnter(N.InnerText); Result.PasswordType = XML.Attribute((XmlElement)N, "type"); break; case "ThingRegistry": Result.ThingRegistry = AssertNotEnter(N.InnerText); break; case "Provisioning": Result.Provisioning = AssertNotEnter(N.InnerText); break; case "Events": Result.Events = AssertNotEnter(N.InnerText); break; case "Sniffer": if (!CommonTypes.TryParse(N.InnerText, out bool b)) { b = false; } Result.Sniffer = b; break; case "TrustServer": if (!CommonTypes.TryParse(N.InnerText, out b)) { b = false; } Result.TrustServer = b; break; case "AllowCramMD5": if (!CommonTypes.TryParse(N.InnerText, out b)) { b = false; } Result.AllowCramMD5 = b; break; case "AllowDigestMD5": if (!CommonTypes.TryParse(N.InnerText, out b)) { b = false; } Result.AllowDigestMD5 = b; break; case "AllowPlain": if (!CommonTypes.TryParse(N.InnerText, out b)) { b = false; } Result.AllowPlain = b; break; case "AllowScramSHA1": if (!CommonTypes.TryParse(N.InnerText, out b)) { b = false; } Result.AllowScramSHA1 = b; break; case "AllowScramSHA256": if (!CommonTypes.TryParse(N.InnerText, out b)) { b = false; } Result.AllowScramSHA256 = b; break; case "AllowEncryption": if (!CommonTypes.TryParse(N.InnerText, out b)) { b = false; } Result.AllowEncryption = b; break; case "RequestRosterOnStartup": if (!CommonTypes.TryParse(N.InnerText, out b)) { b = false; } Result.RequestRosterOnStartup = b; break; case "AllowRegistration": if (!CommonTypes.TryParse(N.InnerText, out b)) { b = false; } Result.AllowRegistration = b; break; case "FormSignatureKey": Result.FormSignatureKey = AssertNotEnter(N.InnerText); break; case "FormSignatureSecret": Result.FormSignatureSecret = AssertNotEnter(N.InnerText); break; } } return(Result); }