aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Modules/Tango.PPC.Technician/ViewModels/SystemViewVM.cs
blob: 143cfe87572c6bb7d443d11821e554cc6176bd35 (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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using Tango.BL;
using Tango.Core.Commands;
using Tango.PPC.Common;
using Tango.PPC.Common.OS;
using Tango.Settings;
using System.Data.Entity;
using Tango.PPC.Common.UWF;
using Tango.BL.Entities;
using Tango.PPC.Common.Build;

namespace Tango.PPC.Technician.ViewModels
{
    public class SystemViewVM : PPCViewModel
    {
        private IOperationSystemManager _os;
        private IUnifiedWriteFilterManager _uwf;
        private Timer _statsTimer;
        private bool _resettingDevice;

        private float _cpu;
        public float CPU
        {
            get { return _cpu; }
            set { _cpu = value; RaisePropertyChangedAuto(); }
        }

        private long _ram;
        public long RAM
        {
            get { return _ram; }
            set { _ram = value; RaisePropertyChangedAuto(); }
        }

        private double _temperature;
        public double Temperature
        {
            get { return _temperature; }
            set { _temperature = value; RaisePropertyChangedAuto(); }
        }

        private TimeSpan _upTime;
        public TimeSpan UpTime
        {
            get { return _upTime; }
            set { _upTime = value; RaisePropertyChangedAuto(); }
        }

        private String _ipAddress;
        public String IPAddress
        {
            get { return _ipAddress; }
            set { _ipAddress = value; RaisePropertyChangedAuto(); }
        }

        private String _totalDyeTime;
        public String TotalDyeTime
        {
            get { return _totalDyeTime; }
            set { _totalDyeTime = value; RaisePropertyChangedAuto(); }
        }

        private String _totalDyeMeters;
        public String TotalDyeMeters
        {
            get { return _totalDyeMeters; }
            set { _totalDyeMeters = value; RaisePropertyChangedAuto(); }
        }

        public Site CurrentSite { get; set; }

        public String SiteName
        {
            get {  return CurrentSite == null? "" : CurrentSite.Name; }
        }


        public RelayCommand ResetDeviceCommand { get; set; }

        public RelayCommand RestartCommand { get; set; }

        public RelayCommand ShutdownCommand { get; set; }

        public RelayCommand FactoryResetCommand { get; set; }

        public RelayCommand ExitToExplorerCommand { get; set; }

        public SystemViewVM(IOperationSystemManager os, IUnifiedWriteFilterManager uwf)
        {
            _os = os;
            _uwf = uwf;

            CPU = 0;
            RAM = 0;

            RestartCommand = new RelayCommand(RestartSystem);
            ShutdownCommand = new RelayCommand(ShutdownSystem);
            FactoryResetCommand = new RelayCommand(FactoryReset);
            ExitToExplorerCommand = new RelayCommand(ExitToExplorer);
            ResetDeviceCommand = new RelayCommand(ResetDevice, () => !_resettingDevice);
        }

        private async void ResetDevice()
        {
            try
            {
                _resettingDevice = true;
                ResetDeviceCommand.RaiseCanExecuteChanged();
                await MachineProvider.MachineOperator.Reset();
                await NotificationProvider.ShowInfo("Embedded device has been reset successfully.");
            }
            catch (Exception ex)
            {
                await NotificationProvider.ShowError(ex.FlattenMessage());
            }
            finally
            {
                _resettingDevice = false;
                ResetDeviceCommand.RaiseCanExecuteChanged();
            }
        }

        private async void FactoryReset()
        {
            if (await NotificationProvider.ShowQuestion("Are you sure you want to reset this device back to factory settings?"))
            {
                Settings.ApplicationState = ApplicationStates.FactoryRestore;
                Settings.Save();

                if (BuildProvider.BuildType == BuildType.TS1800)
                {
                    try
                    {
                        NotificationProvider.SetGlobalBusyMessage("Disabling write filter protection...");
                        await _uwf.Disable();
                        await Task.Delay(2000);
                        NotificationProvider.ReleaseGlobalBusyMessage();
                        await NavigationManager.NavigateTo(Common.Navigation.NavigationView.RestartingSystemView);
                        await Task.Delay(4000);
                        _os.Restart();
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error executing factory reset.");
                        NotificationProvider.ReleaseGlobalBusyMessage();
                        await NotificationProvider.ShowError($"Error executing factory reset.\n{ex.FlattenMessage()}");
                    }
                    finally
                    {
                        NotificationProvider.ReleaseGlobalBusyMessage();
                    }
                }
                else
                {
                    ApplicationManager.Restart();
                }
            }
        }

        private async void ShutdownSystem()
        {
            if (await NotificationProvider.ShowQuestion("Are you sure you want to shutdown the device?"))
            {
                _os.Shutdown();
            }
        }

        private async void RestartSystem()
        {
            if (await NotificationProvider.ShowQuestion("Are you sure you want to restart the device?"))
            {
                await NavigationManager.NavigateTo(Common.Navigation.NavigationView.RestartingSystemView);
                await Task.Delay(4000);
                _os.Restart();
            }
        }

        private async void ExitToExplorer()
        {
            if (await NotificationProvider.ShowQuestion("Close the application and start OS shell?"))
            {
                _os.OpenShell();
                ApplicationManager.ShutDown();
            }
        }

        public override void OnApplicationStarted()
        {
            _statsTimer = new Timer();
            _statsTimer.Interval = 2000;
            _statsTimer.Elapsed += _statsTimer_Elapsed;
            _statsTimer.Start();

            InitSite();
        }

        private void _statsTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (IsVisible)
            {
                CPU = GetAppCPU();
                RAM = GetAppRam();
                //Temperature = GetTemperature();
                UpTime = DateTime.Now - ApplicationManager.StartUpDate;
            }
        }

        public float GetTotalCPU()
        {
            PerformanceCounter cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";

            // will always start at 0
            float firstValue = cpuCounter.NextValue();
            System.Threading.Thread.Sleep(1000);
            // now matches task manager reading
            float secondValue = cpuCounter.NextValue();

            return secondValue;
        }

        public float GetAppCPU()
        {
            PerformanceCounter cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Process";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = Process.GetCurrentProcess().ProcessName;

            // will always start at 0
            float firstValue = cpuCounter.NextValue();
            System.Threading.Thread.Sleep(1000);
            // now matches task manager reading
            float secondValue = cpuCounter.NextValue();

            return secondValue / Environment.ProcessorCount;
        }

        public long GetAppRam()
        {
            Process proc = Process.GetCurrentProcess();
            return proc.PrivateMemorySize64;
        }

        public double GetTemperature()
        {
            try
            {
                double cpuTemp = 0;
                List<double> avg = new List<double>();
                ManagementObjectSearcher mos = new ManagementObjectSearcher(@"root\WMI", "Select * From MSAcpi_ThermalZoneTemperature");

                foreach (System.Management.ManagementObject mo in mos.Get())
                {
                    cpuTemp = Convert.ToDouble(Convert.ToDouble(mo.GetPropertyValue("CurrentTemperature").ToString()) - 2732) / 10;
                    avg.Add(cpuTemp);
                }

                return avg.Average();
            }
            catch
            {
                return 0;
            }
        }

        public String GetIpv4Address()
        {
            try
            {
                var host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (var ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        return ip.ToString();
                    }
                }
                return "N/A";
            }
            catch (Exception ex)
            {
                return "N/A";
            }
        }

        public async override void OnNavigatedTo()
        {
            base.OnNavigatedTo();

            IPAddress = GetIpv4Address();

            try
            {
                using (ObservablesContext db = ObservablesContext.CreateDefault())
                {
                    var jobRuns = await db.JobRuns.Select(x => new { x.StartDate, x.EndDate, x.EndPosition }).ToListAsync();

                    TotalDyeTime = TimeSpan.FromHours(jobRuns.Select(x => x.EndDate - x.StartDate).Sum(x => x.TotalHours)).ToStringUnlimitedHours();

                    int meters = (int)jobRuns.Select(x => x.EndPosition).Sum();
                    TotalDyeMeters = $"{meters.ToString("N0")} meters";
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error loading machine counters.");
                TotalDyeTime = "error!";
                TotalDyeMeters = "error!";
            }
        }

        public async void InitSite()
        {
            if (CurrentSite == null)
            {
                var machine = MachineProvider.Machine;
                if (machine != null && !String.IsNullOrEmpty(machine.SiteGuid))
                {
                    using (ObservablesContext db = ObservablesContext.CreateDefault())
                    {
                        var site = (await db.Sites.Where(x => x.Guid == machine.SiteGuid).ToListAsync()).FirstOrDefault();
                        CurrentSite = site;
                        RaisePropertyChanged( nameof(SiteName));
                    }
                }
            }
        }
    }
}