aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineSetupViewVM.cs
blob: ae31a64a1e443855cd9638e013be1bd483efcbc0 (plain)
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
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.Core;
using Tango.Core.Commands;
using Tango.Core.Helpers;
using Tango.Integration.Operation;
using Tango.Logging;
using Tango.PMR.Connection;
using Tango.PPC.Common;
using Tango.PPC.Common.Application;
using Tango.PPC.Common.Connection;
using Tango.PPC.Common.MachineSetup;
using Tango.PPC.Common.Navigation;
using Tango.PPC.Common.OS;
using Tango.PPC.Common.Web;
using Tango.PPC.UI.ViewsContracts;
using Tango.Settings;
using Tango.SharedUI.Helpers;
using Tango.SQLExaminer;
using Tango.Transport.Adapters;
using Tango.Web;

namespace Tango.PPC.UI.ViewModels
{
    /// <summary>
    /// Represents the machine setup view ViewModel.
    /// </summary>
    /// <seealso cref="Tango.PPC.Common.PPCViewModel{Tango.PPC.UI.ViewsContracts.IMachineSetupView}" />
    public class MachineSetupViewVM : PPCViewModel<IMachineSetupView>
    {
        /// <summary>
        /// Represents the various machine setup view states.
        /// </summary>
        public enum MachineSetupStates
        {
            None,
            Working,
            Completed,
            Failed,
        }

        public enum MachineSetupView
        {
            WelcomeView,
            WiFiSelectionView,
            WiFiTestView,
            TimeZoneView,
            EnvironmentView,
            SetupWelcomeView,
            SetupProgressView,
            SetupCompletedView,
            SetupFailedView,
        }

        private MachineSetupResult _setup_result;
        private IOperationSystemManager _operationSystemManager;
        private IPPCApplicationManager _appManager;
        private PPCWebClient _ppcWebClient;

        #region Properties

        /// <summary>
        /// Gets or sets the machine setup manager.
        /// </summary>
        public IMachineSetupManager MachineSetupManager { get; set; }

        private String _serialNumber;
        /// <summary>
        /// Gets or sets the serial number.
        /// </summary>
        public String SerialNumber
        {
            get { return _serialNumber; }
            set { _serialNumber = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); }
        }

