Пример #1
0
        private void AnalogCallback(IAsyncResult ar)
        {
            try
            {
                if (runningTask != null && runningTask == ar.AsyncState && timer1.Enabled)
                {
                    data = Reader.EndReadWaveform(ar);

                    dataRead(data);

                    Reader.BeginMemoryOptimizedReadWaveform(samples, Callback, myTask, data);
                }
                if (!timer1.Enabled)
                {
                    BTN_Reset.Enabled = true;
                    BTN_Open.Enabled  = true;
                    BTN_Data.Enabled  = true;
                    runningTask       = null;
                    myTask.Dispose();
                }
            }
            catch (DaqException de)
            {
                MessageBox.Show(de.Message);
                runningTask = null;
                myTask.Dispose();
                BTN_Reset.Enabled = false;
                BTN_Start.Enabled = true;
            }
        }
Пример #2
0
        /// <summary>
        /// 停止任务,回到idle状态
        /// </summary>
        /// <returns></returns>
        public bool TryStopTask()
        {
            if (aiTask != null)
            {
                try
                {
                    aiTask.Stop();

                    //之前没有,发布停事件
                    //OnAITaskStopped();
                }
                catch (Exception ex)
                {
                    //目前啥也不用做
                }
                Thread.Sleep(1000);
                if (aiTask != null)
                {
                    aiTask.Dispose();
                }
                aiTask  = null;
                AIState = Status.Idle;
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #3
0
 public void StopMeasurement()
 {
     if (runningTask != null)
     {
         // Dispose of the task
         runningTask = null;
         myTask.Dispose();
     }
 }
Пример #4
0
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            Mouse.OverrideCursor = Cursors.Wait;
            try
            {
                // create the task and channel
                myTask.AOChannels.CreateVoltageChannel(physicalChannelComboBox.Text,
                                                       "",
                                                       Convert.ToDouble(minimumTextBox.Text),
                                                       Convert.ToDouble(maximumTextBox.Text),
                                                       ni.AOVoltageUnits.Volts);

                // verify the task before doing the waveform calculations
                myTask.Control(ni.TaskAction.Verify);

                // calculate some waveform parameters and generate data
                FunctionGenerator fGen = new FunctionGenerator(
                    myTask.Timing,
                    edfrequency.Text,
                    edsamplesPerBuffer.Text,
                    edcyclesPerBuffer.Text,
                    signalTypeComboBox.Text,
                    edamplitude.Text);

                // configure the sample clock with the calculated rate
                myTask.Timing.ConfigureSampleClock("",
                                                   fGen.ResultingSampleClockRate,
                                                   ni.SampleClockActiveEdge.Rising,
                                                   ni.SampleQuantityMode.ContinuousSamples, 1000);


                ni.AnalogSingleChannelWriter writer =
                    new ni.AnalogSingleChannelWriter(myTask.Stream);

                //write data to buffer
                writer.WriteMultiSample(false, fGen.Data);

                profilechart.SetData(fGen.Data);

                //start writing out data
                myTask.Start();

                btnStart.IsEnabled = false;
                btnStop.IsEnabled  = true;


                timer.IsEnabled = true;
            }
            catch (ni.DaqException err)
            {
                timer.IsEnabled = false;
                MessageBox.Show(err.Message);
                myTask.Dispose();
            }
            Mouse.OverrideCursor = Cursors.Arrow;
        }
 private void exitToolStripMenuItem_Click(object sender, EventArgs e)
 {
     serialPort1.Close();
     backgroundWorker1.CancelAsync();
     running_task = null;
     if (mytask != null)
     {
         mytask.Dispose();
     }
     Application.Exit();
 }
Пример #6
0
        public static string GenerateWave(string sourceDevice = "Dev1", double freq = 100, double amp = 2,
                                          string waveType     = "sine")
        {
            waveType = waveType.ToLower();
            AOFunctionGenerationType type = AOFunctionGenerationType.Sine;  //default value

            if (waveType.Equals("square"))
            {
                type = AOFunctionGenerationType.Square;
            }
            else if (waveType.Equals("triangle"))
            {
                type = AOFunctionGenerationType.Triangle;
            }
            NationalInstruments.DAQmx.Task myTask = new NationalInstruments.DAQmx.Task();
            try
            {
                if (amp < 0)
                {
                    amp *= -1;
                }
                if (amp > 5)
                {
                    amp = 5;
                }
                myTask.AOChannels.CreateFunctionGenerationChannel(sourceDevice + "/fgen",
                                                                  "fgen",
                                                                  type,
                                                                  freq,        //freq
                                                                  amp);        //amplitude

                // verify the task before doing the waveform calculations
                myTask.Control(TaskAction.Verify);


                myTask.Stop();
                myTask.AOChannels[0].FunctionGenerationType      = type;
                myTask.AOChannels[0].FunctionGenerationFrequency = freq;
                myTask.AOChannels[0].FunctionGenerationAmplitude = amp;


                myTask.Start();
            }
            catch (DaqException err)
            {
                myTask.Dispose();
                return("Fail" + err.Message);
            }
            myTask.Dispose();
            return("OK");
        }
Пример #7
0
        public bool Analog_Connect(string DAQName, string channel)
        {
            IsConnect = false;

            try
            {
                IsDataGetCom  = false;
                IsDataReadEnd = false;

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

                task = new NationalInstruments.DAQmx.Task();

                task.AIChannels.CreateVoltageChannel(DAQName + "/" + channel, "", AITerminalConfiguration.Rse,
                                                     0, 5.0, AIVoltageUnits.Volts);

                Reader = new AnalogMultiChannelReader(task.Stream);

                //task.Timing.ConfigureSampleClock("", SampleRate, SampleClockActiveEdge.Rising,
                //SampleQuantityMode.FiniteSamples, iChPerSampleNum);

                task.Control(TaskAction.Verify);

                IsConnect = true;
                return(IsConnect);
            }
            catch (DaqException Exception)
            {
                if (task != null)
                {
                    task.Dispose();
                    task = null;
                    MessageBox.Show(Exception.Message);
                }
                return(IsConnect);
            }
            catch (Exception ex)
            {
                if (task != null)
                {
                    task.Dispose();
                    task = null;
                }
                return(IsConnect);
            }
        }
Пример #8
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Start.IsEnabled = false;
            ni.Task myTask = new ni.Task();
            try
            {
                // Create a new task


                // Initialize local variables
                double sampleRate        = Convert.ToDouble(edRate.Text);
                double rangeMinimum      = Convert.ToDouble(edMin.Text);
                double rangeMaximum      = Convert.ToDouble(edMax.Text);
                int    samplesPerChannel = Convert.ToInt32(edchannel.Text);

                // Create a channel
                myTask.AIChannels.CreateVoltageChannel(physicalChannelComboBox.Text, "",
                                                       (ni.AITerminalConfiguration)(-1), rangeMinimum, rangeMaximum, ni.AIVoltageUnits.Volts);

                // Configure timing specs
                myTask.Timing.ConfigureSampleClock("", sampleRate, ni.SampleClockActiveEdge.Rising,
                                                   ni.SampleQuantityMode.FiniteSamples, samplesPerChannel);

                // Verify the task
                myTask.Control(ni.TaskAction.Verify);

                // Prepare the table for data
                InitializeDataTable(myTask.AIChannels, ref dataTable);
                //acquisitionDataGrid.DataContext = dataTable.DefaultView;
                //acquisitionDataGrid.ItemsSource = dataTable.DefaultView;

                // Read the data
                reader = new ni.AnalogMultiChannelReader(myTask.Stream);

                data = reader.ReadWaveform(samplesPerChannel);

                dataToDataTable(data, ref dataTable);

                myTask.Dispose();
            }
            catch (ni.DaqException exception)
            {
                MessageBox.Show(exception.Message);
            }
            finally
            {
                myTask.Dispose();
                Start.IsEnabled = true;
            }
        }
