forked from PeterWaher/IoTGateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.xaml.cs
431 lines (362 loc) · 12.6 KB
/
App.xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Waher.Events;
using Waher.Events.XMPP;
using Waher.Things;
using Waher.Things.SensorData;
using Waher.Networking;
using Waher.Networking.Sniffers;
using Waher.Networking.XMPP;
using Waher.Networking.XMPP.BitsOfBinary;
using Waher.Networking.XMPP.Chat;
using Waher.Networking.XMPP.Control;
using Waher.Things.ControlParameters;
using Waher.Networking.XMPP.Interoperability;
using Waher.Networking.XMPP.Sensor;
using Waher.Networking.XMPP.Provisioning;
namespace Waher.Mock.Lamp.UWP
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session);
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
this.StartActuator();
}
private const string FormSignatureKey = ""; // Form signature key, if form signatures (XEP-0348) is to be used during registration.
private const string FormSignatureSecret = ""; // Form signature secret, if form signatures (XEP-0348) is to be used during registration.
private const int MaxRecordsPerPeriod = 500;
private XmppClient xmppClient = null;
private Timer sampleTimer = null;
private SensorServer sensorServer = null;
private ControlServer controlServer = null;
private BobClient bobClient = null;
private ChatServer chatServer = null;
private InteroperabilityServer interoperabilityServer;
private ThingRegistryClient thingRegistryClient = null;
private ProvisioningClient provisioningClient = null;
private bool connected = false;
private bool immediateReconnect;
private bool registered = false;
private static string ownerJid = null;
private static string qrCodeUrl = null;
private static string key = null;
private static MetaDataTag[] metaData = null;
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();
}
}
private async void UpdateMainWindow(bool LampSwitch)
{
MainPage MainPage = MainPage.Instance;
await MainPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
((TextBlock)MainPage.FindName("Lamp")).Text = LampSwitch ? "ON" : "OFF";
});
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// 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.controlServer != null)
{
this.controlServer.Dispose();
this.controlServer = 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();
}
private void Register()
{
key = Guid.NewGuid().ToString().Replace("-", string.Empty);
// For info on tag names, see: http://xmpp.org/extensions/xep-0347.html#tags
metaData = new MetaDataTag[]
{
new MetaDataStringTag("KEY", key),
new MetaDataStringTag("CLASS", "Lamp Actuator"),
new MetaDataStringTag("MAN", "waher.se"),
new MetaDataStringTag("MODEL", "Waher.Mock.Lamp.UWP"),
new MetaDataStringTag("PURL", "https://github.com/PeterWaher/IoTGateway/tree/master/Mocks/Waher.Mock.Lamp.UWP"),
new MetaDataNumericTag("V",1.0)
};
qrCodeUrl = SimpleXmppConfiguration.GetQRCodeURL(ThingRegistryClient.EncodeAsIoTDiscoURI(metaData), 400, 400);
thingRegistryClient.RegisterThing(metaData, (sender2, e2) =>
{
if (e2.Ok)
{
this.registered = true;
if (e2.IsClaimed)
ownerJid = e2.OwnerJid;
else
ownerJid = string.Empty;
this.RaiseOwnershipChanged();
}
}, null);
}
private void RaiseOwnershipChanged()
{
EventHandler h = OwnershipChanged;
if (h != null)
{
try
{
h(this, new EventArgs());
}
catch (Exception ex)
{
Log.Critical(ex);
}
}
}
public static event EventHandler OwnershipChanged = null;
public static string OwnerJid
{
get { return ownerJid; }
}
public static string QrCodeUrl
{
get { return qrCodeUrl; }
}
}
}