aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.DataCapture/ViewModels/MainViewVM.cs
blob: bbe5432e9aeb9991dcac65973dd6b0546a9ed32c (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
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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using Tango.BL.Entities;
using Tango.BL.Enumerations;
using Tango.Core.Commands;
using Tango.Core.Helpers;
using Tango.Integration.Diagnostics;
using Tango.Integration.Operation;
using Tango.Integration.ExternalBridge;
using Tango.MachineStudio.Common.Diagnostics;
using Tango.MachineStudio.Common.EventLogging;
using Tango.MachineStudio.Common.Notifications;
using Tango.MachineStudio.Common.StudioApplication;
using Tango.MachineStudio.Common.Video;
using Tango.MachineStudio.DataCapture.Recording;
using Tango.MachineStudio.DataCapture.Views;
using Tango.MachineStudio.Logging.ViewModels;
using Tango.PMR.Diagnostics;
using Tango.Settings;
using Tango.SharedUI;
using Tango.Video.DirectCapture;

namespace Tango.MachineStudio.DataCapture.ViewModels
{
    /// <summary>
    /// Represents the data capture main view, view model.
    /// </summary>
    /// <seealso cref="Tango.SharedUI.ViewModel" />
    public class MainViewVM : ViewModel
    {
        private INotificationProvider _notification;
        private IStudioApplicationManager _applicationManager;
        private IDiagnosticsFrameProvider _frameProvider;
        private IEventLogger _eventLogger;
        private String _recordingsFolder;
        private BarItem _recordingBarItem;
        private BarItem _playerBarItem;

        #region Properties

        private ObservableCollection<DataRecording> _recordings;
        /// <summary>
        /// Gets or sets the recordings collection.
        /// </summary>
        public ObservableCollection<DataRecording> Recordings
        {
            get { return _recordings; }
            set { _recordings = value; RaisePropertyChangedAuto(); }
        }

        private DataRecording _selectedRecording;
        /// <summary>
        /// Gets or sets the selected recording.
        /// </summary>
        public DataRecording SelectedRecording
        {
            get { return _selectedRecording; }
            set { _selectedRecording = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); }
        }

        /// <summary>
        /// Gets or sets the video capture provider.
        /// </summary>
        public IVideoCaptureProvider VideoCaptureProvider { get; set; }

        private DiagnosticsFileRecorder _recorder;
        /// <summary>
        /// Gets or sets the diagnostics file recorder.
        /// </summary>
        public DiagnosticsFileRecorder Recorder
        {
            get { return _recorder; }
            set { _recorder = value; RaisePropertyChangedAuto(); }
        }

        private DiagnosticsFilePlayer _player;
        /// <summary>
        /// Gets or sets the diagnostics file player.
        /// </summary>
        public DiagnosticsFilePlayer Player
        {
            get { return _player; }
            set { _player = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets or sets the machine operator.
        /// </summary>
        public IMachineOperator MachineOperator { get; set; }

        private List<CaptureDevice> _captureDevices;
        /// <summary>
        /// Gets or sets the capture devices.
        /// </summary>
        public List<CaptureDevice> CaptureDevices
        {
            get { return _captureDevices; }
            set { _captureDevices = value; RaisePropertyChangedAuto(); }
        }

        private TimelineViewVM _timelineViewVM;
        /// <summary>
        /// Gets or sets the timeline view VM.
        /// </summary>
        public TimelineViewVM TimelineViewVM
        {
            get { return _timelineViewVM; }
            set { _timelineViewVM = value; RaisePropertyChangedAuto(); }
        }

        #endregion

        #region Commands

        /// <summary>
        /// Gets or sets the remove recording command.
        /// </summary>
        public RelayCommand<DataRecording> RemoveRecordingCommand { get; set; }

        /// <summary>
        /// Gets or sets the toggle camera command.
        /// </summary>
        public RelayCommand<CaptureDevice> ToggleCameraCommand { get; set; }

        /// <summary>
        /// Gets or sets the media recording command.
        /// </summary>
        public RelayCommand MediaRecordingCommand { get; set; }

        /// <summary>
        /// Gets or sets the media stop command.
        /// </summary>
        public RelayCommand MediaStopCommand { get; set; }

        /// <summary>
        /// Gets or sets the media toggle play pause command.
        /// </summary>
        public RelayCommand MediaTogglePlayPauseCommand { get; set; }

        /// <summary>
        /// Gets or sets the media play pause command.
        /// </summary>
        public RelayCommand MediaPlayPauseCommand { get; set; }

        /// <summary>
        /// Gets or sets the media seek forward command.
        /// </summary>
        public RelayCommand MediaSeekForwardCommand { get; set; }

        /// <summary>
        /// Gets or sets the media seek backward command.
        /// </summary>
        public RelayCommand MediaSeekBackwardCommand { get; set; }

        /// <summary>
        /// Gets or sets the media seek command.
        /// </summary>
        public RelayCommand<double> MediaSeekCommand { get; set; }

        /// <summary>
        /// Gets or sets the media seek hold command.
        /// </summary>
        public RelayCommand MediaSeekHoldCommand { get; set; }

        #endregion

        #region Constructors

        public MainViewVM()
        {

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MainViewVM"/> class.
        /// </summary>
        public MainViewVM(IVideoCaptureProvider videoCaptureProvider, INotificationProvider notification, IStudioApplicationManager applicationManager, IDiagnosticsFrameProvider frameProvider, IEventLogger eventLogger)
        {
            _notification = notification;
            _applicationManager = applicationManager;
            _frameProvider = frameProvider;
            _eventLogger = eventLogger;

            _eventLogger.NewLog += _eventLogger_NewLog;

            Recorder = new DiagnosticsFileRecorder();
            Player = new DiagnosticsFilePlayer();

            TimelineViewVM = new TimelineViewVM(notification) { EnableTimeMarker = true };

            VideoCaptureProvider = videoCaptureProvider;
            Recordings = new ObservableCollection<DataRecording>();

            ToggleCameraCommand = new RelayCommand<CaptureDevice>(ToggleCamera);

            RemoveRecordingCommand = new RelayCommand<DataRecording>(RemoveRecording);

            MediaRecordingCommand = new RelayCommand(StartDiagnosticsRecording, () => !Recorder.IsRecording && MachineOperator != null && !Player.IsPlaying);
            MediaStopCommand = new RelayCommand(StopRecorderOrPlayer, () => Recorder.IsRecording || Player.IsPlaying);
            MediaPlayPauseCommand = new RelayCommand(DiagnosticsTogglePlayPause, () => !Recorder.IsRecording && SelectedRecording != null);
            MediaSeekForwardCommand = new RelayCommand(MediaSeekForward, () => !Recorder.IsRecording && Player.IsPlaying);
            MediaSeekBackwardCommand = new RelayCommand(MediaSeekBackward, () => !Recorder.IsRecording && Player.IsPlaying);
            MediaSeekCommand = new RelayCommand<double>(MediaSeek, (x) => Player.IsPlaying);
            MediaSeekHoldCommand = new RelayCommand(MediaSeekHold, () => Player.IsPlaying);

            _recordingsFolder = Path.Combine(Path.GetDirectoryName(SettingsManager.Default.Folder), "Recordings");
            Directory.CreateDirectory(_recordingsFolder);

            _frameProvider.FrameReceived += _frameProvider_FrameReceived;

            applicationManager.ConnectedMachineChanged += ApplicationManager_ConnectedMachineChanged;

            _recordingBarItem = new BarItem(_notification, new RecordingBarView() { DataContext = this });
            _playerBarItem = new BarItem(_notification, new PlayingBarView() { DataContext = this });

            CaptureDevices = VideoCaptureProvider.AvailableCaptureDevices.ToList();

            LoadRecordings();
        }

        #endregion

        #region Event Handlers

        private void _eventLogger_NewLog(object sender, MachinesEvent ev)
        {
            if (Recorder.IsRecording)
            {
                Recorder.Write(ev);
            }
        }

        private void ApplicationManager_ConnectedMachineChanged(object sender, IExternalBridgeClient machine)
        {
            MachineOperator = machine;
            InvalidateRelayCommands();
        }

        private void _frameProvider_FrameReceived(object sender, StartDiagnosticsResponse frame)
        {
            if (!_frameProvider.Disable)
            {
                if (Recorder.IsRecording)
                {
                    Recorder.Write(frame);

                    Task.Factory.StartNew(() =>
                    {
                        CaptureDevices.First().Invoke(() =>
                        {
                            if (Recorder.IsRecording)
                            {
                                Recorder.Write(CaptureDevices.Where(x => x.VideoSource != null).Select(x => x.VideoSource.GetAsFrozen() as BitmapSource));
                            }
                        });
                    });
                }
            }
        }


        #endregion

        #region Private Methods

        private void LoadRecordings()
        {
            foreach (var file in Directory.GetFiles(_recordingsFolder, "*.tdr"))
            {
                Recordings.Add(new DataRecording(file, File.GetCreationTime(file)));
            }

            Recordings = Recordings.OrderByDescending(x => x.Date).ToObservableCollection();
        }

        /// <summary>
        /// Removes the recording.
        /// </summary>
        /// <param name="recording">The recording.</param>
        private void RemoveRecording(DataRecording recording)
        {
            if (_notification.ShowQuestion("Are you sure you want to remove the specified recording?"))
            {
                Recordings.Remove(recording);
                PathHelper.TryDeleteFile(recording.FilePath);
            }
        }

        /// <summary>
        /// Toggles the camera.
        /// </summary>
        /// <param name="captureDevice">The capture device.</param>
        private void ToggleCamera(CaptureDevice captureDevice)
        {
            if (captureDevice.Device != null)
            {
                captureDevice.IsStarted = !captureDevice.IsStarted;
            }
        }

        private async void DiagnosticsTogglePlayPause()
        {
            if (!Player.IsPlaying || Player.IsPaused)
            {
                _frameProvider.Disable = true;

                if (SelectedRecording.Player == null)
                {
                    using (_notification.PushTaskItem("Loading Recording..."))
                    {
                        SelectedRecording.Player = new DiagnosticsFilePlayer();
                        await SelectedRecording.Player.Load(SelectedRecording.FilePath);
                        TimelineViewVM.Initialize(SelectedRecording.Player.MachineEvents);
                        TimelineViewVM.TimelineMaxTime = SelectedRecording.Player.TotalTime;
                    }
                }

                RegisterPlayer(SelectedRecording.Player);

                if (!Player.IsPlaying)
                {
                    _playerBarItem.Push();
                }

                Player.Play();
            }
            else
            {
                Player.Pause();
            }

            InvalidateRelayCommands();
        }

        private void RegisterPlayer(DiagnosticsFilePlayer player)
        {
            foreach (var recording in Recordings)
            {
                if (recording.Player != null)
                {
                    recording.Player.FrameReceived -= Player_FrameReceived;
                }
            }

            if (player != null)
            {
                Player = player;
                Player.FrameReceived += Player_FrameReceived;
            }

            CaptureDevices.ForEach(x => x.DisableSourceUpdate());
        }

        private void Player_FrameReceived(object sender, DataFileFrame frame)
        {
            if (_frameProvider.Disable)
            {
                _frameProvider.PushFrame(frame.StartDiagnosticsResponse);

                CaptureDevices.First().BeginInvoke(() =>
                {
                    for (int i = 0; i < frame.VideoFrames.Count; i++)
                    {
                        CaptureDevices[i].VideoSource = frame.VideoFrames[i].ToByteArray().ToBitmapSource();
                    }
                });

                TimelineViewVM.CurrentPosition = (sender as DiagnosticsFilePlayer).CurrentTime;
            }
        }

        public void StartDiagnosticsRecording()
        {
            using (_notification.PushTaskItem("Starting Recording..."))
            {
                Recorder.Start();
                _eventLogger.Log(EventTypes.RECORDING_STARTED, "Recording Started...");
                _recordingBarItem.Push();
            }

            InvalidateRelayCommands();
        }

        public async void StopRecorderOrPlayer()
        {
            if (Recorder.IsRecording)
            {
                using (_notification.PushTaskItem("Stopping Recording..."))
                {
                    await Recorder.Stop();
                    _recordingBarItem.Pop();

                    _eventLogger.Log(EventTypes.RECORDING_STOPPED, "Recording Stopped...");
                }

                String recordingName = _notification.ShowTextInput("Enter recording name", "Recording name");

                if (!String.IsNullOrWhiteSpace(recordingName))
                {
                    using (_notification.PushTaskItem("Saving Recording..."))
                    {
                        String filePath = Path.Combine(_recordingsFolder, recordingName + ".tdr");
                        await Recorder.Save(filePath);
                        Recordings.Insert(0, new DataRecording(filePath));
                    }
                }

                Recorder.Dispose();
                Recorder = new DiagnosticsFileRecorder();
            }
            else if (Player.IsPlaying)
            {
                await Player.Stop();
                TimelineViewVM.CurrentPosition = TimeSpan.Zero;
                CaptureDevices.ForEach(x => x.EnableSourceUpdate());
                _frameProvider.Disable = false;
                _playerBarItem.Pop();
            }

            InvalidateRelayCommands();
        }

        private void MediaSeekBackward()
        {
            if (Player.IsPlaying)
            {
                Player.Seek(Player.CurrentFrame - 200);
            }
        }

        private void MediaSeekForward()
        {
            if (Player.IsPlaying)
            {
                Player.Seek(Player.CurrentFrame + 200);
            }
        }

        private void MediaSeek(double frame)
        {
            if (Player != null)
            {
                Player.Seek((int)frame);
                Player.Play();
            }
        }

        private void MediaSeekHold()
        {
            if (Player != null)
            {
                Player.Pause();
            }
        }

        #endregion
    }
}