-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
601 lines (501 loc) · 17.3 KB
/
App.xaml.cs
File metadata and controls
601 lines (501 loc) · 17.3 KB
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//#define GPIO
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
#if GPIO
using Windows.Devices.Gpio;
#endif
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.Devices.Enumeration;
#if !GPIO
using Microsoft.Maker.RemoteWiring;
using Microsoft.Maker.Serial;
#endif
using Waher.Content;
using Waher.Content.Images;
using Waher.Content.Markdown;
using Waher.Content.Markdown.Web;
using Waher.Events;
using Waher.Networking.HTTP;
using Waher.Persistence;
using Waher.Persistence.Files;
using Waher.Persistence.Serialization;
using Waher.Runtime.Settings;
using Waher.Runtime.Inventory;
using Waher.Script;
using Waher.Security;
using Waher.Security.JWS;
using Waher.Security.JWT;
namespace ActuatorHttp
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
private static App instance = null;
private FilesProvider db = null;
#if GPIO
private const int gpioOutputPin = 5;
private GpioController gpio = null;
private GpioPin gpioPin = null;
#else
private UsbSerial arduinoUsb = null;
private RemoteDevice arduino = null;
#endif
private string deviceId;
private HttpServer httpServer = null;
private readonly IUserSource users = new Users();
private readonly JwtFactory tokenFactory = JwtFactory.CreateHmacSha256();
private JwtAuthentication tokenAuthentication;
private bool? output = null;
/// <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()
{
this.InitializeComponent();
this.Suspending += this.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)
{
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (!(Window.Current.Content is Frame rootFrame))
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += this.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 (e.PrelaunchActivated == false)
{
if (rootFrame.Content is 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
instance = this;
Window.Current.Activate();
Task.Run((Action)this.Init);
}
}
private async void Init()
{
try
{
// Exception types that are logged with an elevated type.
Log.RegisterAlertExceptionType(true,
typeof(OutOfMemoryException),
typeof(StackOverflowException),
typeof(AccessViolationException),
typeof(InsufficientMemoryException));
Log.Informational("Starting application.");
Types.Initialize(
typeof(FilesProvider).GetTypeInfo().Assembly,
typeof(ObjectSerializer).GetTypeInfo().Assembly, // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
typeof(RuntimeSettings).GetTypeInfo().Assembly,
typeof(IContentEncoder).GetTypeInfo().Assembly,
typeof(ImageCodec).GetTypeInfo().Assembly,
typeof(MarkdownDocument).GetTypeInfo().Assembly,
typeof(MarkdownToHtmlConverter).GetTypeInfo().Assembly,
typeof(IJwsAlgorithm).GetTypeInfo().Assembly,
typeof(Expression).GetTypeInfo().Assembly,
typeof(App).GetTypeInfo().Assembly);
this.db = await FilesProvider.CreateAsync(ApplicationData.Current.LocalFolder.Path +
Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);
Database.Register(this.db);
await this.db.RepairIfInproperShutdown(null);
await this.db.Start();
#if GPIO
gpio = GpioController.GetDefault();
if (gpio != null)
{
if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
Status == GpioOpenStatus.PinOpened)
{
if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
{
this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);
this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);
this.gpioPin.Write(this.output.Value ? GpioPinValue.High : GpioPinValue.Low);
await MainPage.Instance.OutputSet(this.output.Value);
Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
new KeyValuePair<string, object>("Output", this.output.Value));
}
else
Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
}
else
Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
}
#else
DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();
DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
if (DeviceInfo is null)
Log.Error("Unable to find Arduino device.");
else
{
Log.Informational("Connecting to " + DeviceInfo.Name);
this.arduinoUsb = new UsbSerial(DeviceInfo);
this.arduinoUsb.ConnectionEstablished += () =>
Log.Informational("USB connection established.");
this.arduino = new RemoteDevice(this.arduinoUsb);
this.arduino.DeviceReady += async () =>
{
try
{
Log.Informational("Device ready.");
this.arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED.
this.arduino.digitalWrite(13, PinState.HIGH);
this.arduino.pinMode(8, PinMode.INPUT); // PIR sensor (motion detection).
this.arduino.pinMode(9, PinMode.OUTPUT); // Relay.
this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);
this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW);
await MainPage.Instance.OutputSet(this.output.Value);
Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
new KeyValuePair<string, object>("Output", this.output.Value));
this.arduino.pinMode("A0", PinMode.ANALOG); // Light sensor.
}
catch (Exception ex)
{
Log.Exception(ex);
}
};
this.arduinoUsb.ConnectionFailed += message =>
{
Log.Error("USB connection failed: " + message);
};
this.arduinoUsb.ConnectionLost += message =>
{
Log.Error("USB connection lost: " + message);
};
this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
}
#endif
this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);
if (string.IsNullOrEmpty(this.deviceId))
{
this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
}
Log.Informational("Device ID: " + this.deviceId);
this.tokenAuthentication = new JwtAuthentication(this.deviceId, this.users, this.tokenFactory);
this.httpServer = new HttpServer();
//this.httpServer = new HttpServer(new LogSniffer());
StorageFile File = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Root/favicon.ico"));
string Root = File.Path;
Root = Root.Substring(0, Root.Length - 11);
this.httpServer.Register(new HttpFolderResource(string.Empty, Root, false, false, true, true));
this.httpServer.Register("/", (req, resp) =>
{
throw new TemporaryRedirectException("/Index.md");
});
this.httpServer.Register("/Momentary", async (req, resp) =>
{
resp.SetHeader("Cache-Control", "max-age=0, no-cache, no-store");
if (req.Header.Accept != null)
{
switch (req.Header.Accept.GetBestAlternative("text/xml", "application/xml", "application/json"))
{
case "text/xml":
case "application/xml":
await this.ReturnMomentaryAsXml(req, resp);
break;
case "application/json":
await this.ReturnMomentaryAsJson(req, resp);
break;
default:
throw new NotAcceptableException();
}
}
else
await this.ReturnMomentaryAsXml(req, resp);
}, this.tokenAuthentication);
this.httpServer.Register("/Set", null, async (req, resp) =>
{
try
{
if (!req.HasData)
throw new BadRequestException();
ContentResponse Content = await req.DecodeDataAsync();
Content.AssertOk();
if (!(Content.Decoded is string s) || !CommonTypes.TryParse(s, out bool OutputValue))
throw new BadRequestException();
if (req.Header.Accept != null)
{
switch (req.Header.Accept.GetBestAlternative("text/xml", "application/xml", "application/json"))
{
case "text/xml":
case "application/xml":
await this.SetOutput(OutputValue, req.RemoteEndPoint);
await this.ReturnMomentaryAsXml(req, resp);
break;
case "application/json":
await this.SetOutput(OutputValue, req.RemoteEndPoint);
await this.ReturnMomentaryAsJson(req, resp);
break;
default:
throw new NotAcceptableException();
}
}
else
{
await this.SetOutput(OutputValue, req.RemoteEndPoint);
await this.ReturnMomentaryAsXml(req, resp);
}
await resp.SendResponse();
}
catch (Exception ex)
{
await resp.SendResponse(ex);
}
}, false, this.tokenAuthentication);
this.httpServer.Register("/Login", null, async (req, resp) =>
{
if (!req.HasData || req.Session is null)
throw new BadRequestException();
object Obj = await req.DecodeDataAsync();
if (!(Obj is Dictionary<string, string> Form) ||
!Form.TryGetValue("UserName", out string UserName) ||
!Form.TryGetValue("Password", out string Password))
{
throw new BadRequestException();
}
string From = null;
if (req.Session.TryGetVariable("from", out Variable v))
From = v.ValueObject as string;
if (string.IsNullOrEmpty(From))
From = "/Index.md";
IUser User = await this.Login(UserName, Password);
if (User != null)
{
Log.Informational("User logged in.", UserName, req.RemoteEndPoint, "LoginSuccessful", EventLevel.Minor);
req.Session["User"] = User;
req.Session.Remove("LoginError");
throw new SeeOtherException(From);
}
else
{
Log.Warning("Invalid login attempt.", UserName, req.RemoteEndPoint, "LoginFailure", EventLevel.Minor);
req.Session["LoginError"] = "Invalid login credentials provided.";
}
throw new SeeOtherException(req.Header.Referer.Value);
}, true, false, true);
this.httpServer.Register("/GetSessionToken", null, (req, resp) =>
{
if (!req.Session.TryGetVariable("User", out Variable v) ||
!(v.ValueObject is IUser User))
{
throw new ForbiddenException();
}
string Token = this.tokenFactory.Create(new KeyValuePair<string, object>("sub", User.UserName));
resp.ContentType = JwtCodec.ContentType;
resp.Write(Token);
return Task.CompletedTask;
}, true, false, true);
}
catch (Exception ex)
{
Log.Emergency(ex);
MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
async () => await Dialog.ShowAsync());
}
}
private DeviceInformation FindDevice(DeviceInformationCollection Devices, params string[] DeviceNames)
{
foreach (string DeviceName in DeviceNames)
{
foreach (DeviceInformation DeviceInfo in Devices)
{
if (DeviceInfo.IsEnabled && DeviceInfo.Name.StartsWith(DeviceName))
return DeviceInfo;
}
}
return null;
}
public class Users : IUserSource
{
public Task<IUser> TryGetUser(string UserName)
{
if (UserName == "MIoT")
return Task.FromResult<IUser>(new User());
else
return Task.FromResult<IUser>(null);
}
}
public class User : IUser
{
public string UserName => "MIoT";
public string PasswordHash => instance.CalcHash("rox");
public string PasswordHashType => "SHA-256";
public bool HasPrivilege(string Privilege)
{
return false;
}
}
private string CalcHash(string Password)
{
return Waher.Security.Hashes.ComputeSHA256HashString(Encoding.UTF8.GetBytes(Password + ":" + this.deviceId));
}
private async Task<IUser> Login(string UserName, string Password)
{
IUser User = await this.users.TryGetUser(UserName);
if (!(User is null))
{
switch (User.PasswordHashType)
{
case "":
if (Password == User.PasswordHash)
return User;
break;
case "SHA-256":
if (this.CalcHash(Password) == User.PasswordHash)
return User;
break;
default:
Log.Error("Unsupported Hash function: " + User.PasswordHashType);
break;
}
}
return null;
}
private async Task ReturnMomentaryAsXml(HttpRequest Request, HttpResponse Response)
{
Response.ContentType = "application/xml";
await Response.Write("<?xml version='1.0' encoding='");
await Response.Write(Response.Encoding.WebName);
await Response.Write("'?>");
string SchemaUrl = Request.Header.GetURL();
int i = SchemaUrl.IndexOf("/Momentary");
SchemaUrl = SchemaUrl.Substring(0, i) + "/schema.xsd";
await Response.Write("<Momentary timestamp='");
await Response.Write(DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
await Response.Write("' xmlns='");
await Response.Write(SchemaUrl);
await Response.Write("'>");
if (this.output.HasValue)
{
await Response.Write("<Output value='");
await Response.Write(this.output.Value ? "true" : "false");
await Response.Write("'/>");
}
await Response.Write("</Momentary>");
}
private async Task ReturnMomentaryAsJson(HttpRequest _, HttpResponse Response)
{
Response.ContentType = "application/json";
await Response.Write("{\"ts\":\"");
await Response.Write(DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
await Response.Write('"');
if (this.output.HasValue)
{
await Response.Write(",\"output\":");
await Response.Write(this.output.Value ? "true" : "false");
}
await Response.Write('}');
}
internal static App Instance => instance;
internal async Task SetOutput(bool On, string Actor)
{
#if GPIO
if (this.gpioPin != null)
{
this.gpioPin.Write(On ? GpioPinValue.High : GpioPinValue.Low);
#else
if (this.arduino != null)
{
this.arduino.digitalWrite(9, On ? PinState.HIGH : PinState.LOW);
#endif
await RuntimeSettings.SetAsync("Actuator.Output", On);
this.output = On;
Log.Informational("Setting Control Parameter.", string.Empty, Actor ?? "Windows user",
new KeyValuePair<string, object>("Output", On));
if (Actor != null)
await MainPage.Instance.OutputSet(On);
}
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// 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 (instance == this)
instance = null;
this.httpServer?.Dispose();
this.httpServer = null;
#if GPIO
this.gpioPin?.Dispose();
this.gpioPin = null;
#else
if (this.arduino != null)
{
this.arduino.digitalWrite(13, PinState.LOW);
this.arduino.pinMode(13, PinMode.INPUT); // Onboard LED.
this.arduino.pinMode(9, PinMode.INPUT); // Relay.
this.arduino.Dispose();
this.arduino = null;
}
if (this.arduinoUsb != null)
{
this.arduinoUsb.end();
this.arduinoUsb.Dispose();
this.arduinoUsb = null;
}
#endif
this.db?.Stop()?.Wait();
this.db?.Flush()?.Wait();
Log.TerminateAsync().Wait();
deferral.Complete();
}
public static string Output
{
get
{
if (instance.output.HasValue)
return instance.output.Value ? "ON" : "OFF";
else
return string.Empty;
}
}
}
}