Exemple #1
0
 //===========================================================================================
 /// <summary>
 /// generates a response based on any errors that occur in one of the Preprocess data methods
 /// </summary>
 /// <param name="errorCode">The error code that was set in the Preprocess data method</param>
 /// <param name="originalResponse">The response before calling the Preprocess data method</param>
 /// <returns>The response</returns>
 //===========================================================================================
 internal virtual string GetPreprocessDataErrorResponse(ErrorCodes errorCode, string originalResponse)
 {
     return originalResponse;
 }
Exemple #2
0
 //==================================================================================================
 /// <summary>
 /// Indicates that there's a pending error that hasn't been thrown yet
 /// and should be by the next AOSCAN messasge or WriteScanData call
 /// </summary>
 /// <param name="errorCode">The pending error code</param>
 //==================================================================================================
 internal void SetPendingOutputScanError(ErrorCodes errorCode)
 {
     PendingOutputScanError = m_driverInterface.ErrorCode;
 }
Exemple #3
0
        public double[,] ReadScanData(int samplesRequested, int timeOut, out ErrorCodes errorCode)
        {
            Monitor.Enter(m_readDataLock);

            int samplesToRead;

            if (PendingInputScanError != ErrorCodes.NoErrors && PendingInputScanError != ErrorCodes.DataOverrun) {
                errorCode = PendingInputScanError;
                PendingInputScanError = ErrorCodes.NoErrors;
                Monitor.Exit(m_readDataLock);
                return null;
            }

            if (samplesRequested == 0) {
                errorCode = ErrorCodes.InputScanReadCountIsZero;
                Monitor.Exit(m_readDataLock);
                return null;
            }

            double[,] userScanData = null;

            int channelCount = m_driverInterface.CriticalParams.AiChannelCount;
            int byteRatio = m_driverInterface.CriticalParams.DataInXferSize;
            int bytesRequested = samplesRequested * byteRatio * channelCount;

            if (bytesRequested > m_driverInterface.InputScanBuffer.Length) {
                errorCode = ErrorCodes.RequestedReadSamplesGreaterThanBufferSize;
                Monitor.Exit(m_readDataLock);
                return null;
            }

            if (m_driverInterface.InputScanStatus == ScanState.Idle || m_driverInterface.InputScanStatus == ScanState.Overrun) {
                int availableSamplesPerChannel = (int)(m_driverInterface.InputScanCount - m_driverInterface.InputSamplesReadPerChannel);
                samplesToRead = Math.Min(availableSamplesPerChannel, samplesRequested);

                if (samplesToRead > 0) {
                    userScanData = new double[channelCount, samplesToRead];

                    // get the current read index
                    int readIndex = m_driverInterface.CurrentInputScanReadIndex;

                    // get a reference to the driver interface's internal read buffer
                    byte[] internalReadBuffer = m_driverInterface.InputScanBuffer;

                    //if (m_driverInterface.InputScanStatus == ScanState.Overrun)
                    //    DebugLogger.WriteLine("Reading {0} samples (Overrun - Thread {1})", samplesToRead, Thread.CurrentThread.ManagedThreadId);
                    //else
                    //    DebugLogger.WriteLine("Reading {0} samples (Stopped - Thread {1})", samplesToRead, Thread.CurrentThread.ManagedThreadId);

                    // copy the data to the inpuScanData array
                    Ai.CopyScanData(internalReadBuffer, userScanData, ref readIndex, samplesToRead);

                    // update the current read index
                    m_driverInterface.CurrentInputScanReadIndex = readIndex;
                }

                errorCode = m_driverInterface.ErrorCode;

                Monitor.Exit(m_readDataLock);

                return userScanData;
            }

            errorCode = m_driverInterface.ErrorCode;

            // first check the driver interface error code
            if (errorCode == ErrorCodes.NoErrors) {
                if (!m_driverInterface.CriticalParams.TriggerRearmEnabled &&
                        m_driverInterface.CriticalParams.InputSampleMode == SampleMode.Finite) {
                    if (samplesRequested > m_driverInterface.CriticalParams.InputScanSamples)
                        errorCode = ErrorCodes.TooManySamplesRequested;

                    if ((ulong)m_driverInterface.CriticalParams.InputScanSamples == m_driverInterface.InputSamplesReadPerChannel) {
                        errorCode = ErrorCodes.NoMoreInputSamplesAvailable;
                    }
                }

                if (errorCode == ErrorCodes.NoErrors) {
                    // wait until there is enough fresh data to read
                    // if the device went idle then samples to read may be less than samples requested
                    samplesToRead = m_driverInterface.WaitForData(samplesRequested, timeOut);

                    // check the error code again in case a data overrun occurred
                    if (m_driverInterface.ErrorCode == ErrorCodes.NoErrors) {
                        if (samplesToRead > 0) {
                            userScanData = new double[channelCount, samplesRequested];

                            // get the current read index
                            int readIndex = m_driverInterface.CurrentInputScanReadIndex;

                            // get a reference to the driver interface's internal read buffer
                            byte[] internalReadBuffer = m_driverInterface.InputScanBuffer;

                            // copy the data to the inpuScanData array
                            Ai.CopyScanData(internalReadBuffer, userScanData, ref readIndex, samplesToRead);

                            // update the current read index
                            m_driverInterface.CurrentInputScanReadIndex = readIndex;
                        } else {
                            errorCode = ErrorCodes.NoMoreInputSamplesAvailable;
                        }
                    } else {
                        errorCode = m_driverInterface.ErrorCode;
                    }

                    if (!m_driverInterface.CriticalParams.TriggerRearmEnabled &&
                            m_driverInterface.CriticalParams.InputSampleMode == SampleMode.Finite) {
                        if ((ulong)m_driverInterface.CriticalParams.InputScanSamples == m_driverInterface.InputScanCount) {
                            m_driverInterface.WaitForIdle();
                        }
                    }
                }
            }

            Monitor.Exit(m_readDataLock);

            return userScanData;
        }