Пример #9
0
 public void measureDAQ()
 {
     try
     {
         Console.WriteLine("measureDAQ() called..");
         data = reader.ReadWaveform(samplesPerChannel);
         dataToDataTable(data, ref dataTable);
     }
     catch (DaqException exception)
     {
         // Display Errors
         Console.WriteLine(exception.Message);
         runningTask = null;
         myTask.Dispose();
     }
 }
Пример #10
0
        ///Reads the tcontrol volatege from the DAQ
        public static double ReadControl()
        {
            double analogData      = 0;
            var    temperatureTask = new NationalInstruments.DAQmx.Task();

            try
            {
                temperatureTask.AIChannels.CreateVoltageChannel(deviceName + "/ai1", "Volt", AITerminalConfiguration.Rse, 0, 5, AIVoltageUnits.Volts);
                var reader = new AnalogSingleChannelReader(temperatureTask.Stream);
                analogData = reader.ReadSingleSample();
                if ((analogData < -0.5) || (analogData > 5.5))
                {
                    throw new Exception("Data from temperatureTask outside boundries");
                }
            }
            catch (Exception e)
            {
                analogData = 999; //999 is an error code
            }
            finally
            {
                temperatureTask.Dispose();
            }
            return(analogData);
        }
Пример #11
0
        public void startTempReading(tempCallback itcb)
        {
            try
            {
                tcb    = itcb;
                myTask = new NationalInstruments.DAQmx.Task();
                AIChannel          channel1;
                AIChannel          channel2;
                AIThermocoupleType thermocoupleType;



                thermocoupleType = AIThermocoupleType.K;
                string[] channellist = DaqSystem.Local.GetPhysicalChannels(PhysicalChannelTypes.AI, PhysicalChannelAccess.External);

                channel1 = myTask.AIChannels.CreateThermocoupleChannel(channellist[1], "", 0, 1000, thermocoupleType, AITemperatureUnits.DegreesC);
                channel2 = myTask.AIChannels.CreateThermocoupleChannel(channellist[3], "", 0, 1000, thermocoupleType, AITemperatureUnits.DegreesC);
                channel1.AutoZeroMode = AIAutoZeroMode.Once;
                channel2.AutoZeroMode = AIAutoZeroMode.Once;

                /* if (scxiModuleCheckBox.Checked)
                 * {
                 *   switch (autoZeroModeComboBox.SelectedIndex)
                 *   {
                 *       case 0:
                 *           autoZeroMode = AIAutoZeroMode.None;
                 *           break;
                 *       case 1:
                 *       default:
                 *           autoZeroMode = AIAutoZeroMode.Once;
                 *           break;
                 *   }
                 *   myChannel.AutoZeroMode = autoZeroMode;
                 * }*/

                myTask.Timing.ConfigureSampleClock("", 4,
                                                   SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 1000);

                myTask.Control(TaskAction.Verify);

                analogInReader = new AnalogMultiChannelReader(myTask.Stream);

                runningTask = myTask;
                //InitializeDataTable(myTask.AIChannels, ref dataTable);
                //acquisitionDataGrid.DataSource = dataTable;

                // Use SynchronizeCallbacks to specify that the object
                // marshals callbacks across threads appropriately.
                analogInReader.SynchronizeCallbacks = true;
                analogInReader.BeginReadWaveform(10, myAsyncCallback, myTask);
            }
            catch (DaqException exception)
            {
                //MessageBox.Show(exception.Message);
                myTask.Dispose();
                runningTask = null;
            }
        }
