aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.Stubs/Images
ModeNameSize
-rw-r--r--stubs.jpg96798logstatsplain
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tango.BL.Entities;
using Tango.Core;
using Tango.Logging;
using Tango.PMR.Diagnostics;
using Tango.Serialization;

namespace Tango.Integration.Diagnostics
{
    /// <summary>
    /// Represents a Tango machine diagnostics file player capable of streaming diagnostics data frames.
    /// </summary>
    /// <seealso cref="Tango.Core.ExtendedObject" />
    /// <seealso cref="System.IDisposable" />
    public class DiagnosticsFilePlayer : ExtendedObject, IDisposable
    {
        private FileStream _dataFileStream; //Holds the data file stream.
        private DiagnosticsTimeCodeChannel _timeCodeChannel; //Holds the encapsulated time code data.
        private long _diagnosticsDataOffset; //Holds the actual starting position for the diagnostics packets.
        private Thread _playThread; //Holds the playing thread.
        private TaskCompletionSource<object> _stopTaskSource; //Holds the "Stop" async method completion source.

        #region Events

        /// <summary>
        /// Occurs when there is a new diagnostic frame is available.
        /// </summary>
        public event EventHandler<DataFileFrame> FrameReceived;

        #endregion

        #region Properties

        private bool _isLoaded;
        /// <summary>
        /// Gets a value indicating whether a diagnostics file is currently loaded and ready to be played.
        /// </summary>
        public bool IsLoaded
        {
            get { return _isLoaded; }
            private set { _isLoaded = value; RaisePropertyChangedAuto(); }
        }

        private bool _isPlaying;
        /// <summary>
        /// Gets a value indicating whether the player is in play mode (Played/Pause).
        /// </summary>
        public bool IsPlaying
        {
            get { return _isPlaying; }
            private set { _isPlaying = value; RaisePropertyChangedAuto(); }
        }

        private bool _isPaused;
        /// <summary>
        /// Gets or sets a value indicating whether the player is paused.
        /// </summary>
        public bool IsPaused
        {
            get { return _isPaused; }
            private set { _isPaused = value; RaisePropertyChangedAuto(); }
        }

        private TimeSpan _currentTime;
        /// <summary>
        /// Gets the current playing time.
        /// </summary>
        public TimeSpan CurrentTime
        {
            get { return _currentTime; }
            private set { _currentTime = value; RaisePropertyChanged(nameof(CurrentTime)); }
        }

        private TimeSpan _totalTime;
        /// <summary>
        /// Gets or sets the total playing time.
        /// </summary>
        public TimeSpan TotalTime
        {
            get { return _totalTime; }
            set { _totalTime = value; RaisePropertyChangedAuto(); }
        }

        private int _currentFrame;
        /// <summary>
        /// Gets or sets the current frame index.
        /// </summary>
        public int CurrentFrame
        {
            get { return _currentFrame; }
            set
            {
                _currentFrame = value;

                OnCurrentFrameChanged();

                RaisePropertyChanged(nameof(CurrentFrame));
            }
        }

        private long _totalFrames;
        /// <summary>
        /// Gets the total frames count.
        /// </summary>
        public long TotalFrames
        {
            get { return _totalFrames; }
            private set { _totalFrames = value; RaisePropertyChangedAuto(); }
        }