Exemple #4
0
        //==============================================================================
        /// <summary>
        /// Creates an Exception object based on the error code
        /// </summary>
        /// <param name="deviceMessage">The message that was sent to the device</param>
        /// <param name="errorCode">The error that occurred</param>
        /// <returns>The Exception</returns>
        //==============================================================================
        internal DaqException ResolveException(string deviceMessage, ErrorCodes errorCode)
        {
            DaqException daqException;

            string errorMessage = GetErrorMessage(errorCode);

            if (errorCode == ErrorCodes.InvalidMessage)
                errorMessage += String.Format(" [{0}]", deviceMessage);

            daqException = new DaqException(errorMessage, errorCode);

            return daqException;
        }
Exemple #5
0
        //==============================================================================
        /// <summary>
        /// Creates an Exception object based on the error code
        /// </summary>
        /// <param name="errorCode">The error that occurred</param>
        /// <param name="response">The last response</param>
        /// <returns>The Exception</returns>
        //==============================================================================
        internal DaqException ResolveException(ErrorCodes errorCode, DaqResponse response)
        {
            DaqException daqException;

            string errorMessage = GetErrorMessage(errorCode);

            ErrorLevel level;

            if (errorCode < ErrorCodes.DeviceNotResponding)
                level = ErrorLevel.Warning;
            else
                level = ErrorLevel.Error;

            daqException = new DaqException(this, errorMessage, errorCode, level, response);

            return daqException;
        }
