aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.DataCapture/ViewModels/MainViewVM.cs
blob: 5bd6ff809d410f5d88717798397d4d0ebb4d2be4 (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
40pre { 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.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.BL.Entities;
using Tango.MachineStudio.Common.Notifications;

namespace Tango.MachineStudio.DB.ViewModels
{
    public class ProcessParametersTablesGroupsViewVM : DbTableViewModel<ProcessParametersTablesGroup>
    {
        public ProcessParametersTablesGroupsViewVM(INotificationProvider notification) : base(notification)
        {
            
        }

        protected override void OnBeforeEntitySave(DialogOpenMode mode, ProcessParametersTablesGroup entity)
        {
            entity.SaveDate = DateTime.UtcNow;

            if (entity.Rml != null && entity.Active)
            {
                foreach (var group in entity.Rml.ProcessParametersTablesGroups.Where(x => x != entity))
                {
                    group.Active = false;
                }
            }

            base.OnBeforeEntitySave(mode, entity);
        }
    }
}
id='n362' href='#n362'>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
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.Services;
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

        /// <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.RecordingStarted, "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.RecordingStopped, "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
    }
}