        private List<MachinesEvent> _machineEvents;
        /// <summary>
        /// Gets or sets the machine events.
        /// </summary>
        public List<MachinesEvent> MachineEvents
        {
            get { return _machineEvents; }
            set { _machineEvents = value; RaisePropertyChangedAuto(); }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Loads the specified diagnostics file.
        /// </summary>
        /// <param name="fileName">Absolute file path.</param>
        /// <returns></returns>
        public async Task Load(String fileName)
        {
            Task task = new Task(() => 
            {
                try
                {
                    if (_dataFileStream != null)
                    {
                        _dataFileStream.Dispose();
                    }

                    _dataFileStream = new FileStream(fileName, FileMode.Open);

                    BinaryReader binaryReader = new BinaryReader(_dataFileStream);

                    int timeCodeDataSize = binaryReader.ReadInt32();
                    byte[] timeCodeData = binaryReader.ReadBytes(timeCodeDataSize);

                    BinaryDataSerializer serializer = new BinaryDataSerializer();
                    _timeCodeChannel = serializer.DeserializeFromBytes<DiagnosticsTimeCodeChannel>(timeCodeData);

                    _diagnosticsDataOffset = _dataFileStream.Position;

                    CurrentFrame = 0;
                    TotalFrames = _timeCodeChannel.Frames.Count;
                    TotalTime = TimeSpan.FromMilliseconds(_timeCodeChannel.Frames.Last().Milliseconds);

                    if (_timeCodeChannel.Events != null)
                    {
                        MachineEvents = _timeCodeChannel.Events.Select(x => x.ToMachineEvent()).ToList();
                    }

                    IsLoaded = true;
                }
                catch (Exception ex)
                {
                    if (_dataFileStream != null)
                    {
                        _dataFileStream.Dispose();
                    }

                    throw LogManager.Log(ex);
                }
            });

            task.Start();
            await task;
        }

        /// <summary>
        /// Seeks to the specified frame index.
        /// </summary>
        /// <param name="frameIndex">Index of the frame.</param>
        public void Seek(int frameIndex)
        {
            if (frameIndex < 0)
            {
                frameIndex = 0;
            }
            else if (frameIndex > TotalFrames - 1)
            {
                frameIndex = (int)(TotalFrames - 1);
            }

            CurrentFrame = frameIndex;
        }

        /// <summary>
        /// Starts playing the diagnostics file.
        /// </summary>
        /// <exception cref="InvalidOperationException">No diagnostics file is currently loaded.</exception>
        public void Play()
        {
            if (!IsLoaded) throw LogManager.Log(new InvalidOperationException("No diagnostics file is currently loaded."));

            IsPaused = false;

            if (!IsPlaying)
            {
                IsPlaying = true;
                _playThread = new Thread(PlayThreadMethod);
                _playThread.IsBackground = true;
                _playThread.Start();
            }
        }

        /// <summary>
        /// Stops this instance.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException">No diagnostics file is currently loaded.</exception>
        public Task Stop()
        {
            if (!IsLoaded) throw LogManager.Log(new InvalidOperationException("No diagnostics file is currently loaded."));

            if (IsPlaying)
            {
                _stopTaskSource = new TaskCompletionSource<object>();
                IsPlaying = false;
                IsPaused = false;
                return _stopTaskSource.Task;
            }
            else
            {
                return Task.FromResult(new object());
            }
        }

        /// <summary>
        /// Pauses the player.
        /// </summary>
        /// <exception cref="InvalidOperationException">No diagnostics file is currently loaded.</exception>
        public void Pause()
        {
            if (!IsLoaded) throw LogManager.Log(new InvalidOperationException("No diagnostics file is currently loaded."));

            if (IsPlaying)
            {
                IsPaused = true;
            }
        }

        #endregion

        #region Protected Methods

        /// <summary>
        /// Called when the current frame has been changed
        /// </summary>
        protected void OnCurrentFrameChanged()
        {
            if (IsPlaying)
            {
                if (_currentFrame > _timeCodeChannel.Frames.Count - 1)
                {
                    _currentFrame = _timeCodeChannel.Frames.Count - 1;
                }

                if (_dataFileStream != null && _dataFileStream.CanSeek)
                {
                    _dataFileStream.Position = _diagnosticsDataOffset + _timeCodeChannel.Frames[_currentFrame].Position;
                }

                byte[] data = new byte[_timeCodeChannel.Frames[_currentFrame].FrameLength];
                _dataFileStream.Read(data, 0, data.Length);
                DataFileFrame frame = DataFileFrame.Parser.ParseFrom(data);
                OnFrameReceived(frame);
                data = null;
            }

            if (_timeCodeChannel != null)
            {
                CurrentTime = TimeSpan.FromMilliseconds(_timeCodeChannel.Frames[_currentFrame].Milliseconds);
            }
        }

        /// <summary>
        /// Raises the <see cref="FrameReceived"/> event.
        /// </summary>
        /// <param name="frame">The frame.</param>
        protected virtual void OnFrameReceived(DataFileFrame frame)
        {
            FrameReceived?.Invoke(this, frame);
        }

        #endregion

        #region Playing Thread

        /// <summary>
        /// Handles the playing thread.
        /// </summary>
        private void PlayThreadMethod()
        {
            while (IsPlaying)
            {
                if (!IsPaused)
                {
                    CurrentFrame++;

                    if (CurrentFrame >= TotalFrames - 1)
                    {
                        CurrentFrame = 0;
                    }
                }

                if (CurrentFrame > 0)
                {
                    Thread.Sleep(_timeCodeChannel.Frames[CurrentFrame].Milliseconds - _timeCodeChannel.Frames[CurrentFrame - 1].Milliseconds);
                }
                else
                {
                    Thread.Sleep(10);
                }
            }

            CurrentFrame = 0;
            CurrentTime = TimeSpan.Zero;

            _stopTaskSource.SetResult(new object());
        }

        #endregion

        #region IDisposable

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            IsPlaying = false;

            if (_dataFileStream != null)
            {
                _dataFileStream.Dispose();
                _dataFileStream = null;
            }
        }

        #endregion

        #region Finalizer

        /// <summary>
        /// Finalizes an instance of the <see cref="DiagnosticsFilePlayer"/> class.
        /// </summary>
        ~DiagnosticsFilePlayer()
        {
            if (_dataFileStream != null)
            {
                _dataFileStream.Dispose();
            }
        }

        #endregion
    }
}