Пример #12
0
        void StopTask()
        {
            try
            {
                runningTask = null;

                inputTask.Stop();
                outputTask.Stop();

                inputTask.Dispose();
                outputTask.Dispose();
            }
            catch (Exception ex)
            {
                WarningDAQUpdate?.Invoke(ex.Message);
            }
            //Dispose();
        }
Пример #13
0
 public void Stop()
 {
     this.IsInitialized = false;
     if (_daqTask != null)
     {
         _daqTask.Stop();
         _daqTask.Dispose();
     }
 }
Пример #14
0
        /// <summary>
        /// Indlæser en serie af samples fra NI-DAQ i volt
        /// </summary>
        /// <param name="samples">Antal ønsket datapunkter</param>
        /// <returns>Returnerer en liste af datapunkter</returns>
        public List <double> ReadInput(int samples)
        {
            indstilDAQ();

            var seqList = new List <double>(reader.ReadMultiSample(samples));

            analogInTask.Dispose();

            return(seqList);
        }
 protected virtual void Dispose(bool disposing)
 {
     if (!disposed)
     {
         if (disposing)
         {
             readTask.Dispose();
         }
         disposed = true;
     }
 }
Пример #16
0
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            // This example uses the default source (or gate) terminal for
            // the counter of your device.  To determine what the default
            // counter pins for your device are or to set a different source
            // (or gate) pin, refer to the Connecting Counter Signals topic
            // in the NI-DAQmx Help (search for "Connecting Counter Signals").

            try
            {
                myTask.COChannels.CreatePulseChannelFrequency(counterComboBox.Text,
                                                              "ContinuousPulseTrain", ni.COPulseFrequencyUnits.Hertz, idleState, 0.0,
                                                              Convert.ToDouble(frequencyTextBox.Text),
                                                              Convert.ToDouble(dutyCycleTextBox.Text));

                myTask.Timing.ConfigureImplicit(ni.SampleQuantityMode.ContinuousSamples, 1000);

                myTask.Start();

                btnStart.IsEnabled = false;
                btnStop.IsEnabled  = true;

                timer.IsEnabled = true;
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                myTask.Dispose();
                btnStart.IsEnabled = true;
                btnStop.IsEnabled  = false;
                timer.IsEnabled    = false;
            }
        }
Пример #17
0
 /// <summary>
 /// 停止任务,回到idle状态
 /// </summary>
 /// <returns></returns>
 public bool TryStopTask()
 {
     if (aiTask != null)
     {
         try
         {
             aiTask.Stop();
         }
         catch (Exception ex)
         {
             //目前啥也不用做
         }
         aiTask.Dispose();
         aiTask  = null;
         AIState = Status.Idle;
         return(true);
     }
     else
     {
         return(false);
     }
 }
Пример #18
0
        public void StopDAQ()
        {
            // Dispose of the task
            SW_RMSData.Dispose();
            SW_State.Dispose();


            runningTask = null;
            myTask.Dispose();

            indexP = 0;
            iii    = 0;
        }