Exemple #6
0
        //===========================================================================================
        /// <summary>
        /// Virtual method to preprocess a message
        /// </summary>
        /// <param name="message">The message to process</param>
        /// <returns>True if the message is to be sent to the device, otherwise false</returns>
        //===========================================================================================
        internal virtual bool PreprocessMessage(ref string message, string messageType)
        {
            SendMessageToDevice = true;

            if (message.Contains(Constants.EQUAL_SIGN) && message.Contains(Constants.QUERY.ToString())) {
                m_apiMessageError = ErrorCodes.InvalidMessage;
                SendMessageToDevice = false;
                return SendMessageToDevice;
            }

            // first check if an Ai Cal is in progress by the cal thread id
            // Cal is running if the cal thread id is non-zero
            if (Ai != null && Ai.CalThreadId != 0 && Thread.CurrentThread.ManagedThreadId != Ai.CalThreadId) {
                // if a calibration is running, then respond with device busy and
                // don't send the message to the device
                if (messageType != DaqComponents.AICAL && !message.Contains(DaqProperties.STATUS)) {
                    ApiResponse = new DaqResponse(PropertyValues.DEVICE_BUSY, double.NaN);
                    SendMessageToDevice = false;
                    return SendMessageToDevice;
                }
            }

            // next check if an Ao Cal is in progress by the cal thread id
            // Cal is running if the cal thread id is non-zero
            if (Ao != null && Ao.CalThreadId != 0 && Thread.CurrentThread.ManagedThreadId != Ao.CalThreadId) {
                // if a calibration is running, then respond with device busy and
                // don't send the message to the device
                if (messageType != DaqComponents.AOCAL && !message.Contains(DaqProperties.STATUS)) {
                    ApiResponse = new DaqResponse(PropertyValues.DEVICE_BUSY, double.NaN);
                    SendMessageToDevice = false;
                    return SendMessageToDevice;
                }
            }

            if (messageType == DaqComponents.DEV) {
                if (message.Contains(APIMessages.DEVPID)) {
                    ApiResponse = new DaqResponse(APIMessages.DEVPID.Remove(0, 1) + Constants.EQUAL_SIGN + m_deviceID.ToString(), (double)m_deviceID);
                    SendMessageToDevice = false;
                    return SendMessageToDevice;
                }

                if (message.Contains(DaqCommands.LOADCAPS)) {
                    LoadDeviceCaps(true);

                    if (Ai != null)
                        Ai.Initialize();

                    if (Ao != null)
                        Ao.Initialize();

                    if (Dio != null)
                        Dio.Initialize();

                    if (Ctr != null)
                        Ctr.Initialize();

                    if (Tmr != null)
                        Tmr.Initialize();

                    ApiResponse = new DaqResponse(DaqComponents.DEV + ":" + DaqCommands.LOADCAPS, Double.NaN);

                    SendMessageToDevice = false;

                    return SendMessageToDevice;
                }
            }

            if (messageType == DaqComponents.AI ||
                    messageType == DaqComponents.AISCAN ||
                        messageType == DaqComponents.AITRIG ||
                            messageType == DaqComponents.AICAL ||
                                messageType == DaqComponents.AIQUEUE) {
                if (Ai != null) {
                    m_apiMessageError = Ai.PreprocessMessage(ref message, messageType);

                    if (m_apiMessageError == ErrorCodes.NoErrors)
                        Ai.SetCriticalParams(message, messageType);

                    return SendMessageToDevice;
                }
            }

            if (messageType == DaqComponents.AO || messageType == DaqComponents.AOSCAN || messageType == DaqComponents.AOCAL) {
                if (Ao != null) {
                    m_apiMessageError = Ao.PreprocessMessage(ref message, messageType);

                    if (m_apiMessageError == ErrorCodes.NoErrors)
                        Ao.SetCriticalParams(message, messageType);

                    return SendMessageToDevice;
                }
            }

            if (messageType == DaqComponents.DIO) {
                if (Dio != null) {
                    m_apiMessageError = Dio.PreprocessMessage(ref message, messageType);

                    return SendMessageToDevice;
                }
            }

            if (messageType == DaqComponents.CTR) {
                if (Ctr != null) {
                    m_apiMessageError = Ctr.PreprocessMessage(ref message, messageType);

                    return SendMessageToDevice;
                }
            }

            if (messageType == DaqComponents.TMR) {
                if (Tmr != null) {
                    m_apiMessageError = Tmr.PreprocessMessage(ref message, messageType);

                    return SendMessageToDevice;
                }
            }

            return true;
        }