        private String _hostAddress;
        /// <summary>
        /// Gets or sets the host address.
        /// </summary>
        public String HostAddress
        {
            get pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tango.BL;
using Tango.Core;
using Tango.Core.Commands;
using Tango.Core.ExtensionMethods;
using Tango.Core.Helpers;
using Tango.Core.Threading;
using Tango.Explorer;
using Tango.Integration.ExternalBridge;
using Tango.PMR.FirmwareUpgrade;
using Tango.PPC.Common;
using Tango.PPC.Common.Application;
using Tango.PPC.Common.ExternalBridge;
using Tango.PPC.Common.MachineUpdate;
using Tango.PPC.Common.Navigation;
using Tango.PPC.Common.Notifications;
using Tango.PPC.Common.Publish;
using Tango.PPC.Common.Web;
using Tango.PPC.Shared.RemoteUpgrade;
using Tango.PPC.UI.Dialogs;
using Tango.PPC.UI.Notifications.NotificationItems;
using Tango.PPC.UI.ViewsContracts;
using Tango.Transport;

namespace Tango.PPC.UI.ViewModels
{
    public class MachineUpdateViewVM : PPCViewModel<IMachineUpdateView>, IExternalBridgeRequestHandler
    {
        public enum MachineUpdateView
        {
            UpdateCheckView,
            UpdateCheckErrorView,
            UpdateAvailableView,
            UpToDateView,
            UpdateProgressView,
            UpdateDbProgressView,
            UpdateCompletedView,
            UpdateFailedView,
            UpdateFromPackageView,
            UpdateFailedFromPackageView,
        }

        private MachineUpdateResult _update_result;
        private DbCompareResult _db_compare_result;
        private bool _isChecking;
        private CheckForUpdateResponse _checkUpdateResponse;
        private UpdateAvailableNotificationItem _updateNotificationItem;

        #region Properties

        /// <summary>
        /// Gets or sets the machine update manager.
        /// </summary>
        public IMachineUpdateManager MachineUpdateManager { get; set; }

        private String _latestVersion;
        /// <summary>
        /// Gets or sets the latest version.
        /// </summary>
        public String LatestVersion
        {
            get { return _latestVersion; }
            set { _latestVersion = value; RaisePropertyChangedAuto(); }
        }

        private bool _isDbUpdate;
        /// <summary>
        /// Gets or sets a value indicating whether this instance is database update.
        /// </summary>
        public bool IsDbUpdate
        {
            get { return _isDbUpdate; }
            set { _isDbUpdate = value; RaisePropertyChangedAuto(); }
        }

        private String _failedError;
        /// <summary>
        /// Gets or sets the setup failed error.
        /// </summary>
        public String FailedError
        {
            get { return _failedError; }
            set { _failedError = value; RaisePropertyChangedAuto(); }
        }

        #endregion

        #region Commands

        /// <summary>
        /// Gets or sets the complete command.
        /// </summary>
        public RelayCommand CompleteCommand { get; set; }

        /// <summary>
        /// Gets or sets the install command.
        /// </summary>
        public RelayCommand UpdateCommand { get; set; }

        /// <summary>
        /// Gets or sets the restart command.
        /// </summary>
        public RelayCommand RestartCommand { get; set; }

        /// <summary>
        /// Gets or sets the close command.
        /// </summary>
        public RelayCommand CloseCommand { get; set; }

        /// <summary>
        /// Gets or sets to application command.
        /// </summary>
        public RelayCommand ToApplicationCommand { get; set; }

        #endregion

        #region Constructors

        public MachineUpdateViewVM(IMachineUpdateManager machineUpdateManager, IPPCExternalBridgeService externalBridge, IPPCApplicationManager applicationManager, INavigationManager navigationManager, INotificationProvider notificationProvider)
        {
            MachineUpdateManager = machineUpdateManager;
            externalBridge.RegisterRequestHandler(this);

            CompleteCommand = new RelayCommand(CompleteUpdate);
            UpdateCommand = new RelayCommand(Update);
            RestartCommand = new RelayCommand(CheckForUpdates);
            CloseCommand = new RelayCommand(() =>
            {
                NavigationManager.NavigateTo(Common.Navigation.NavigationView.HomeModule);
                NavigateTo(MachineUpdateView.UpdateCheckView);
            });

            ToApplicationCommand = new RelayCommand(() =>
            {
                NavigationManager.NavigateTo(Common.Navigation.NavigationView.HomeModule);
                NavigateTo(MachineUpdateView.UpdateCheckView);
            });

            machineUpdateManager.UpdateAvailable += MachineUpdateManager_UpdateAvailable;

            NavigationManager = navigationManager;
            NotificationProvider = notificationProvider;
            ApplicationManager = applicationManager;
            ApplicationManager.UpdaterFailed += ApplicationManager_UpdaterFailed;
        }

        #endregion

        #region Update

        public async void CheckForUpdates()
        {
            await NavigateTo(MachineUpdateView.UpdateCheckView);

            if (_isChecking) return;

            try
            {
                _isChecking = true;
                IsDbUpdate = false;

                await Task.Delay(2000);
                if (!await ConnectivityProvider.CheckInternetConnection())
                {
                    _isChecking = false;
                    await NavigateTo(MachineUpdateView.UpdateCheckErrorView);
                    return;
                }

                var response = await MachineUpdateManager.CheckForUpdate();

                try
                {
                    if (response.UsedNotExistingRmlsGuids.Count > 0)
                    {
                        using (ObservablesContext db = ObservablesContext.CreateDefault())
                        {
                            var arr = response.UsedNotExistingRmlsGuids.ToArray();
                            var jobs = await db.Jobs.Where(x => arr.Contains(x.RmlGuid)).ToListAsync();
                            FailedError = $"The following jobs must be removed or change thread type before the system can be updated:\n{String.Join("\n", jobs.Select(x => x.Name))}";
                            _isChecking = false;
                            await NavigateTo(MachineUpdateView.UpdateFailedView);
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "Error on used RML check procedure.");
                }

                _checkUpdateResponse = response;

                if (response.IsUpdateAvailable)
                {
                    LatestVersion = response.Version;
                    await NavigateTo(MachineUpdateView.UpdateAvailableView);
                }
                else if (response.IsDatabaseUpdateAvailable)
                {
                    IsDbUpdate = true;
                    _db_compare_result = new DbCompareResult()
                    {
                        RequiresUpdate = true,
                        UpdateDBResponse = response.UpdateDBResponse
                    };
                    await NavigateTo(MachineUpdateView.UpdateAvailableView);
                }
                else
                {
                    _db_compare_result = await MachineUpdateManager.UpdateDBCheck();

                    if (_db_compare_result.RequiresUpdate)
                    {
                        IsDbUpdate = true;
                        await NavigateTo(MachineUpdateView.UpdateAvailableView);
                    }
                    else
                    {
                        await NavigateTo(MachineUpdateView.UpToDateView);
                    }
                }
            }
            catch (Exception ex)
            {
                FailedError = ex.FlattenMessage();
                LogManager.Log(ex, "Error while trying to check for updates.");
                await NavigateTo(MachineUpdateView.UpdateFailedView);
            }
            finally
            {
                _isChecking = false;
            }
        }

        private async void Update()
        {
            if (!IsDbUpdate)
            {
                await NavigateTo(MachineUpdateView.UpdateProgressView);

                LogManager.Log("Starting machine update...");

                try
                {
                    _update_result = await MachineUpdateManager.Update(_checkUpdateResponse.SetupFirmware, _checkUpdateResponse.
an class="p">); await NavigateTo(MachineUpdateView.UpdateCompletedView); } catch (Exception ex) { FailedError = ex.FlattenMessage(); LogManager.Log(ex, "Machine update failed."); await NavigateTo(MachineUpdateView.UpdateFailedView); } } else { await NavigateTo(MachineUpdateView.UpdateDbProgressView); LogManager.Log("Starting database update..."); try { await MachineUpdateManager.UpdateDB(_db_compare_result); LogManager.Log("Database update completed."); await NavigateTo(MachineUpdateView.UpdateCompletedView); } catch (Exception ex) { FailedError = ex.FlattenMessage(); LogManager.Log(ex, "Database update failed."); await NavigateTo(MachineUpdateView.UpdateFailedView); } } } #endregion #region Complete private void CompleteUpdate() { LogManager.Log("Completing machine update..."); if (IsDbUpdate || !_update_result.RequiresBinariesUpdate) { LogManager.Log("Restarting Application..."); ApplicationManager.Restart(); } else { String updater_exe = Path.Combine(_update_result.UpdatePackagePath, "Tango.PPC.Updater.exe"); ApplicationManager.UpdateApplication(updater_exe, PathHelper.GetStartupPath()); } } #endregion #region Override Methods /// <summary> /// Called when the application has been started. /// </summary> public override void OnApplicationStarted() { } /// <summary> /// Navigates to the specified view. /// </summary> /// <param name="view">The view.</param> private Task NavigateTo(MachineUpdateView view) { return View.NavigateTo(view); } /// <summary> /// Called when the application is ready and all modules views are loaded. /// </summary> public override void OnApplicationReady() { base.OnApplicationReady(); StorageProvider.RegisterFileHandler(ExplorerFileDefinition.Update.Extension, HandleSoftwareUpdatePackageLoaded); StorageProvider.RegisterFileHandler(ExplorerFileDefinition.Firmware.Extension, HandleFirmwareUpgradeLoaded); if (ApplicationManager.IsAfterUpdate) { RunPostUpdatePackages(); } else { MachineUpdateManager.EnableAutoCheckForUpdates = true; } } /// <summary> /// Called when the navigation system has navigated to this VM view. /// </summary> public override void OnNavigatedTo() { base.OnNavigatedTo(); if (_updateNotificationItem != null) { _updateNotificationItem.Close(); _updateNotificationItem = null; } } #endregion #region Post Update Packages private async void RunPostUpdatePackages() { await Task.Delay(1000); LogManager.Log("Application was loaded after an update. Checking for required post-update packages..."); bool required = false; try { required = await MachineUpdateManager.PostUpdatePackagesRequired(); } catch (Exception ex) { LogManager.Log(ex, "Error checking for post-update packages."); } if (required) { LogManager.Log("Post-update packages found and needs to be installed. Navigating to machine update and running post-update packages..."); await NavigationManager.NavigateTo(Common.Navigation.NavigationView.MachineUpdateView); await NavigateTo(MachineUpdateView.UpdateProgressView); try { var result = await MachineUpdateManager.RunPostUpdatePackages(); LogManager.Log("Post-update packages installed successfully."); await Task.Delay(2000); if (result.RestartRequired) { LogManager.Log("Restart required. Restarting..."); ApplicationManager.Restart(); } else { await NavigationManager.NavigateTo(Common.Navigation.NavigationView.LayoutView); } } catch (Exception ex) { LogManager.Log(ex, "Error occurred while running post-update packages."); } } else { LogManager.Log("No post-update packages installation required."); } } #endregion #region Handle USB Update private async void HandleSoftwareUpdatePackageLoaded(List<ExplorerFileItem> fileItems) { var fileItem = fileItems.FirstOrDefault(); if (fileItem == null) return; PublishInfo packageFile = null; LogManager.Log("TUP file loaded from storage..."); try { packageFile = await MachineUpdateManager.GetUpdatePackageFileInfo(fileItem.Path); } catch (Exception ex) { LogManager.Log(ex, $"Error loading publish info from {fileItem.Path}."); await NotificationProvider.ShowError("An error occurred while trying to load the selected software update package. Please make sure the package is valid."); return; } UpdateFromFileViewVM vm = new UpdateFromFileViewVM(); vm.PublishInfo = packageFile; LogManager.Log($"TUP publish info:\n{packageFile.ToJson()}"); LogManager.Log("Displaying TUP update dialog..."); await NotificationProvider.ShowDialog(vm); if (vm.DialogResult) { await NavigationManager.NavigateTo(Common.Navigation.NavigationView.MachineUpdateView); await NavigateTo(MachineUpdateView.UpdateProgressView); LogManager.Log("Starting machine update from package..."); try { _update_result = await MachineUpdateManager.UpdateFromTUP(fileItem.Path, MachineProvider.Machine.SetupFirmware, MachineProvider.Machine.SetupFpga); LogManager.Log("Machine update from package completed."); await NavigateTo(MachineUpdateView.UpdateCompletedView); } catch (Exception ex) { LogManager.Log(ex, "Machine update from package failed."); FailedError = ex.FlattenMessage(); await NavigateTo(MachineUpdateView.UpdateFailedFromPackageView); } } } private async void HandleFirmwareUpgradeLoaded(List<ExplorerFileItem> fileItems) { var fileItem = fileItems.FirstOrDefault(); if (fileItem == null) return; LogManager.Log("TFP file loaded from storage..."); VersionPackageDescriptor packageInfo; FirmwareUpgradeFromFileViewVM vm = new FirmwareUpgradeFromFileViewVM(); try { using (FileStream st = File.OpenRead(fileItem.Path)) { packageInfo = await MachineProvider.MachineOperator.GetFirmwarePackageInfo(st); } packageInfo.Validate(); vm.Version = packageInfo.GetMcuVersion().ToString(); } catch (Exception ex) { LogManager.Log(ex, $"Error loading package info from {fileItem.Path}."); await NotificationProvider.ShowError($"An error occurred while trying to load the selected firmware upgrade package.\n{ex.FlattenMessage()}"); return; } LogManager.Log($"TFP publish info:\n{packageInfo.ToJsonString()}"); LogManager.Log("Displaying TFP update dialog..."); await NotificationProvider.ShowDialog(vm); if (vm.DialogResult) { await NavigationManager.NavigateTo(Common.Navigation.NavigationView.MachineUpdateView); await NavigateTo(MachineUpdateView.UpdateProgressView); LogManager.Log("Starting firmware upgrade from package..."); try { await MachineUpdateManager.UpdateFromTFP(fileItem.Path); LogManager.Log("Firmware upgrade from package completed."); _update_result = new MachineUpdateResult() { RequiresBinariesUpdate = false, }; await NavigateTo(MachineUpdateView.UpdateCompletedView); } catch (Exception ex) { LogManager.Log(ex, "Firmware upgrade from package failed."); FailedError = ex.FlattenMessage(); await NavigateTo(MachineUpdateView.UpdateFailedFromPackageView); } } } #endregion #region Auto Check For Update private void MachineUpdateManager_UpdateAvailable(object sender, CheckForUpdateResponse e) { if (!IsVisible && _updateNotificationItem == null) { LogManager.Log($"New {(e.IsDatabaseUpdateAvailable ? "database updates" : "application version")} detected ({e.Version}). Pushing notification..."); InvokeUI(() => { _updateNotificationItem = new UpdateAvailableNotificationItem(); _updateNotificationItem.Version = Version.Parse(e.Version).ToString(3); _updateNotificationItem.IsDatabaseUpdate = e.IsDatabaseUpdateAvailable && !e.IsUpdateAvailable; _updateNotificationItem.Pressed += (_, __) => { _updateNotificationItem = null; if (MachineProvider.MachineOperator.IsPrinting) { NotificationProvider.ShowInfo("Cannot perform a machine update while the machine is dyeing."); return; } if (!IsVisible) { LogManager.Log("Update available notification pressed. Navigating to update view..."); NavigationManager.NavigateTo(Common.Navigation.NavigationView.MachineUpdateView); CheckForUpdates(); } }; _updateNotificationItem.Closed += (_, __) => { _updateNotificationItem = null; }; if (!BuildProvider.IsEureka) { NotificationProvider.PushNotification(_updateNotificationItem); } }); } } #endregion #region Updater Failed private void ApplicationManager_UpdaterFailed(object sender, EventArgs e) { InvokeUI(async () => { try { await NavigationManager.NavigateTo(NavigationView.MachineUpdateView); await NavigateTo(MachineUpdateView.UpdateProgressView); await MachineUpdateManager.RestoreLastDatabaseBackup(); await Task.Delay(5000); ApplicationManager.Restart(); } catch (Exception ex) { await NotificationProvider.ShowError($"Could not restore the application to its previous state.\n{ex.FlattenMessage()}"); ApplicationManager.Restart(); } }); } #endregion #region External Bridge Handler [ExternalBridgeRequestHandlerMethod(typeof(StartRemoteApplicationUpgradeRequest), RequestHandlerLoggingMode.LogRequestName)] public async Task OnStartRemoteApplicationUpgradeRequest(StartRemoteApplicationUpgradeRequest request, String token, ExternalBridgeReceiver receiver) { await receiver.SendGenericResponse(new StartRemoteApplicationUpgradeResponse(), token); bool stopReporting = false; try { ThreadFactory.StartNew(async () => { while (!stopReporting) { if (MachineUpdateManager.Status != null) { try { await receiver.SendGenericResponse(new StartRemoteApplicationUpgradeResponse() { Progress = new TangoProgress<double>() { Message = MachineUpdateManager.Status.Message, IsIndeterminate = MachineUpdateManager.Status.IsIntermediate, Maximum = MachineUpdateManager.Status.Total, Value = MachineUpdateManager.Status.Progress }, }, token, new TransportResponseConfig() { Priority = QueuePriority.Low }); } catch (Exception ex) { LogManager.Log(ex, "Error sending remote upgrade progress."); } } Thread.Sleep(500); } }); InvokeUI(() => { NavigationManager.NavigateTo(Common.Navigation.NavigationView.MachineUpdateView); NavigateTo(MachineUpdateView.UpdateProgressView); }); LogManager.Log("Starting machine update from package..."); try { _update_result = await MachineUpdateManager.UpdateFromTUP(request.RemoteTupFilePath, request.SetupFirmware, request.SetupFPGA); LogManager.Log("Machine update from package completed."); stopReporting = true; InvokeUI(() => { NavigateTo(MachineUpdateView.UpdateCompletedView); }); } catch (Exception ex) { LogManager.Log(ex, "Machine update from package failed."); FailedError = ex.FlattenMessage(); InvokeUI(() => { NavigateTo(MachineUpdateView.UpdateFailedFromPackageView); }); throw ex; } await receiver.SendGenericResponse(new StartRemoteApplicationUpgradeResponse() { Progress = new TangoProgress<double>("Completed", false, 100, 100), }, token, new TransportResponseConfig() { Completed = true }); try { File.Delete(request.RemoteTupFilePath); } catch { } await Task.Delay(2000); CompleteUpdate(); } catch (Exception ex) { stopReporting = true; await receiver.SendErrorResponse(ex, token); } finally { stopReporting = true; try { File.Delete(request.RemoteTupFilePath); } catch { } } } [ExternalBridgeRequestHandlerMethod(typeof(StartRemoteFirmwareUpgradeRequest), RequestHandlerLoggingMode.LogRequestName)] public async Task OnStartRemoteFirmwareUpgradeRequest(StartRemoteFirmwareUpgradeRequest request, String token, ExternalBridgeReceiver receiver) { await receiver.SendGenericResponse(new StartRemoteFirmwareUpgradeResponse(), token); bool stopReporting = false; try { ThreadFactory.StartNew(async () => { while (!stopReporting) { if (MachineUpdateManager.Status != null) { try { await receiver.SendGenericResponse(new StartRemoteFirmwareUpgradeResponse() { Progress = new TangoProgress<double>() { Message = MachineUpdateManager.Status.Message, IsIndeterminate = MachineUpdateManager.Status.IsIntermediate, Maximum = MachineUpdateManager.Status.Total, Value = MachineUpdateManager.Status.Progress } }, token, new TransportResponseConfig() { Priority = QueuePriority.Low }); } catch (Exception ex) { LogManager.Log(ex, "Error sending remote upgrade progress."); } } Thread.Sleep(500); } }); InvokeUI(() => { NavigationManager.NavigateTo(Common.Navigation.NavigationView.MachineUpdateView); NavigateTo(MachineUpdateView.UpdateProgressView); }); LogManager.Log("Starting firmware upgrade from package..."); try { await MachineUpdateManager.UpdateFromTFP(request.RemoteTfpFilePath); stopReporting = true; LogManager.Log("Firmware upgrade from package completed."); _update_result = new MachineUpdateResult() { RequiresBinariesUpdate = false, }; InvokeUI(() => { NavigateTo(MachineUpdateView.UpdateCompletedView); }); } catch (Exception ex) { stopReporting = true; LogManager.Log(ex, "Firmware upgrade from package failed."); FailedError = ex.FlattenMessage(); InvokeUI(() => { NavigateTo(MachineUpdateView.UpdateFailedFromPackageView); }); throw ex; } await receiver.SendGenericResponse(new StartRemoteFirmwareUpgradeResponse() { Progress = new TangoProgress<double>("Completed", false, 100, 100), }, token, new TransportResponseConfig() { Completed = true }); try { File.Delete(request.RemoteTfpFilePath); } catch { } await Task.Delay(2000); CompleteUpdate(); } catch (Exception ex) { stopReporting = true; await receiver.SendErrorResponse(ex, token); } finally { stopReporting = true; try { File.Delete(request.RemoteTfpFilePath); } catch { } } } public void OnReceiverDisconnected(ExternalBridgeReceiver receiver) { //Do Nothing. } #endregion } }