/// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); if (this.sampleTimer != null) { this.sampleTimer.Dispose(); this.sampleTimer = null; } if (this.interoperabilityServer != null) { this.interoperabilityServer.Dispose(); this.interoperabilityServer = null; } if (this.chatServer != null) { this.chatServer.Dispose(); this.chatServer = null; } if (this.bobClient != null) { this.bobClient.Dispose(); this.bobClient = null; } if (this.sensorServer != null) { this.sensorServer.Dispose(); this.sensorServer = null; } if (this.provisioningClient != null) { this.provisioningClient.Dispose(); this.provisioningClient = null; } if (this.thingRegistryClient != null) { this.thingRegistryClient.Dispose(); this.thingRegistryClient = null; } if (this.xmppClient != null) { this.xmppClient.Dispose(); this.xmppClient = null; } Log.Terminate(); deferral.Complete(); }
public override void DisposeClients() { this.interopServer.Dispose(); this.interopServer = null; this.interopClient.Dispose(); this.interopClient = null; base.DisposeClients(); }
public override void ConnectClients() { base.ConnectClients(); Assert.AreEqual(XmppState.Connected, this.client1.State); Assert.AreEqual(XmppState.Connected, this.client2.State); this.interopClient = new InteroperabilityClient(this.client1); this.interopServer = new InteroperabilityServer(this.client2); this.interopServer.OnGetInterfaces += (sender, e) => { e.Add("Interface A", "Interface B", "Interface C", "Interface D"); }; }
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(); } }
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)); xmppConfiguration = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config", Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name. Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password. FormSignatureKey, FormSignatureSecret, typeof(Program).Assembly); using (XmppClient Client = xmppConfiguration.GetClient("en", typeof(Program).Assembly, false)) { Client.AllowRegistration(FormSignatureKey, FormSignatureSecret); if (xmppConfiguration.Sniffer) { Client.Add(new ConsoleOutSniffer(BinaryPresentationMethod.ByteCount, LineEnding.PadWithSpaces)); } if (!string.IsNullOrEmpty(xmppConfiguration.Events)) { Log.Register(new XmppEventSink("XMPP Event Sink", Client, xmppConfiguration.Events, false)); } if (!string.IsNullOrEmpty(xmppConfiguration.ThingRegistry)) { thingRegistryClient = new ThingRegistryClient(Client, xmppConfiguration.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(xmppConfiguration.Provisioning)) { ProvisioningClient = new ProvisioningClient(Client, xmppConfiguration.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 == 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); 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(); } }
private async void StartActuator() { try { Log.Informational("Starting application."); SimpleXmppConfiguration xmppConfiguration = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config", Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name. Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password. FormSignatureKey, FormSignatureSecret, typeof(App).GetTypeInfo().Assembly); Log.Informational("Connecting to XMPP server."); xmppClient = xmppConfiguration.GetClient("en", typeof(App).GetTypeInfo().Assembly, false); xmppClient.AllowRegistration(FormSignatureKey, FormSignatureSecret); if (xmppConfiguration.Sniffer && MainPage.Sniffer != null) { xmppClient.Add(MainPage.Sniffer); } if (!string.IsNullOrEmpty(xmppConfiguration.Events)) { Log.Register(new XmppEventSink("XMPP Event Sink", xmppClient, xmppConfiguration.Events, false)); } if (!string.IsNullOrEmpty(xmppConfiguration.ThingRegistry)) { thingRegistryClient = new ThingRegistryClient(xmppClient, xmppConfiguration.ThingRegistry); thingRegistryClient.Claimed += (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(xmppConfiguration.Provisioning)) { provisioningClient = new ProvisioningClient(xmppClient, xmppConfiguration.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); 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(); } }
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(); } }
public static void ServerLoop() { AcceptDone = new ManualResetEvent(false); Worlds = new Worlds(); Clients = new List <Client>(); Log.SetLogFile(".\\Logs\\LoginLog.log"); Log.Entitle("Login Server (CLIENT VERSION {0})", ServerConstants.CLIENT_VERSION); try { Settings.Initialize(); Database.Test(); Database.Analyze(false); SecurityCode = Settings.GetString("SecurityCode", "Interconnection"); Log.Inform("Cross-servers code '{0}' assigned.", Log.MaskString(LoginServer.SecurityCode)); RequireStaffIP = Settings.GetBool("RequireStaffIP", "Login"); IsMaintenance = Settings.GetBool("isMaintenance", "Login"); PatchVer = Settings.GetInt("PatchVersion", "Login"); PatchDownloadUrl = Settings.GetString("PatchDownloadUrl", "Login"); Log.Inform("Staff will {0} be required to connect through a staff IP.", LoginServer.RequireStaffIP ? " " : " not "); Log.Debug("IsMaintenance: {0}", IsMaintenance); TcpListener Listener = new TcpListener(IPAddress.Any, Settings.GetInt("Port", "Login")); Listener.Start(); Log.Inform("Initialized clients listener on {0}.", Listener.LocalEndpoint); LoginServer.Pinger.Interval = Settings.GetInt("PingInterval"); LoginServer.Pinger.Start(); Log.Inform("Clients pinger set to {0} ms.", LoginServer.Pinger.Interval); foreach (string world in Settings.GetBlocksFromBlock("Worlds", 1)) { Worlds.Add(new World() { ID = Settings.GetByte("ID", world), HostIP = Settings.GetIPAddress("Host", world), Flag = Settings.GetEnum <ServerUtilities.ServerFlag>("Flag", world), Channel = Settings.GetByte("Channel", world), EventMessage = Settings.GetString("EventMessage", world), DisableCreation = Settings.GetBool("DisableCreation", world), ScrollingHeader = Settings.GetString("ScrollingHeader", world), Rates = new ServerUtilities.Rates() { Experience = Settings.GetInt("ExperienceRate", world), QuestExperience = Settings.GetInt("QuestExperienceRate", world), PartyQuestExperience = Settings.GetInt("PartyQuestExperience", world), Meso = Settings.GetInt("MesoDropRate", world), Loot = Settings.GetInt("LootDropRate", world) } }); } IsAlive = true; Log.Success("Server started on thread {0}.", Thread.CurrentThread.ManagedThreadId); AppDomain.CurrentDomain.UnhandledException += (s, e) => { Log.Error("Unhandled exception from Server: \n{0}", e.ExceptionObject.ToString()); }; new Thread(new ThreadStart(InteroperabilityServer.ServerLoop)).Start(); while (IsAlive) { AcceptDone.Reset(); Listener.BeginAcceptSocket((iar) => { new Client(Listener.EndAcceptSocket(iar)); AcceptDone.Set(); }, null); AcceptDone.WaitOne(); } InteroperabilityServer.Stop(); Client[] remainingClients = Clients.ToArray(); foreach (Client client in remainingClients) { client.Dispose(); } Listener.Stop(); Log.Warn("Login stopped."); } catch (Exception e) { Log.Error(e); Log.Inform("Could not start server because of errors."); } finally { Console.Read(); } }
private static void Main(string[] args) { if (args.Length == 1 && args[0].ToLower() == "setup" || !File.Exists(Application.ExecutablePath + "Configuration.ini")) { LoginServerSetup.Run(); } LoginServer.Worlds = new Worlds(); LoginServer.Channels = new ChannelsHelper(); LoginServer.Clients = new List <LoginClientHandler>(); Log.Entitle("Login Server v.{0}.{1}", Application.MapleVersion, Application.PatchVersion); try { Settings.Initialize(); Database.Test(); Database.Analyze(false); ChannelServerHandler.SecurityCode = Settings.GetString("Channels/SecurityCode"); Log.Inform("Cross-servers code '{0}' assigned.", Log.MaskString(ChannelServerHandler.SecurityCode)); LoginServer.RequireStaffIP = Settings.GetBool("Server/RequireStaffIP"); Log.Inform("Staff will{0}be required to connect through a staff IP.", LoginServer.RequireStaffIP ? " " : " not "); LoginServer.AutoRegister = Settings.GetBool("Server/AutoRegister"); Log.Inform("Automatic registration {0}.", LoginServer.AutoRegister ? "enabled" : "disabled"); LoginServer.RequestPin = Settings.GetBool("Server/RequestPin"); Log.Inform("Pin will{0}be requested upon login.", LoginServer.RequestPin ? " " : " not "); LoginServer.RequestPic = Settings.GetBool("Server/RequestPic"); Log.Inform("Pic will{0}be requested upon char selection.", LoginServer.RequestPic ? " " : " not "); LoginServer.MaxCharacters = Settings.GetInt("Server/MaxCharacters"); Log.Inform("Maximum of {0} characters per account.", LoginServer.MaxCharacters); LoginServer.EnableSpecialCharCreation = true; Log.Inform("Special char creation is{0}.", LoginServer.EnableSpecialCharCreation ? " enabled" : " disabled"); LoginServer.Listener = new TcpListener(IPAddress.Any, Settings.GetInt("Server/Port")); LoginServer.Listener.Start(); Log.Inform("Initialized clients listener on {0}.", LoginServer.Listener.LocalEndpoint); LoginServer.IsAlive = true; } catch (Exception e) { Log.Error(e); } if (LoginServer.IsAlive) { Log.Success("Server started on thread {0}.", Thread.CurrentThread.ManagedThreadId); new Thread(new ThreadStart(InteroperabilityServer.Main)).Start(); } else { Log.Inform("Could not start server because of errors."); } while (LoginServer.IsAlive) { LoginServer.AcceptDone.Reset(); LoginServer.Listener.BeginAcceptSocket(new AsyncCallback(LoginServer.OnAcceptSocket), null); LoginServer.AcceptDone.WaitOne(); } InteroperabilityServer.Stop(); LoginClientHandler[] remainingClients = LoginServer.Clients.ToArray(); foreach (LoginClientHandler client in remainingClients) { client.Stop(); } LoginServer.Dispose(); Log.Warn("Server stopped."); Console.Read(); }