Пример #19
0
        private void AnalogInCallback(IAsyncResult ar)
        {
            string DAQinputrange   = InputrangecomboBox.Text;
            string DAQaisignaltype = ConnecttypecomboBox.Text;

            convertClkRate = int.Parse(SamplingTextbox.Text);
            sectionLength  = int.Parse(DataLengthtextBox.Text);
            startChannel   = int.Parse(ChanneltextBox.Text);

            try
            {
                double[] sensordata = new double[sectionLength];
                if (runningTask != null && runningTask == ar.AsyncState)
                {
                    // Read the available data from the channels
                    data = analogInReader.EndReadWaveform(ar);
                    for (int i = 0; i < data[0].Samples.Count; i++)
                    {
                        sensordata[i] = data[0].Samples[i].Value;
                    }
                    // Plot your data her
                    sensordata = SF.Bandpassfilter(sensordata, convertClkRate, lowcutoff, highcutoff);
                    DoChart1update(sensordata);
                    DoChart2update(sensordata);
                    DoChart3update(sensordata);

                    //read data from data buffer
                    analogInReader.BeginMemoryOptimizedReadWaveform(sectionLength,
                                                                    analogCallback, myTask, data);
                }
            }
            catch (NationalInstruments.DAQmx.DaqException exception)
            {
                // Display Errors
                MessageBox.Show(exception.Message);
                runningTask = null;
                myTask.Dispose();
            }
        }
 protected virtual void Dispose(bool disposing)
 {
     if (!disposed)
     {
         if (disposing)
         {
             writer.WriteSingleSample(true, 0.0);
             writeTask.Dispose();
             sensor.Dispose();
         }
         disposed = true;
     }
 }
Пример #21
0
        private void BTN_Start_Click(object sender, EventArgs e)
        {
            if (runningTask == null)
            {
                try
                {
                    BTN_Reset.Enabled = false;
                    BTN_Start.Enabled = false;
                    BTN_Open.Enabled  = false;
                    BTN_Data.Enabled  = false;
                    timer1.Interval   = (Convert.ToInt32(Text_Time.Text) + 1) * 1000;
                    timer1.Enabled    = true;

                    fs = File.Open(@"C:\Users\gy157\Documents\data.bin", FileMode.Create);
                    wr = new BinaryWriter(fs);

                    if (chart1.Series.Count > 0)
                    {
                        chart1.Series[0].Points.Clear();
                    }
                    chart1.Series.Add("chart1");
                    chart1.Series["chart1"].ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
                    chart1.Series["chart1"].IsVisibleInLegend = false;

                    myTask = new NationalInstruments.DAQmx.Task();

                    samples = Convert.ToInt32(UpDown_Samples.Value);
                    freq    = Convert.ToDouble(UpDown_Freq.Value);
                    myTask.AIChannels.CreateVoltageChannel("Dev1/ai3", "", (AITerminalConfiguration)(-1), -10, 10, AIVoltageUnits.Volts);
                    myTask.Timing.ConfigureSampleClock("", freq, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, samples);
                    myTask.Control(TaskAction.Verify);

                    runningTask = myTask;
                    Reader      = new AnalogMultiChannelReader(myTask.Stream);
                    Callback    = new AsyncCallback(AnalogCallback);

                    Reader.SynchronizeCallbacks = true;
                    Reader.BeginReadWaveform(samples, Callback, myTask);
                }
                catch (DaqException de)
                {
                    MessageBox.Show(de.Message);
                    runningTask = null;
                    myTask.Dispose();
                    BTN_Reset.Enabled = false;
                    BTN_Start.Enabled = true;
                }
            }
        }
Пример #22
0
        public static void Dispose()
        {
            if (motorControlChannel == null)
            {
                return;
            }

            motorControlChannel.Dispose();
            motorLoadChannel.Dispose();
            motorRotationsChannel.Dispose();
            motorControlTask.Dispose();
            motorLoadTask.Dispose();
            motorRotationsTask.Dispose();

            disposed = true;
        }
