aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/StubsUtils/Tango.StubsUtils.Service.UI/ViewModels/MainViewVM.cs
blob: 091bb6bf3226745ec64bc0901fc01a761474fc66 (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
using Notifications.Wpf;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using Tango.Core;
using Tango.Core.Commands;
using Tango.Logging;
using Tango.Settings;
using Tango.SharedUI;
using Tango.SharedUI.Components;
using Tango.SharedUI.Helpers;
using Tango.StubsUtils.Service.UI.Views;

namespace Tango.StubsUtils.Service.UI.ViewModels
{
    public class MainViewVM : ViewModel
    {
        private ProducerConsumerQueue<String> _logsQueue;
        private Thread _logsThread;
        private NotificationManager _notification;

        private ServiceUISettings _settings;
        public ServiceUISettings Settings
        {
            get { return _settings; }
            set { _settings = value; RaisePropertyChangedAuto(); }
        }

        private StubsService _service;
        public StubsService Service
        {
            get { return _service; }
            set { _service = value; RaisePropertyChangedAuto(); }
        }

        private bool _isTrayIconVisible;
        public bool IsTrayIconVisible
        {
            get { return _isTrayIconVisible; }
            set { _isTrayIconVisible = value; RaisePropertyChangedAuto(); }
        }

        private List<String> _availablePorts;
        public List<String> AvailablePorts
        {
            get { return _availablePorts; }
            set { _availablePorts = value; RaisePropertyChangedAuto(); }
        }

        private String _selectedPort;
        public String SelectedPort
        {
            get { return _selectedPort; }
            set { _selectedPort = value; RaisePropertyChangedAuto(); }
        }

        private SimpleStringLogger _logger;
        public SimpleStringLogger Logger
        {
            get { return _logger; }
            set { _logger = value; RaisePropertyChangedAuto(); }
        }

        public RelayCommand ExitCommand { get; set; }
        public RelayCommand OpenCommand { get; set; }
        public RelayCommand RefreshPortsCommand { get; set; }
        public RelayCommand ToggleConnectionCommand { get; set; }
        public RelayCommand ClearLogCommand { get; set; }
        public RelayCommand StartPerformanceTesterCommand { get; set; }

        public MainViewVM()
        {
            ExitCommand = new RelayCommand(ExitApplication);
            OpenCommand = new RelayCommand(OpenMainWindow);
            IsTrayIconVisible = true;
            AvailablePorts = new List<string>();
            RefreshPortsCommand = new RelayCommand(RefreshPorts);
            ToggleConnectionCommand = new RelayCommand(ToggleConnection);
            StartPerformanceTesterCommand = new RelayCommand(StartPerformanceTester);
            ClearLogCommand = new RelayCommand(ClearLog);
            _logsQueue = new ProducerConsumerQueue<string>();

            _logsThread = new Thread(LogsThreadMethod);
            _logsThread.IsBackground = true;
            _logsThread.Start();

            _notification = new NotificationManager();

            Init();
        }

        public async void Init()
        {
            try
            {
                Logger = new SimpleStringLogger() { Enabled = true };
                Logger.LogReceived += Logger_LogReceived;

                LogManager.RegisterLogger(Logger);

                LogManager.Log("Initializing...");
                Settings = SettingsManager.Default.GetOrCreate<ServiceUISettings>();
                SelectedPort = Settings.USBPort;

                RefreshPorts();

                Service = new StubsService();
                Service.CommunicationFailed += Service_CommunicationFailed;
                await Service.Start();

                _notification.Show(new NotificationContent()
                {
                    Title = "Tango Stubs Service",
                    Message = $"Service Started",
                    Type = NotificationType.Success
                });

                if (Settings.AutoConnect)
                {
                    await Task.Delay(2000);
                    ToggleConnection();
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error initializing service.");

                _notification.Show(new NotificationContent()
                {
                    Title = "Tango Stubs Service",
                    Message = $"Initialization Error",
                    Type = NotificationType.Error
                });
            }
        }

        private void Service_CommunicationFailed(object sender, EventArgs e)
        {
            if (IsTrayIconVisible)
            {
                InvokeUI(() => 
                {
                    _notification.Show(new NotificationContent()
                    {
                        Title = "Tango Stubs Service",
                        Message = $"Communication Error",
                        Type = NotificationType.Error
                    });
                });
            }
        }

        private void Logger_LogReceived(object sender, LogItemBase e)
        {
            String message = e.TimeStamp.ToString("HH:mm:ss.ff") + ": " + e.Message;
            _logsQueue.BlockEnqueue(message);
        }

        private void LogsThreadMethod()
        {
            while (true)
            {
                List<String> logs = new List<string>();

                logs.Add(_logsQueue.BlockDequeue());

                while (_logsQueue.Count > 0)
                {
                    logs.Add(_logsQueue.BlockDequeue());
                }

                InvokeUINow(() =>
                {
                    List<Inline> inlines = new List<Inline>();

                    foreach (var log in logs)
                    {
                        inlines.Add(new Run(log));
                        inlines.Add(new LineBreak());
                    }

                    MainView.Instance.paragraphLog.Inlines.AddRange(inlines);

                    if (Mouse.LeftButton != MouseButtonState.Pressed)
                    {
                        MainView.Instance.scrollViewerLogs.ScrollViewer?.ScrollToEnd();
                    }
                });

                Thread.Sleep(200);
            }
        }

        private void ClearLog()
        {
            InvokeUI(() =>
            {
                IsFree = false;
                UIHelper.DoEvents();
                MainView.Instance.paragraphLog.Inlines.Clear();
                IsFree = true;
            });
        }

        private async void OpenMainWindow()
        {
            Application.Current.MainWindow.Visibility = Visibility.Visible;
            await Task.Delay(200);
            Application.Current.MainWindow.WindowState = WindowState.Normal;
            Application.Current.MainWindow.Focus();
            Application.Current.MainWindow.Activate();
            IsTrayIconVisible = false;
        }

        public async void ExitApplication()
        {
            IsFree = false;
            SaveSettings();
            IsTrayIconVisible = false;
            UIHelper.DoEvents();
            await Task.Delay(1000);
            Environment.Exit(0);
        }

        private void RefreshPorts()
        {
            AvailablePorts = SerialPort.GetPortNames().ToList();

            if (SelectedPort == null)
            {
                SelectedPort = AvailablePorts.FirstOrDefault();
            }

            InvalidateRelayCommands();
        }

        private async void ToggleConnection()
        {
            try
            {
                IsFree = false;

                if (!Service.IsConnected)
                {
                    try
                    {
                        await Service.Connect(SelectedPort);
                        SaveSettings();

                        if (IsTrayIconVisible)
                        {
                            _notification.Show(new NotificationContent()
                            {
                                Title = "Tango Stubs Service",
                                Message = $"Connected ({SelectedPort})",
                                Type = NotificationType.Success
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error connecting to the specified serial port.");

                        if (IsTrayIconVisible)
                        {
                            _notification.Show(new NotificationContent()
                            {
                                Title = "Tango Stubs Service",
                                Message = $"Connection Error ({SelectedPort})",
                                Type = NotificationType.Error
                            });
                        }
                    }
                }
                else
                {
                    try
                    {
                        await Service.Disconnect();
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error disconnecting from the specified serial port.");
                    }
                }
            }
            finally
            {
                IsFree = true;
            }
        }

        private void SaveSettings()
        {
            Settings.USBPort = SelectedPort;
            Settings.Save();
        }

        private void StartPerformanceTester()
        {
            Process.Start("tangostub_perf.exe");
        }
    }
}