Exemple #7
0
		public void GenerateResFile(ArrayList files, string sTxtDir,
			string sResDir, ErrorCodes errorCodeIn, string callingRoutine)
		{
			ErrorCodes errorCode = errorCodeIn;
			LogFile.AddVerboseLine("*** Called GenerateResFile from " + callingRoutine);
			while (true)
			{
				try
				{
					// release any locked files first
					Icu.Cleanup();

					// Call icu\tools\genrb.exe to compile res_index.txt, root.txt and XXX.txt
					Process prc;
					prc= new Process();
					// genrb fails with quoted -i and -s arguments when the directory ends with backslash.
					string sIcuResDir = m_icuBase + m_IcuData;
					if (sIcuResDir.LastIndexOf("\\") == sIcuResDir.Length - 1)
						sIcuResDir = sIcuResDir.Substring(0, sIcuResDir.Length - 1);
					if (sTxtDir.LastIndexOf("\\") == sTxtDir.Length - 1)
						sTxtDir = sTxtDir.Substring(0, sTxtDir.Length - 1);
					if (sResDir.LastIndexOf("\\") == sResDir.Length - 1)
						sResDir = sResDir.Substring(0, sResDir.Length - 1);
					prc.StartInfo.FileName = m_icuBase + "tools\\genrb.exe ";
					// Arguments need directories surrounded in double quotes to cover spaces in path.
					StringBuilder bldr = new StringBuilder();
					bldr.AppendFormat("-v -k -d \"{0}\" -i \"{1}\" ", sResDir, sIcuResDir);
					bldr.AppendFormat("-s \"{0}\"", sTxtDir);

					foreach (string FileName in files)
						bldr.AppendFormat(" {0}", FileName.Substring(1 + FileName.LastIndexOf("\\")));

					prc.StartInfo.Arguments = bldr.ToString();
					prc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
					prc.StartInfo.WorkingDirectory = sTxtDir;
					LogFile.AddLine(" GenerateResFile: <" + prc.StartInfo.Arguments + ">");

					prc.Start();
					prc.WaitForExit();
					int ret;
					ret = prc.ExitCode;
					if (ret != 0)
					{
						// This should never happen anymore because we are generating the res files in
						// the Icu34 directory then moving them to Icu34\icudt34l where the files may be locked.
						// Now we are testing for locked files before we do any other file manipulation.
						if (ret == 4 && RunSilent == false)
						{
							LogFile.AddLine(" File Access Error: asking user to retry or Cancel.");

							// arguments to the MessageBox to ask user to retry or cancel
							string message = InstallLanguageStrings.ksStopAllFwApps;
							string caption = InstallLanguageStrings.ksInstallLanguageMsgCaption;
							MessageBoxButtons buttons = MessageBoxButtons.RetryCancel;
							MessageBoxIcon icon = MessageBoxIcon.Exclamation;
							MessageBoxDefaultButton defButton = MessageBoxDefaultButton.Button1;

							DialogResult result = MessageBox.Show(message, caption, buttons, icon, defButton);
							if(result == DialogResult.Retry)
								continue;	// repeat
							errorCode = ErrorCodes.CancelAccessFailure;
						}

						System.Console.WriteLine("GENRB returned error code " + ret.ToString());
						System.Console.WriteLine(Error.Text(errorCode));
						LogFile.AddErrorLine("GENRB returned error code " + ret.ToString());
						foreach(string FileName in files)
							System.Console.WriteLine(" " + FileName);
						throw new LDExceptions(errorCode);
					}
					break;
				}
				catch(Exception e)
				{
					System.Diagnostics.Debug.WriteLine(e.Message);
					throw new LDExceptions(errorCode, e.Message);
				}
			}
		}
Exemple #8
0
		/// <summary>
		/// Build an output file using the specified input file taking the action
		/// required to replace the specified line, or insert the text before the
		/// specified line.
		/// </summary>
		/// <param name="inputFilespec">The file we are reading from.</param>
		/// <param name="outputFilespec">The file we are modifying.</param>
		/// <param name="lineNumber">Line from the input file that we want to modify</param>
		/// <param name="newLineText">Text to replace or insert.</param>
		/// <param name="action">Currently only supports replace OR insert.</param>
		/// <param name="errorCode">Error to throw if it fails.</param>
		/// <returns>True if the action was performed on the file.</returns>
		public bool ModifyFile(string inputFilespec, string outputFilespec, int lineNumber,
			string newLineText,	eAction action, ErrorCodes errorCode)
		{
			bool rval = false;

			if ((action != eAction.insert) && (action != eAction.replace))
				return rval;

			if ((inputFilespec.Length <= 0) || (lineNumber < 0))
				return rval;

			try
			{
				Generic.DeleteFile(outputFilespec);
			}
			catch
			{
				string emsg = "Error while deleting file: " + outputFilespec;
				LogFile.AddErrorLine(emsg);
				throw new LDExceptions(ErrorCodes.FileWrite, emsg);
			}

			LogFile.AddVerboseLine("StreamReader on <" + inputFilespec + ">");
			StreamReader inputStream = new StreamReader(inputFilespec,
				System.Text.Encoding.Default, true);	// Check for Unicode BOM chars.
			int chT = inputStream.Peek();	// force autodetection of encoding.
			StreamWriter outputStream = null;
			try
			{
				outputStream = new StreamWriter(outputFilespec, false,
					inputStream.CurrentEncoding);
			}
			catch
			{
				throw new LDExceptions(errorCode);
			}

			string newLine;
			int lineCount = 0;
			while (inputStream.Peek() >= 0)
			{
				lineCount++;
				newLine = inputStream.ReadLine();
				if (lineCount == lineNumber)	// at the line in question
				{
					if (action == eAction.replace &&
						newLineText.Length > 0)
						outputStream.WriteLine(newLineText);	// write out the new line

					rval = true;
					if (action == eAction.insert)			// if eAction.insert
					{
						outputStream.WriteLine(newLineText);	// write out the new line
						outputStream.WriteLine(newLine);	// write out the line just read
					}
				}
				else
					outputStream.WriteLine(newLine);	// write out the line just read
			}
			inputStream.Close();
			outputStream.Close();
			return rval;
		}