/// <summary>
 /// Initialize a new instance of the class. This constructor instantiates each element of the 'DownloadedEvents' array with a new EventRecord.
 /// </summary>
 public MostRecentDownloadedEvents()
 {
     for (short car = CarNumberMinValue; car <= CarNumberMaxValue; car++)
     {
         m_MostRecentDownloadedEvents[car] = new EventRecord();
     }
 }
        /// <summary>
        /// Get the fault log/snapshot log data stream corresponding to the specified record.
        /// </summary>
        /// <param name="eventRecord">The event record associated with the data stream that is to be downloaded.</param>
        /// <returns>The data stream corresponding to the specified event record.</returns>
        /// <exception cref="CommunicationException">Thrown if the error code returned from the calls to the PTUDLL32.GetStreamInformation() or PTUDLL32Event.GetStream()
        /// methods is not CommunicationError.Success.</exception>
        public DataStream_t GetStream(EventRecord eventRecord)
        {
            short watchVariableCount, sampleCount, sampleMultiple;
            short[] watchIdentifiers, dataTypes;
            GetStreamInformation(0, out watchVariableCount, out sampleCount, out sampleMultiple, out watchIdentifiers, out dataTypes);

            int[] buffer = new int[sampleCount * watchVariableCount];   // Default values are all zeroes.

            // Not used by the calling class.
            // short timeOrigin = 0;

            Workset_t workset = ConvertToWorkset(eventRecord.Description, watchIdentifiers, sampleMultiple);
            DataStream_t dataStream = new DataStream_t(eventRecord, watchVariableCount, sampleCount, sampleMultiple, workset);

            DateTime startTime = eventRecord.DateTime.Subtract(new TimeSpan(0, 0, 0, 0, dataStream.DurationPreTripMs));

            // Convert the retrieved data stream into a list of individual, time-stamped watch variable data frames.
            List<WatchFrame_t> watchFrameList = ConvertToWatchFrameList(startTime, sampleCount, dataStream.FrameIntervalMs, buffer, dataTypes, workset);

            dataStream.WatchFrameList = watchFrameList;

            // Configure the upper and lower display limits.
            dataStream.ConfigureAutoScale();
#if NODELAY
#else
            // Include a delay to provide verisimilitude.
            System.Threading.Thread.Sleep(SleepMsVerisimilitudeGetStream);
#endif
            return dataStream;
        }
        /// <summary>
        /// Get the event record, including the event variable values, corresponding to the specified event index for the event log that is currently loaded into memory.
        /// </summary>
        /// <param name="currentEventLog">The event log that has been loaded into memory using the LoadEventLog() method.</param>
        /// <param name="eventIndex">The event index of the required event record.</param>
        /// <param name="eventRecord">The event record corresponding to the specified event index.</param>
        /// <exception cref="CommunicationException">Thrown if the error code returned from the call to the PTUDLL32.GetFaultHdr() method is not CommunicationError.Success.</exception>
        public void GetEventRecord(Log currentEventLog, short eventIndex, out EventRecord eventRecord)
        {
            if (eventIndex < 0)
            {
                eventRecord = null;
                return;
            }

            String time, date;
            time = DateTime.Now.ToString(CommonConstants.FormatStringTimeSec);
            date = DateTime.Now.ToString(CommonConstants.FormatStringDateFromVCU);

            short logIndex = (short)(currentEventLog.Identifier - 1);

            short lookupIndex = 0, i = 0;
            if (eventIndex < Lookup.EventTable.IdentifierMax)
            {
                do
                {
                    while (Lookup.EventTable.Items[lookupIndex] == null)
                        ++lookupIndex;
                    if (i == eventIndex)
                        break;
                    ++i;
                    ++lookupIndex;
                }
                while (lookupIndex < Lookup.EventTable.IdentifierMax);

                eventRecord = new EventRecord(lookupIndex);

                if (eventRecord.LogIdentifier != logIndex)
                {
                    eventRecord = null;
                    return;
                }
            }
            else    // Invalid index
            {
                eventRecord = null;
                return;
            }

            // Add the record VCU fields.
            eventRecord.LogIdentifier = currentEventLog.Identifier;
            eventRecord.EventIndex = lookupIndex;
            eventRecord.Time = time;
            eventRecord.Date = date;

            // Convert the date and time retrieved from the VCU to a .NET DateTime object.
            try
            {
                eventRecord.DateTime = DateTime.Parse(date + CommonConstants.Space + time, new CultureInfo(CultureEnglishUS, false));
            }
            catch (FormatException)
            {
                eventRecord.DateTime = Parameter.InvalidDateTime;
            }

            if (eventRecord.StreamNumber == CommonConstants.False)
            {
                eventRecord.StreamSaved = false;
            }
            else
            {
                eventRecord.StreamSaved = true;
            }

            // ---------------------------------------------------------
            // Get the event variables associated with the event record.
            // ---------------------------------------------------------

            // Define the data types associated with each event variable aasociated with the selected event.
            short[] types = new short[eventRecord.EventVariableList.Count];
            for (int index = 0; index < eventRecord.EventVariableList.Count; index++)
            {
                types[index] = (short)eventRecord.EventVariableList[index].DataType;
            }

            // -----------------------------------------------------------------------------------------------------
            // Retrieve and store the raw values for each of the event variables associated with the event.
            // -----------------------------------------------------------------------------------------------------
            double[] values;
            GetFaultVar(eventRecord.EventIndex, (short)eventRecord.EventVariableList.Count, types, out values);

            // Store the raw event variable values.
            for (int index = 0; index < eventRecord.EventVariableList.Count; index++)
            {
                eventRecord.EventVariableList[index].ValueFromTarget = values[index];
            }
#if NODELAY
#else
            // Include a delay to provide verisimilitude.
            System.Threading.Thread.Sleep(SleepMsVerisimilitudeGetRecord);
#endif
        }
