This repository has been archived by the owner on Apr 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 53
/
MainPage.xaml.cs
405 lines (348 loc) · 15.6 KB
/
MainPage.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
/*
Copyright 2017 Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using Windows.ApplicationModel;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Shared;
using Microsoft.Devices.Management;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Diagnostics;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace Toaster
{
public sealed partial class MainPage : Page
{
DeviceManagementClient deviceManagementClient;
private EventWaitHandle _iotHubOfflineEvent;
private DeviceClient _deviceClient;
private async Task EnableDeviceManagementUiAsync(bool enable)
{
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
this.buttonRestart.IsEnabled = enable;
this.buttonReset.IsEnabled = enable;
});
}
public MainPage()
{
this.InitializeComponent();
this.buttonStart.IsEnabled = true;
this.buttonStop.IsEnabled = false;
PackageVersion version = Package.Current.Id.Version;
ApplicationVersion.Text = string.Format("{0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision);
_iotHubOfflineEvent = new EventWaitHandle(true, EventResetMode.AutoReset);
#pragma warning disable 4014
// DM buttons will be enabled when we have created the DM client
this.EnableDeviceManagementUiAsync(false);
this.imageHot.Visibility = Visibility.Collapsed;
this.InitializeDeviceClientAsync();
#pragma warning restore 4014
}
private async Task<string> GetConnectionStringAsync()
{
var tpmDevice = new TpmDevice();
string connectionString = "";
do
{
try
{
connectionString = await tpmDevice.GetConnectionStringAsync();
break;
}
catch (Exception)
{
// We'll just keep trying.
}
await Task.Delay(1000);
} while (true);
return connectionString;
}
private async Task ResetConnectionAsync()
{
Logger.Log("ResetConnectionAsync start", LoggingLevel.Verbose);
// Attempt to close any existing connections before
// creating a new one
if (_deviceClient != null)
{
await _deviceClient.CloseAsync().ContinueWith((t) =>
{
var e = t.Exception;
if (e != null)
{
var msg = "existingClient.CloseAsync exception: " + e.Message + "\n" + e.StackTrace;
System.Diagnostics.Debug.WriteLine(msg);
Logger.Log(msg, LoggingLevel.Verbose);
}
});
}
// Get new SAS Token
var deviceConnectionString = await GetConnectionStringAsync();
// Create DeviceClient. Application uses DeviceClient for telemetry messages, device twin
// as well as device management
_deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, TransportType.Mqtt);
// For testing connection failure, we can use a short time-out.
// _deviceClient.OperationTimeoutInMilliseconds = 5000;
// IDeviceTwin abstracts away communication with the back-end.
// AzureIoTHubDeviceTwinProxy is an implementation of Azure IoT Hub
IDeviceTwin deviceTwin = new AzureIoTHubDeviceTwinProxy(_deviceClient, _iotHubOfflineEvent, Logger.Log);
// IDeviceManagementRequestHandler handles device management-specific requests to the app,
// such as whether it is OK to perform a reboot at any givem moment, according the app business logic
// ToasterDeviceManagementRequestHandler is the Toaster app implementation of the interface
IDeviceManagementRequestHandler appRequestHandler = new ToasterDeviceManagementRequestHandler(this);
// Create the DeviceManagementClient, the main entry point into device management
this.deviceManagementClient = await DeviceManagementClient.CreateAsync(deviceTwin, appRequestHandler);
await EnableDeviceManagementUiAsync(true);
// Set the callback for desired properties update. The callback will be invoked
// for all desired properties -- including those specific to device management
await _deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyUpdated, null);
// Tell the deviceManagementClient to sync the device with the current desired state.
await this.deviceManagementClient.ApplyDesiredStateAsync();
Logger.Log("ResetConnectionAsync end", LoggingLevel.Verbose);
}
private void InitializeDeviceClientAsync()
{
IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync(
async (workItem) =>
{
while (true)
{
_iotHubOfflineEvent.WaitOne();
try
{
await ResetConnectionAsync();
}
catch (Exception e)
{
_iotHubOfflineEvent.Set();
var msg = "InitializeDeviceClientAsync exception: " + e.Message + "\n" + e.StackTrace;
System.Diagnostics.Debug.WriteLine(msg);
Logger.Log(msg, LoggingLevel.Error);
}
await Task.Delay(1 * 60 * 1000);
}
});
}
public async Task OnDesiredPropertyUpdated(TwinCollection twinProperties, object userContext)
{
Dictionary<string, object> desiredProperties = AzureIoTHubDeviceTwinProxy.DictionaryFromTwinCollection(twinProperties);
// Let the device management client process properties specific to device management
await this.deviceManagementClient.ApplyDesiredStateAsync(desiredProperties);
}
// This method may get called on the DM callback thread - not on the UI thread.
public async Task<bool> YesNo(string question)
{
var tcs = new TaskCompletionSource<bool>();
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
UserDialog dlg = new UserDialog(question);
ContentDialogResult dialogResult = await dlg.ShowAsync();
tcs.SetResult(dlg.Result);
});
var result = await tcs.Task;
return result;
}
private void OnStartToasting(object sender, RoutedEventArgs e)
{
this.buttonStart.IsEnabled = false;
this.buttonStop.IsEnabled = true;
this.slider.IsEnabled = false;
this.textBlock.Text = string.Format("Toasting at {0}%", this.slider.Value);
this.imageHot.Visibility = Visibility.Visible;
if (deviceManagementClient != null)
{
deviceManagementClient.AllowReboots(false);
}
}
private void OnStopToasting(object sender, RoutedEventArgs e)
{
if (deviceManagementClient != null)
{
deviceManagementClient.AllowReboots(true);
}
this.buttonStart.IsEnabled = true;
this.buttonStop.IsEnabled = false;
this.slider.IsEnabled = true;
this.textBlock.Text = "Ready";
this.imageHot.Visibility = Visibility.Collapsed;
}
/*
// ToDo: Not implemented in SystemConfigurator.
private async void OnCheckForUpdates(object sender, RoutedEventArgs e)
{
bool updatesAvailable = await deviceManagementClient.CheckForUpdatesAsync();
if (updatesAvailable)
{
System.Diagnostics.Debug.WriteLine("updates available");
var dlg = new UserDialog("Updates available. Install?");
await dlg.ShowAsync();
// Don't do anything yet
}
}
*/
private async void RestartSystem()
{
bool success = true;
try
{
await deviceManagementClient.RebootAsync();
}
catch(Exception)
{
success = false;
}
StatusText.Text = success? "Operation completed" : "Operation failed";
}
private void OnSystemRestart(object sender, RoutedEventArgs e)
{
RestartSystem();
}
private async void FactoryReset()
{
bool success = true;
try
{
// The recovery partition guid is typically picked from a pre-defined set of guids
// by the builder of the image. For our testing purposes, we have been using the following
// guid.
string recoveryPartitionGUID = "a5935ff2-32ba-4617-bf36-5ac314b3f9bf";
await deviceManagementClient.StartFactoryResetAsync(false /*don't clear TPM*/, recoveryPartitionGUID);
}
catch (Exception)
{
success = false;
}
StatusText.Text = success? "Succeeded!" : "Failed!";
}
private void OnFactoryReset(object sender, RoutedEventArgs e)
{
FactoryReset();
}
private async void SetWindowsTelemetryAsync()
{
try
{
await this.deviceManagementClient.SetWindowsTelemetryLevelAsync((WindowsTelemetryLevel)RequestedWindowsTelemetryLevel.SelectedIndex);
StatusText.Text = "Set Windows Telemetry Level -> Success";
}
catch (Exception ex)
{
StatusText.Text = "Set Windows Telemetry Level -> Error: " + ex.HResult + " - " + ex.Message;
}
}
private async void GetWindowsTelemetryAsync()
{
try
{
WindowsTelemetryLevel level = await this.deviceManagementClient.GetWindowsTelemetryLevelAsync();
CurrentWindowsTelemetryLevel.Text = level.ToString();
StatusText.Text = "Get Windows Telemetry Level -> Success";
}
catch (Exception ex)
{
StatusText.Text = "Get Windows Telemetry Level -> Error: " + ex.HResult + " - " + ex.Message;
}
}
private void OnSetWindowsTelemetry(object sender, RoutedEventArgs e)
{
SetWindowsTelemetryAsync();
}
private void OnGetWindowsTelemetry(object sender, RoutedEventArgs e)
{
GetWindowsTelemetryAsync();
}
private async void SetTimeServiceStartedAsync()
{
try
{
TimeServiceState timeServiceState = new TimeServiceState();
timeServiceState.enabled = true;
timeServiceState.startup = ServiceStartup.Auto;
timeServiceState.started = RequestedTimeServiceStartedState.SelectedIndex == 0;
timeServiceState.settingsPriority = RequestedTimeServicePriorityState.SelectedIndex == 0 ? SettingsPriority.Local : SettingsPriority.Remote;
await this.deviceManagementClient.SetTimeServiceAsync(timeServiceState);
StatusText.Text = "Set Time Service Started -> Success";
}
catch (Exception ex)
{
StatusText.Text = "Set Time Service Started -> Error: " + ex.HResult + " - " + ex.Message;
}
}
private async void GetTimeServiceStartedAsync()
{
try
{
TimeServiceState state = await this.deviceManagementClient.GetTimeServiceStateAsync();
CurrentTimeServiceStartedState.Text = state.started ? "started" : "stopped";
CurrentTimeServicePriorityState.Text = state.settingsPriority.ToString();
StatusText.Text = "Get Time Service Started -> Success";
}
catch (Exception ex)
{
StatusText.Text = "Get Time Service Started -> Error: " + ex.HResult + " - " + ex.Message;
}
}
private void OnSetTimeService(object sender, RoutedEventArgs e)
{
SetTimeServiceStartedAsync();
}
private void OnGetTimeServiceStarted(object sender, RoutedEventArgs e)
{
GetTimeServiceStartedAsync();
}
private async void SetRingAsync()
{
try
{
WindowsUpdateRingState ringState = new WindowsUpdateRingState();
ringState.ring = RequestedRingState.SelectedIndex == 0 ? WindowsUpdateRing.EarlyAdopter :
RequestedRingState.SelectedIndex == 1 ? WindowsUpdateRing.GeneralAvailability : WindowsUpdateRing.Preview;
ringState.settingsPriority = RequestedRingPriorityState.SelectedIndex == 0 ? SettingsPriority.Local : SettingsPriority.Remote;
await this.deviceManagementClient.SetWindowsUpdateRingAsync(ringState);
StatusText.Text = "Set Windows Update Ring -> Success";
}
catch (Exception ex)
{
StatusText.Text = "Set Windows Update Ring -> Error: " + ex.HResult + " - " + ex.Message;
}
}
private async void GetRingAsync()
{
try
{
WindowsUpdateRingState state = await this.deviceManagementClient.GetWindowsUpdateRingAsync();
CurrentRingState.Text = state.ring == WindowsUpdateRing.EarlyAdopter ? "Early Adopter" :
state.ring == WindowsUpdateRing.GeneralAvailability ? "General Availability" : "Preview";
CurrentRingPriorityState.Text = state.settingsPriority.ToString();
StatusText.Text = "Get Windows Update Ring -> Success";
}
catch (Exception ex)
{
StatusText.Text = "Get Windows Update Ring -> Error: " + ex.HResult + " - " + ex.Message;
}
}
private void OnSetRing(object sender, RoutedEventArgs e)
{
SetRingAsync();
}
private void OnGetRing(object sender, RoutedEventArgs e)
{
GetRingAsync();
}
}
}