Пример #23
0
        /// <summary>
        /// 停止任务,回到idle状态
        /// </summary>
        /// <returns></returns>
        public bool StopTask()
        {
            if (aiTask != null)
            {
                aiTask.Stop();
                aiTask.Dispose();
                aiTask = null;

                AIState = Status.Idle;
                OnStatusChanged();

                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #24
0
        public void StopDAQ()
        {
            // Dispose of the task
            if (savedata_checkBox.Checked == true)
            {
                SW_RMSData.Dispose();
                SW_RawData.Dispose();
                SW_entropy.Dispose();
            }


            runningTask = null;
            myTask.Dispose();
            maxrms[0] = 0;
            plotrms   = new double[plotrms.Length];
            MSE       = new double[MSE.Length];
            indexP    = 0;
            indexplot = 0;
        }
Пример #25
0
        public void GenerateWave(string device = "Dev1", double freq = 100, double amp = 2,
                                 AOFunctionGenerationType type = AOFunctionGenerationType.Sine)
        {
            try
            {
                if (myTask == null)
                {
                    myTask = new NationalInstruments.DAQmx.Task();
                    if (amp < 0)
                    {
                        amp *= -1;
                    }
                    if (amp > 5)
                    {
                        amp = 5;
                    }
                    myTask.AOChannels.CreateFunctionGenerationChannel(device + "/fgen",
                                                                      "fgen",
                                                                      type,
                                                                      freq,    //freq
                                                                      amp);    //amplitude

                    // verify the task before doing the waveform calculations
                    myTask.Control(TaskAction.Verify);
                }
                else
                {
                    myTask.Stop();
                    myTask.AOChannels[0].FunctionGenerationType      = type;
                    myTask.AOChannels[0].FunctionGenerationFrequency = freq;
                    myTask.AOChannels[0].FunctionGenerationAmplitude = amp;
                }

                myTask.Start();
            }
            catch (DaqException err)
            {
                MessageBox.Show(err.Message);
                myTask.Dispose();
                myTask = null;
            }
        }
Пример #26
0
 public void AnalogInCallback(IAsyncResult ar)
 {
     try
     {
         if (runningTask != null && runningTask == ar.AsyncState)
         {
             data = analogInReader.EndReadWaveform(ar);
             dataRecord(data, ref dataTable);
             tcb(datatoShow());
             //analogInReader.BeginMemoryOptimizedReadWaveform(10, myAsyncCallback, myTask, data);
             analogInReader.BeginMemoryOptimizedReadWaveform(1, myAsyncCallback, myTask, data);
         }
     }
     catch (DaqException exception)
     {
         MessageBox.Show(exception.Message);
         myTask.Dispose();
         runningTask = null;
     }
 }
Пример #27
0
 public void Digital_Write(int index, bool value)
 {
     LED[index] = value;
     if (Writer != null)
     {
         try
         {
             Writer.WriteSingleSampleMultiLine(true, LED);
         }
         catch (DaqException de)
         {
             if (Writetask != null)
             {
                 Writetask.Dispose();
                 Writetask = null;
             }
             IsConnect = false;
             //return IsConnect;
         }
     }
 }
Пример #28
0
 //포트0 열결 해제
 public void Disconnect_port0()
 {
     if (Writetask != null)
     {
         Writetask.Dispose();
         Writetask = null;
         if (writer != null)
         {
             writer = null;
         }
     }
     if (Readtask != null)
     {
         Readtask.Dispose();
         Readtask = null;
         if (reader != null)
         {
             reader = null;
         }
     }
 }
Пример #29
0
        //Writes the outputsignal to port ao0
        public static void WriteOutput(double signal)
        {
            double analogData;
            var    signalTask = new NationalInstruments.DAQmx.Task();

            try
            {
                analogData = signal;
                signalTask.AOChannels.CreateVoltageChannel(deviceName + "/ao0", "Signal", 0, 5, AOVoltageUnits.Volts);
                var writer = new AnalogSingleChannelWriter(signalTask.Stream);
                writer.WriteSingleSample(true, analogData);
            }
            catch (Exception e)
            {
                lastException = Convert.ToString(e);
            }
            finally
            {
                signalTask.Dispose();
            }
        }
Пример #30
0
        public void InitiateAsyncDaq(bool QueueMode)
        {
            _queueMode = QueueMode;
            if (runningTask == null)
            {
                try
                {
                    // Create a new task
                    myTask = new NationalInstruments.DAQmx.Task();

                    // Create a virtual channel
                    myTask.AIChannels.CreateVoltageChannel(_daqSettingsDTO.physicalChannelName_, "",
                                                           (AITerminalConfiguration)(-1), _daqSettingsDTO.MinValueVolt_, _daqSettingsDTO.MaxValueVolt, AIVoltageUnits.Volts);

                    // Configure the timing parameters
                    myTask.Timing.ConfigureSampleClock("", _daqSettingsDTO.SampleRate,                                                                         // 1000 = frekvensen der læses med i hz
                                                       SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, _daqSettingsDTO.SamplesPerChannel); // 100 = antal samples per læsning

                    // Verify the Task
                    myTask.Control(TaskAction.Verify);

                    runningTask    = myTask;
                    analogInReader = new AnalogMultiChannelReader(myTask.Stream);
                    analogCallback = new AsyncCallback(AnalogInCallback);

                    // Use SynchronizeCallbacks to specify that the object
                    // marshals callbacks across threads appropriately.
                    analogInReader.SynchronizeCallbacks = true;
                    analogInReader.BeginReadWaveform(_daqSettingsDTO.SamplesPerChannel,
                                                     analogCallback, myTask);
                }
                catch (DaqException exception)
                {
                    // Display Errors
                    runningTask = null;
                    myTask.Dispose();
                }
            }
        }
Пример #31
0
        private void runMainPerformance2()
        {
            if (runningTask == null)
            {
                try
                {
                    duration = Properties.Settings.Default.jobDuration * 1000;
                    countRows = 0;
                    fault_count = 0;
                    fault_stitch = "";
                    iswelding = false;
                    current_stitch = 0;
                    samplingVariable = Convert.ToInt32(1 / ((Properties.Settings.Default.samplesPerChannelNumeric * 100) / Properties.Settings.Default.rateNumeric));

                    //this.label3.Content = Convert.ToString(Properties.Settings.Default.jobNum - 1);
                    //this.label5.Content = Convert.ToString(fault_num);

                    dataTable = new DataTable();

                    // Create a new task
                    myTask = new NationalInstruments.DAQmx.Task();

                    // Create a virtual channel
                    myTask.AIChannels.CreateVoltageChannel(Properties.Settings.Default.physicalChannel, "",
                        (AITerminalConfiguration)(-1), Convert.ToDouble(Properties.Settings.Default.minVoltage),
                        Convert.ToDouble(Properties.Settings.Default.maxVoltage), AIVoltageUnits.Volts);

                    // Configure the timing parameters
                    myTask.Timing.ConfigureSampleClock("", Properties.Settings.Default.rateNumeric,
                        SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 100000);

                    // Verify the Task
                    myTask.Control(TaskAction.Verify);

                    // Prepare the table for Data
                    InitializeDataTable(myTask.AIChannels, ref dataTable);

                    runningTask = myTask;
                    analogInReader = new AnalogMultiChannelReader(myTask.Stream);
                    analogCallback = new AsyncCallback(AnalogInCallback2);

                    // Use SynchronizeCallbacks to specify that the object 
                    // marshals callbacks across threads appropriately.
                    analogInReader.SynchronizeCallbacks = true;
                    analogInReader.BeginReadWaveform(Convert.ToInt32(Properties.Settings.Default.samplesPerChannelNumeric),
                        analogCallback, myTask);
                }
                catch (DaqException exception)
                {
                    // Display Errors
                    MessageBox.Show(exception.Message, "기기 연결을 확인해주세요");
                    runningTask = null;
                    myTask.Dispose();
                }
            }
        }
Пример #32
0
        private void firstMainPerformance(bool isref)
        {
            this.label_projectName.Content = Properties.Settings.Default.projectName;
            if (runningTask == null)
            {
                if (isref == true)
                {
                    jobNumGrid.ColumnDefinitions[1].Width = new GridLength(1, GridUnitType.Star);
                    jobNumGrid.ColumnDefinitions[0].Width = new GridLength(1, GridUnitType.Star);
                    try
                    {
                        Properties.Settings.Default.jobNum = 1;
                        duration = Properties.Settings.Default.jobDuration * 1000;
                        try
                        {
                            string conStr = "Server=localhost;Database=" + Properties.Settings.Default.databaseName + ";Uid=" + Properties.Settings.Default.databaseID + ";Pwd=" + Properties.Settings.Default.databasePwd;
                            MySqlConnection con = new MySqlConnection(conStr);

                            MySqlCommand comm = con.CreateCommand();
                            MySqlDataReader Reader;
                            con.Open();
                            comm.CommandText = "SELECT MAX(Measure_index) FROM `" + Properties.Settings.Default.databaseName + "`.`measured_data`";
                            Reader = comm.ExecuteReader();
                            Reader.Read();
                            measure_index = Convert.ToInt32(Reader[0]) + 1;
                            con.Close();

                        }
                        catch (Exception exc)
                        {
                            measure_index = 0;
                        }

                        try
                        {
                            string conStr = "Server=localhost;Database=" + Properties.Settings.Default.databaseName + ";Uid=" + Properties.Settings.Default.databaseID + ";Pwd=" + Properties.Settings.Default.databasePwd;
                            MySqlConnection con = new MySqlConnection(conStr);

                            MySqlCommand comm = con.CreateCommand();
                            MySqlDataReader Reader;

                            con.Open();
                            comm.CommandText = "SELECT COUNT(*) FROM `" + Properties.Settings.Default.databaseName + "`.`measured_data`";
                            Reader = comm.ExecuteReader();
                            Reader.Read();
                            measured_id = Convert.ToInt32(Reader[0]) + 1;
                            con.Close();
                        }
                        catch (Exception exc)
                        {
                            measured_id = 0;
                        }

                        try
                        {
                            string conStr = "Server=localhost;Database=" + Properties.Settings.Default.databaseName + ";Uid=" + Properties.Settings.Default.databaseID + ";Pwd=" + Properties.Settings.Default.databasePwd;
                            MySqlConnection con = new MySqlConnection(conStr);

                            MySqlCommand comm = con.CreateCommand();
                            MySqlDataReader Reader;

                            con.Open();
                            comm.CommandText = "SELECT COUNT(*) FROM `" + Properties.Settings.Default.databaseName + "`.`test_reference` WHERE Reference_id=" + Properties.Settings.Default.reference_id;
                            Reader = comm.ExecuteReader();
                            Reader.Read();
                            numOfdata = Convert.ToInt32(Reader[0]);
                            con.Close();

                            con.Open();

                            string commtext = "SELECT * FROM `" + Properties.Settings.Default.databaseName + "`.`test_reference` WHERE Reference_id=" + Properties.Settings.Default.reference_id;
                            MySqlDataAdapter mda = new MySqlDataAdapter(commtext, con);

                            DataSet ds = new DataSet();

                            mda.Fill(ds);
                            refDataTable = ds.Tables[0];
                            con.Close();
                        }
                        catch (Exception exc)
                        {

                        }

                        int txtFilePathIndex = Properties.Settings.Default.textFilePathSetting.LastIndexOf("\\");
                        string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + "SF LWM\\" + Properties.Settings.Default.projectName + "\\" + DateTime.Now.ToString("yyyy MM dd") + "_" + DateTime.Now.ToString("HH mm ss");
                        Properties.Settings.Default.txtFilePath = path;
                        DirectoryInfo f = new DirectoryInfo(path);
                        if (f.Exists == false)
                            f.Create();

                        countRows = 0;
                        fault_count = 0;
                        fault_stitch = "";
                        iswelding = false;
                        current_stitch = 0;
                        samplingVariable = Convert.ToInt32(1 / ((Properties.Settings.Default.samplesPerChannelNumeric * 100) / Properties.Settings.Default.rateNumeric));

                        this.label3.Content = Convert.ToString(Properties.Settings.Default.jobNum - 1);

                        dataTable = new DataTable();

                        chart1.Series[0].Points.Clear();
                        chart2.Series[0].Points.Clear();

                        int numofGraphs = Properties.Settings.Default.physicalChannelCheckedIndex.Length;

                        switch (numofGraphs)
                        {
                            case 0:
                                break;
                            case 1:
                                chart1.ChartAreas[0].AxisX.Maximum = Convert.ToDouble(numOfdata);
                                chart1.ChartAreas[0].AxisX.Minimum = 0;
                                break;
                            case 2:
                                chart1.ChartAreas[0].AxisX.Maximum = Convert.ToDouble(numOfdata);
                                chart1.ChartAreas[0].AxisX.Minimum = 0;
                                chart2.ChartAreas[0].AxisX.Maximum = Convert.ToDouble(numOfdata);
                                chart2.ChartAreas[0].AxisX.Minimum = 0;
                                break;
                        }
                        
                        // Create a new task
                        myTask = new NationalInstruments.DAQmx.Task();

                        // Create a virtual channel
                        myTask.AIChannels.CreateVoltageChannel(Properties.Settings.Default.physicalChannel, "",
                            (AITerminalConfiguration)(-1), Convert.ToDouble(Properties.Settings.Default.minVoltage),
                            Convert.ToDouble(Properties.Settings.Default.maxVoltage), AIVoltageUnits.Volts);

                        // Configure the timing parameters
                        myTask.Timing.ConfigureSampleClock("", Properties.Settings.Default.rateNumeric,
                            SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 100000);

                        // Verify the Task
                        myTask.Control(TaskAction.Verify);

                        // Prepare the table for Data
                        InitializeDataTable(myTask.AIChannels, ref dataTable);

                        runningTask = myTask;
                        analogInReader = new AnalogMultiChannelReader(myTask.Stream);
                        analogCallback = new AsyncCallback(AnalogInCallback);

                        // Use SynchronizeCallbacks to specify that the object 
                        // marshals callbacks across threads appropriately.
                        analogInReader.SynchronizeCallbacks = true;
                        analogInReader.BeginReadWaveform(Convert.ToInt32(Properties.Settings.Default.samplesPerChannelNumeric),
                            analogCallback, myTask);
                    }
                    catch (DaqException exception)
                    {
                        // Display Errors
                        MessageBox.Show(exception.Message, "기기 연결을 확인해주세요");
                        runningTask = null;
                        myTask.Dispose();
                    }
                }
                else
                {
                    jobNumGrid.ColumnDefinitions[1].Width = new GridLength(0);
                    jobNumGrid.ColumnDefinitions[0].Width = new GridLength(1, GridUnitType.Star);
                    try
                    {
                        Properties.Settings.Default.jobNum = 1;
                        duration = Properties.Settings.Default.jobDuration * 1000;
                        try
                        {
                            string conStr = "Server=localhost;Database=" + Properties.Settings.Default.databaseName + ";Uid=" + Properties.Settings.Default.databaseID + ";Pwd=" + Properties.Settings.Default.databasePwd;
                            MySqlConnection con = new MySqlConnection(conStr);

                            MySqlCommand comm = con.CreateCommand();
                            MySqlDataReader Reader;
                            con.Open();
                            comm.CommandText = "SELECT MAX(Measure_index) FROM `" + Properties.Settings.Default.databaseName + "`.`measured_data`";
                            Reader = comm.ExecuteReader();
                            Reader.Read();
                            measure_index = Convert.ToInt32(Reader[0]) + 1;
                            con.Close();
                        }
                        catch (Exception exc)
                        {
                            measure_index = 0;
                        }

                        try
                        {
                            string conStr = "Server=localhost;Database=" + Properties.Settings.Default.databaseName + ";Uid=" + Properties.Settings.Default.databaseID + ";Pwd=" + Properties.Settings.Default.databasePwd;
                            MySqlConnection con = new MySqlConnection(conStr);

                            MySqlCommand comm = con.CreateCommand();
                            MySqlDataReader Reader;

                            con.Open();
                            comm.CommandText = "SELECT COUNT(*) FROM `" + Properties.Settings.Default.databaseName + "`.`measured_data`";
                            Reader = comm.ExecuteReader();
                            Reader.Read();
                            measured_id = Convert.ToInt32(Reader[0]) + 1;
                            con.Close();
                        }
                        catch (Exception exc)
                        {
                            measured_id = 0;
                        }

                        numOfdata = Convert.ToInt32((Properties.Settings.Default.rateNumeric / Properties.Settings.Default.samplesPerChannelNumeric) * (duration / 1000));
                        int txtFilePathIndex = Properties.Settings.Default.textFilePathSetting.LastIndexOf("\\");
                        string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + "SF LWM\\" + Properties.Settings.Default.projectName + "\\" + DateTime.Now.ToString("yyyy MM dd") + "_" + DateTime.Now.ToString("HH mm ss");
                        Properties.Settings.Default.txtFilePath = path;
                        DirectoryInfo f = new DirectoryInfo(path);
                        if (f.Exists == false)
                            f.Create();

                        countRows = 0;
                        fault_count = 0;
                        fault_stitch = "";
                        iswelding = false;
                        current_stitch = 0;
                        samplingVariable = Convert.ToInt32(1 / ((Properties.Settings.Default.samplesPerChannelNumeric * 100) / Properties.Settings.Default.rateNumeric));

                        this.label3.Content = Convert.ToString(Properties.Settings.Default.jobNum - 1);

                        dataTable = new DataTable();

                        chart1.Series[0].Points.Clear();
                        chart2.Series[0].Points.Clear();

                        chart1.ChartAreas[0].AxisX.Maximum = Convert.ToDouble(numOfdata);
                        chart1.ChartAreas[0].AxisX.Minimum = 0;
                        chart2.ChartAreas[0].AxisX.Maximum = Convert.ToDouble(numOfdata);
                        chart2.ChartAreas[0].AxisX.Minimum = 0;

                        // Create a new task
                        myTask = new NationalInstruments.DAQmx.Task();

                        // Create a virtual channel
                        myTask.AIChannels.CreateVoltageChannel(Properties.Settings.Default.physicalChannel, "",
                            (AITerminalConfiguration)(-1), Convert.ToDouble(Properties.Settings.Default.minVoltage),
                            Convert.ToDouble(Properties.Settings.Default.maxVoltage), AIVoltageUnits.Volts);

                        // Configure the timing parameters
                        myTask.Timing.ConfigureSampleClock("", Properties.Settings.Default.rateNumeric,
                            SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 100000);

                        // Verify the Task
                        myTask.Control(TaskAction.Verify);

                        // Prepare the table for Data
                        InitializeDataTable(myTask.AIChannels, ref dataTable);

                        runningTask = myTask;
                        analogInReader = new AnalogMultiChannelReader(myTask.Stream);
                        analogCallback = new AsyncCallback(AnalogInCallback2);

                        // Use SynchronizeCallbacks to specify that the object 
                        // marshals callbacks across threads appropriately.
                        analogInReader.SynchronizeCallbacks = true;
                        analogInReader.BeginReadWaveform(Convert.ToInt32(Properties.Settings.Default.samplesPerChannelNumeric),
                            analogCallback, myTask);
                    }
                    catch (DaqException exception)
                    {
                        // Display Errors
                        MessageBox.Show(exception.Message, "기기 연결을 확인해주세요");
                        runningTask = null;
                        myTask.Dispose();
                    }
                }
            }
        }