예제 #4
0
        /// <summary>
        /// Clean up the resources used by the form.
        /// </summary>
        /// <param name="disposing">True to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected override void Cleanup(bool disposing)
        {
            try
            {
                if (disposing)
                {
                    // Cleanup managed objects by calling their Dispose() methods.
                    if (components != null)
                    {
                        components.Dispose();
                    }

                    if (m_TimerProgressBarUpdate != null)
                    {
                        m_TimerProgressBarUpdate.Stop();
                        m_TimerProgressBarUpdate.Dispose();
                    }

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

                // Whether called by consumer code or the garbage collector free all unmanaged resources and set the value of managed data members to null.
                m_TimerProgressBarUpdate = null;
                m_CommunicationInterface = null;
                m_EventRecord = null;
                m_BackgroundWorker = null;
                
                #region --- Windows Form Designer Variables ---
                // Detach the event handler delegates.

                // Set the Windows Form Designer Variables to null.

                #endregion --- Windows Form Designer Variables ---
            }
            catch (Exception)
            {
                // Don't do anything, just ensure that an exception isn't thrown.
            }
            finally
            {
                base.Cleanup(disposing);
            }
        }
예제 #5
0
        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        /// <param name="communicationInterface">Reference to the communicaton interface that is to be used to communicate with the VCU</param>
        /// <param name="eventRecord">The event record associated with the data stream.</param>
        public FormGetStream(ICommunicationEvent communicationInterface, EventRecord eventRecord)
        {
            InitializeComponent();

            CommunicationInterface = communicationInterface;
            Debug.Assert(CommunicationInterface != null);

            m_EventRecord = eventRecord;
            m_LabelDataStreamName.Text = string.Format("{0} {1} - {2}", m_EventRecord.Description, m_EventRecord.DateTime.ToShortDateString(), m_EventRecord.DateTime.ToString("HH:mm:ss"));

            #region - [Background Worker] -
            // Instantiate BackgroundWorker and attach handlers to its DoWork and RunWorkerCompleted events.
            m_BackgroundWorker = new BackgroundWorker();
            m_BackgroundWorker.DoWork += new DoWorkEventHandler(m_BackgroundWorker_DoWork);
            //m_BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_BackgroundWorker_RunWorkerCompleted);
            #endregion - [Background Worker] -

            #region - [ProgressBar Timer] -
            m_TimerProgressBarUpdate = new System.Windows.Forms.Timer();
            m_TimerProgressBarUpdate.Tick += new EventHandler(ProgressBarUpdate);
            m_TimerProgressBarUpdate.Interval = IntervalMsDisplayUpdate;
            m_TimerProgressBarUpdate.Enabled = true;
            m_TimerProgressBarUpdate.Stop();
            #endregion - [ProgressBar Timer] -

            #region - [Progress Bar] -
            short dataStreamTypeIdentifier;
            try
            {
                dataStreamTypeIdentifier = Lookup.LogTable.Items[m_EventRecord.LogIdentifier].DataStreamTypeIdentifier;
            }
            catch (Exception)
            {
                dataStreamTypeIdentifier = 0;
            }

            int updatesPerSec = (int)(CommonConstants.SecondMs / IntervalMsDisplayUpdate);

            switch (dataStreamTypeIdentifier)
            {
                case DataStreamTypeStandardFaultLog:
                    m_ProgressBarDownload.Maximum = DurationSecDownloadStandardFaultLog * updatesPerSec;
                    m_TimeoutMsThreadComplete = (int)(DurationSecDownloadStandardFaultLog * TimeoutFactor);
                    break;
                case DataStreamTypeFaultLogCTA:
                    m_ProgressBarDownload.Maximum = DurationSecDownloadFaultLogCTA * updatesPerSec;
                    m_TimeoutMsThreadComplete = (int)(DurationSecDownloadFaultLogCTA * TimeoutFactor);
                    break;
                case DataStreamTypeSnapshotLog:
                    m_ProgressBarDownload.Maximum = DurationSecDownloadSnapshotLog * updatesPerSec;
                    m_TimeoutMsThreadComplete = (int)(DurationSecDownloadSnapshotLog * TimeoutFactor);
                    break;
                default:
                    m_ProgressBarDownload.Maximum = DurationSecDownloadStandardFaultLog * updatesPerSec;
                    m_TimeoutMsThreadComplete = (int)(DurationSecDownloadStandardFaultLog * TimeoutFactor);
                    break;
            }
            
            m_ProgressBarDownload.Minimum = 0;
            m_ProgressBarDownload.Value = 0;
            #endregion - [Progress Bar] -
        }
예제 #6
0
        /// <summary>
        /// Get the fully qualified filename of the fault log associated with the specified event record.
        /// </summary>
        /// <remarks>
        /// Returns string.Empty if a stream has not been saved for the specified event record.
        /// </remarks>
        /// <param name="eventRecord">The event record.</param>
        /// <returns>The fully qualified filename of the fault log associated with the specified event record.</returns>
        public static string GetFullyQualifiedFaultLogFilename(EventRecord eventRecord)
        {
            if (eventRecord.StreamSaved == true)
            {
                Debug.Assert(eventRecord.CarIdentifier != string.Empty,
                             "FormViewEventLog.GetFullyQualifiedFaultLogFilename() - [eventRecord.CarIdentifier != string.Empty]");
                Debug.Assert(eventRecord.Description != string.Empty,
                             "FormViewEventLog.GetFullyQualifiedFaultLogFilename() - [eventRecord.Description != string.Empty]");

                string defaultFilename = General.DeriveName(eventRecord.CarIdentifier, eventRecord.DateTime, CommonConstants.ExtensionFaultLog,
                                                            eventRecord.Description);
                string fullFilename = DirectoryManager.PathFaultLogs + CommonConstants.BindingFilename + defaultFilename;
                return fullFilename;
            }
            else
            {
                return string.Empty;
            }
        }
예제 #7
0
        /// <summary>
        /// Initializes a new instance of the structure. Used when initializing a datastream to store fault log data retrieved from the VCU. 
        /// </summary>
        /// <param name="eventRecord">The event record associated with the data stream.</param>
        /// <param name="watchCount">The number of watch variables contained within the data stream.</param>
        /// <param name="sampleCount">The number of data samples associated with the data stream.</param>
        /// <param name="sampleMultiple">The multiple of the base sample interval at which the data is recorded.</param>
        /// <param name="workset">The workset associated with the data stream.</param>
        public DataStream_t(EventRecord eventRecord, short watchCount, short sampleCount, short sampleMultiple, Workset_t workset)
        {
            // Get the log information associated with the event record.
            Log log = Lookup.LogTable.Items[eventRecord.LogIdentifier];

            DataStreamTypeParameters = log.DataStreamTypeParameters;
            StreamNumber = eventRecord.StreamNumber;
            LogType = LogType.DataStream;
            EventDescription = eventRecord.Description;
            FrameIntervalMs = (short)(sampleMultiple * log.SampleIntervalMs);

            SampleCount = sampleCount;
            DurationMs = (SampleCount - 1) * FrameIntervalMs;

            DurationPreTripMs = DataStreamTypeParameters.TripIndex * FrameIntervalMs;
            DurationPostTripMs = DurationMs - DurationPreTripMs;

            Workset = new Workset_t();
            Workset = workset;

            WatchFrameList = new List<WatchFrame_t>(SampleCount);
            AutoScaleWatchValues = new AutoScale_t[workset.Count];
            TimeOrigin = CommonConstants.NotDefined;
        }
예제 #8
0
        /// <summary>
        /// If a fault log data stream has been saved for the selected event record, retrieve the fault log from disk and call the form used to plot the fault log.
        /// </summary>
        /// <param name="selectedEventRecord">The selected event record.</param>
        protected override void ShowFaultLog(EventRecord selectedEventRecord)
        {
            // Skip, if the Dispose() method has been called.
            if (IsDisposed)
            {
                return;
            }

            // Skip, if a data stream hasn't been saved for the selected record.
            if ((selectedEventRecord == null) || (selectedEventRecord.StreamSaved == false))
            {
                MessageBox.Show(Resources.MBTFaultLogNotAvailable, Resources.MBCaptionInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // ------------------------------------------------------------------------
            // Retrieve the data stream corresponding to the selected record from disk.
            // ------------------------------------------------------------------------
            string fullyQualifiedFaultLogFilename = General.GetFullyQualifiedFaultLogFilename(selectedEventRecord);
            FileInfo fileInfo = new FileInfo(fullyQualifiedFaultLogFilename);
            WatchFile_t watchFile;
            if (fileInfo.Exists)
            {
                // De-serialize the selected file.
                watchFile = FileHandling.Load<WatchFile_t>(fullyQualifiedFaultLogFilename, FileHandling.FormatType.Binary);

                // Ensure that the de-serialized file contains data.
                if (watchFile.DataStream.WatchFrameList == null)
                {
                    // File format is not recognised, report message.
                    MessageBox.Show(Resources.MBTInvalidFormat, Resources.MBCaptionError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // Ensure that the selected log file is associated with the current project.
                if (watchFile.Header.ProjectInformation.ProjectIdentifier != Parameter.ProjectInformation.ProjectIdentifier)
                {
                    MessageBox.Show(Resources.MBTProjectIdMismatch, Resources.MBCaptionError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                watchFile.Filename = fileInfo.Name;
                watchFile.FullFilename = fileInfo.FullName;
            }
            else
            {
                MessageBox.Show(Resources.MBTDataStreamNotSaved, Resources.MBCaptionInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                Cursor = Cursors.Default;
                return;
            }

            // -------------------------
            // Plot the saved fault log.
            // -------------------------
            try
            {
                FormOpenFaultLog formViewSavedFaultLog = new FormOpenFaultLog(watchFile);
                formViewSavedFaultLog.MdiParent = MdiParent;

                // The CalledFrom property is used to allow the called form to reference back to this form.
                formViewSavedFaultLog.CalledFrom = this;
                formViewSavedFaultLog.Show();
                Hide();
            }
            catch (Exception exception)
            {
                MessageBox.Show(Resources.MBTShowFaultLogFailed + CommonConstants.NewLine + CommonConstants.NewLine + exception.Message, Resources.MBCaptionInformation,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return;
        }
예제 #9
0
        /// <summary>
        /// Get the event record, including the event variable values, corresponding to the specified event index for the event log that is currently
        /// loaded into memory.
        /// </summary>
        /// <param name="currentEventLog">The event log that has been loaded into memory using the LoadEventLog() method.</param>
        /// <param name="eventIndex">The event index of the required event record.</param>
        /// <param name="eventRecord">The event record corresponding to the specified event index.</param>
        /// <exception cref="CommunicationException">Thrown if the error code returned from the call to the PTUDLL32.GetFaultHdr() method is not
        /// CommunicationError.Success.</exception>
        public void GetEventRecord(Log currentEventLog, short eventIndex, out EventRecord eventRecord)
        {
            // Check that the function delegate has been initialized.
            Debug.Assert(m_GetFaultHdr != null, "CommunicationEvent.GetEventRecord() - [m_GetFaultHdr != null]");
            Debug.Assert(m_MutexCommuncationInterface != null, "CommunicationEvent.GetEventRecord() - [m_MutexCommuncationInterface != null]");

            short eventIdentifier, taskIdentifier, streamNumber;
            String time, date;

            CommunicationError errorCode = CommunicationError.UnknownError;
            try
            {
                m_MutexCommuncationInterface.WaitOne(DefaultMutexWaitDurationMs, false);
                errorCode = (CommunicationError)m_GetFaultHdr(eventIndex, out eventIdentifier, out taskIdentifier, out time, out date,
                                                              out streamNumber);
            }
            catch (Exception)
            {
                errorCode = CommunicationError.SystemException;
                throw new CommunicationException("CommunicationEvent.GetEventRecord()", errorCode);
            }
            finally
            {
                m_MutexCommuncationInterface.ReleaseMutex();
            }

            if (DebugMode.Enabled == true)
            {
                DebugMode.GetFaultHdr_t getFaultHdr = new DebugMode.GetFaultHdr_t(eventIndex, eventIdentifier, taskIdentifier, time, date,
                                                                                  streamNumber, errorCode);
                DebugMode.Write(getFaultHdr.ToXML());
            }

            if (errorCode != CommunicationError.Success)
            {
                throw new CommunicationException("CommunicationEvent.GetEventRecord()", errorCode);
            }

            // Get the identifier field from the events table that matches the specified event, task and log identifiers.
            short identifier;
            short logIndex = (short)(currentEventLog.Identifier - 1);
            identifier = Lookup.EventTable.GetIdentifier(logIndex, taskIdentifier, eventIdentifier);

            // Check that the event corresponding to specified LOGID, TASKID and EVENTID was found in the EVENTS table of the data dictionary.
            if (identifier < 0)
            {
                MessageBox.Show(string.Format(Resources.MBTEventNotFound, logIndex, taskIdentifier, eventIdentifier), Resources.MBCaptionError,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                eventRecord = null;
                return;
            }

            // Instantiate new event record based upon this identifier.
            eventRecord = new EventRecord(identifier);

            // Add the record VCU fields.
            eventRecord.LogIdentifier = currentEventLog.Identifier;
            eventRecord.EventIndex = eventIndex;
            eventRecord.Time = time.ToString();
            eventRecord.Date = date.ToString();

            // Convert the date and time retrieved from the VCU to a .NET DateTime object.
            try
            {
                eventRecord.DateTime = DateTime.Parse(date + CommonConstants.Space + time, new CultureInfo(CultureEnglishUS, false));
            }
            catch (FormatException)
            {
                eventRecord.DateTime = Parameter.InvalidDateTime;
            }

            eventRecord.StreamNumber = streamNumber;
            if (streamNumber == CommonConstants.False)
            {
                eventRecord.StreamSaved = false;
            }
            else
            {
                eventRecord.StreamSaved = true;
            }

            // ---------------------------------------------------------
            // Get the event variables associated with the event record.
            // ---------------------------------------------------------

            // Define the data types associated with each event variable aasociated with the selected event.
            short[] types = new short[eventRecord.EventVariableList.Count];
            for (int index = 0; index < eventRecord.EventVariableList.Count; index++)
            {
                types[index] = (short)eventRecord.EventVariableList[index].DataType;
            }

            // -----------------------------------------------------------------------------------------------------
            // Retrieve and store the raw values for each of the event variables associated with the event.
            // -----------------------------------------------------------------------------------------------------
            double[] values;
            GetFaultVar(eventRecord.EventIndex, (short)eventRecord.EventVariableList.Count, types, out values);

            // Store the raw event variable values.
            for (int index = 0; index < eventRecord.EventVariableList.Count; index++)
            {
                eventRecord.EventVariableList[index].ValueFromTarget = values[index];
            }
        }
예제 #10
0
        /// <summary>
        /// Get the fault log/snapshot log data stream corresponding to the specified record.
        /// </summary>
        /// <param name="eventRecord">The event record associated with the data stream that is to be downloaded.</param>
        /// <returns>The data stream corresponding to the specified event record.</returns>
        /// <exception cref="CommunicationException">Thrown if the error code returned from the calls to the PTUDLL32.GetStreamInformation() or PTUDLL32Event.GetStream() 
        /// methods is not CommunicationError.Success.</exception>
        public DataStream_t GetStream(EventRecord eventRecord)
        {
            // Check that the function delegate has been initialized.
            Debug.Assert(m_GetStream != null, "CommunicationEvent.GetStream() - [m_GetStream != null]");
            Debug.Assert(m_MutexCommuncationInterface != null, "CommunicationEvent.GetStream() - [m_MutexCommuncationInterface != null]");

            Debug.Assert(eventRecord.StreamSaved == true, "CommuncationEvent.GetStream() - [eventRecord.StreamSaved == true]");
            Debug.Assert(eventRecord.StreamNumber != CommonConstants.NotUsed,
                         "CommuncationEvent.GetStream() - [eventRecord.StreamNumber != CommonConstants.NotUsed]");

            short watchCount, sampleCount, sampleMultiple;
            short[] watchIdentifiers, dataTypes;

            GetStreamInformation(eventRecord.StreamNumber, out watchCount, out sampleCount, out sampleMultiple, out watchIdentifiers, out dataTypes);

            int[] buffer = new int[sampleCount * watchCount];
            short timeOrigin;

            CommunicationError errorCode = CommunicationError.UnknownError;
            try
            {
                m_MutexCommuncationInterface.WaitOne(DefaultMutexWaitDurationMs, false);

                // TODO - CommunicationEvent.GetStream(). Check on the significance of the timeOrigin parameter in the GetStream() method.
                errorCode = (CommunicationError)m_GetStream(eventRecord.StreamNumber, buffer, out timeOrigin, watchCount, sampleCount, dataTypes);
            }
            catch (Exception)
            {
                errorCode = CommunicationError.SystemException;
                throw new CommunicationException("CommunicationEvent.GetStream()", errorCode);
            }
            finally
            {
                m_MutexCommuncationInterface.ReleaseMutex();
            }

            if (DebugMode.Enabled == true)
            {
                DebugMode.GetStream_t getStream = new DebugMode.GetStream_t(eventRecord.StreamNumber, buffer, timeOrigin, watchCount,
                                                                            sampleCount, dataTypes, errorCode);
                DebugMode.Write(getStream.ToXML());
            }

            if (errorCode != CommunicationError.Success)
            {
                throw new CommunicationException("CommunicationEvent.GetStream()", errorCode);
            }

            Workset_t workset = ConvertToWorkset(eventRecord.Description, watchIdentifiers, sampleMultiple);
            DataStream_t dataStream = new DataStream_t(eventRecord, watchCount, sampleCount, sampleMultiple, workset);

            DateTime startTime = eventRecord.DateTime.Subtract(new TimeSpan(0, 0, 0, 0, dataStream.DurationPreTripMs));

            // Convert the retrieved data stream into a list of individual, time-stamped watch variable data frames.
            List<WatchFrame_t> watchFrameList = ConvertToWatchFrameList(startTime, sampleCount, dataStream.FrameIntervalMs, buffer, dataTypes,
                                                                        workset);

            dataStream.WatchFrameList = watchFrameList;

            // Configure the upper and lower display limits.
            dataStream.ConfigureAutoScale();

            return dataStream;
        }