Example #1
0
        public void EnsureIDidNotMessUpTasks()
        {
            var task = new Task("do stuff");
            task.Start();
            task.Stop();

            task.Start();
            task.Stop();

            var description = task.Description;

            // just make sure it doesn't blow up
        }
Example #2
0
        public void RepositoryWorks()
        {
            var taskRepository = new TaskRepository() { Configuration = new CoreConfiguration(".", ".") };

            var task = new Task("do stuff");
            task.Start();
            task.Stop();

            task.Start();
            task.Stop();

            taskRepository.CreateTask(task);

            var loadedTask = taskRepository.FromFileName(task.FileName);
            Assert.Equal(task.Durations.Count, loadedTask.Durations.Count);
            Assert.Equal(task.Name, loadedTask.Name);
        }
Example #3
0
        public void CanStartSaveGetAndStop()
        {
            var taskRepository = new TaskRepository() { Configuration = new CoreConfiguration(".",".") };

            var task = new Task("do stuff");
            task.Start();

            taskRepository.CreateTask(task);

            Thread.Sleep(TimeSpan.FromSeconds(1)); // TODO: remove this sleep
            var loadedTask = taskRepository.FromFileName(task.FileName);
            loadedTask.Stop();

            Assert.Equal(1, loadedTask.Durations.Count);
        }
 //This takes in a voltage. A bit cheezy, but I needed the laser
 // voltage to be set as soon value as soon as it gets configured.
 public void ConfigureSetLaserVoltage(double voltage)
 {
     outputLaserTask = new Task("FeedbackToLaser");
     laserChannel =
             (AnalogOutputChannel)Environs.Hardware.AnalogOutputChannels[laserChannelName];
     laserChannel.AddToTask(outputLaserTask, -10, 10);
     outputLaserTask.Control(TaskAction.Verify);
     laserWriter = new AnalogSingleChannelWriter(outputLaserTask.Stream);
     laserWriter.WriteSingleSample(true, voltage);
     outputLaserTask.Start();
 }
        public void TestReservedToInProgressActualOwner()
        {
            IdentityId actualId = new IdentityId();
            ILoggingService loggingService = SetupLoggerMock(new List<TaskHistoryEvent>());
            Task task = new Task(
                         new TaskId(), TaskStatus.Reserved, string.Empty,
                         string.Empty, Priority.Normal, false,
                         DateTime.UtcNow, new IdentityId().GetIdentity(),
                         DateTime.UtcNow, null, actualId.GetIdentity())
            {
                LoggingService = loggingService
            };

            Assert.IsNotNull(task);
            IPrincipal actualOwner = new ClaimsPrincipal(actualId.GetIdentity());
            Thread.CurrentPrincipal = actualOwner;
            task.Start();
            Assert.AreEqual(TaskStatus.InProgress, task.Status);
            Assert.AreEqual(actualId.GetIdentity(), task.ActualOwner);
            Assert.IsNotNull(task.History);
            Assert.AreEqual(1, task.History.Count());
            TaskHistoryEvent history = task.History.ElementAt(0);
            Assert.IsNotNull(history);
            Assert.AreEqual(TaskStatus.Reserved, history.OldStatus);
            Assert.AreEqual(TaskStatus.InProgress, history.NewStatus);
            Assert.AreEqual(actualId, history.UserId);
        }
Example #6
0
        private static void startButton_Click()
        {
            try
            {
                continuousTask = DaqSystem.Local.LoadTask(taskName);

                runningTask = continuousTask;
                continuousTask.Start();
                reader = new AnalogMultiChannelReader(continuousTask.Stream);

                callBack = new AsyncCallback(ReadCallBack);

                reader.SynchronizeCallbacks = true;
                reader.BeginReadWaveform(Convert.ToInt32(continuousTask.Timing.SamplesPerChannel), callBack, continuousTask);
                while (true)
                {
                }

            }
            catch (DaqException ex)
            {
                continuousTask.Dispose();
            }
        }
        public void TestTaskReady()
        {
            TaskEntity entity = new TaskEntity
            {
                TaskId = new TaskId(),
                Initiator = new IdentityId().GetIdentity(),
                Priority = Priority.Normal,
                Status = TaskStatus.Created,
                Created = DateTime.UtcNow,
                Name = "Name",
                Subject = "Subject"
            };

            Task task = new Task(entity)
            {
                LoggingService = new Mock<ILoggingService>().Object,
                Priority = Priority.High

            };

            TaskDao dao = new TaskDao(SessionFactory);
            task.Accept(dao);
            Task loaded;
            using (ISession session = SessionFactory.OpenSession())
            {
                TaskEntity te = session.Query<TaskEntity>().Where(t => t.TaskId == entity.TaskId).FirstOrDefault();
                loaded=new Task(te);
            }
            Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            IPrincipal p = Thread.CurrentPrincipal;
            loaded.Start();
            task.Accept(dao);
            loaded.Claim();
            task.Accept(dao);
        }
 public void ConfigureScanTrigger()
 {
     sendScanTriggerTask = new Task("Send Cavity UnlockCavity Trigger");
     sendTriggerChannel = (DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels[triggerOutput];
     sendTriggerChannel.AddToTask(sendScanTriggerTask);
     sendScanTriggerTask.Control(TaskAction.Verify);
     triggerWriter = new DigitalSingleChannelWriter(sendScanTriggerTask.Stream);
     triggerWriter.WriteSingleSampleSingleLine(true, false);
     sendScanTriggerTask.Start();
 }
Example #9
0
        /// <summary>
        /// Perform IV cycles while standing in place
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="worker"></param>
        /// <param name="e"></param>
        public void IV_AcquireDataWithoutMoving(IVSettings settings, BackgroundWorker worker, DoWorkEventArgs e)
        {
            int finalFileNumber = settings.IVGeneralSettings.CurrentFileNumber;
            double[,] dataAcquired;
            List<IDataChannel> physicalChannels = new List<IDataChannel>();

            //
            // Save this run settings if desired
            //
            SaveSettingsIfNeeded(settings, settings.IVGeneralSettings.IsFileSavingRequired, settings.IVGeneralSettings.Path);

            //
            // apply initial voltage on the EM if needed
            //
            ApplyVoltageOnElectroMagnetIfNeeded(settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet);


            //
            // create the input and output tasks
            //
            m_ivInputTask = GetContinuousAITask(settings.IVGeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);
            m_ivInputTask.Stream.ReadRelativeTo = ReadRelativeTo.FirstSample;
            m_outputTask = GetContinuousAOTask(settings);

            //
            // initiate writer for the output and set initial bias
            //
            InitiateOutputWriter(m_outputTask, settings);

            //
            // Main loop for data aquisition
            //
            for (int i = 0; i < settings.IVGeneralSettings.TotalNumberOfCycles; i++)
            {
                //
                // Cancel the operatin if user asked for
                //
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                m_quitRealTimeOperation = false;

                //
                // we set the votlage to triangle wave and then open the junction by the EM
                //
                writer.BeginWriteMultiSample(false, m_functionGenerator.TriangleWave, null, null);

                //
                // Start the input task.
                //
                try
                {
                    m_ivInputTask.Start();
                }
                catch (DaqException ex)
                {
                    throw new SBJException("Error occured when tryin to start DAQ input task", ex);
                }

                //
                // start reading continuously. 
                // when the junction is opened, the opening thread will change m_quitJuncctionOpeningOperation to true.
                // set dataAquired to null otherwise it saves last cycle's data. 
                //
                reader = new AnalogMultiChannelReader(m_ivInputTask.Stream);
                dataAcquired = null;
                try
                {
                    while (!m_quitRealTimeOperation)
                    {
                        try
                        {
                            dataAcquired = reader.ReadMultiSample(-1);
                        }
                        catch (DaqException)
                        {
                            continue;
                        }
                    }

                    if (dataAcquired != null)
                    {
                        if (settings.ChannelsSettings.ActiveChannels.Count != dataAcquired.GetLength(0))
                        {
                            throw new SBJException("Number of data channels doesn't fit the recieved data.");
                        }
                    }
                }
                catch (DaqException ex)
                {
                    //
                    // Probably timeout.
                    // Ignore this cycle and rerun.
                    //
                    m_ivInputTask.Stop();
                    continue;
                }

                //
                // At this point the reader has returned with all the data and we can stop the input task.
                //
                m_ivInputTask.Stop();

                //
                // if we didn't acquire any data, there's no need to save anything.
                //
                if (dataAcquired == null)
                {
                    continue;
                }

                //
                // Assign the aquired data for each channel.
                // First clear all data from previous interation.
                //                
                ClearRawData(settings.ChannelsSettings.ActiveChannels);
                AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, dataAcquired);

                //
                // physical channel will include both simple and complex channels. 
                // 
                physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

                //
                // calculate the physical data for each channel
                //
                GetPhysicalData(physicalChannels);

                //
                // the IV acquisition is done, we need to return the output to constant voltage for the next cycle
                //
                writer.BeginWriteMultiSample(false, m_functionGenerator.ConstWave, null, null);

                // 
                // Increase file number by one
                // Save data if needed
                //
                finalFileNumber++;
                if (settings.IVGeneralSettings.IsFileSavingRequired)
                {
                    finalFileNumber = SaveData(settings.IVGeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
                }

                //
                // Signal UI we have the data
                //
                if (DataAquired != null)
                {
                    DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
                }
            }

            //
            // Finish the measurement properly
            //
            if (settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet)
            {
                m_electroMagnet.Shutdown();
            }
            m_ivInputTask.Dispose();
            m_ivInputTask = null;
            m_outputTask.Dispose();
            m_outputTask = null;
            m_stepperMotor.Shutdown();
        }
Example #10
0
        /// <summary>
        /// Do Cycles of closing and opening the junction, while measuring IVs
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="worker"></param>
        /// <param name="e"></param>
        public void IV_AcquireData(IVSettings settings,BackgroundWorker worker, DoWorkEventArgs e)
        {
            bool isCancelled = false;
            int finalFileNumber = settings.IVGeneralSettings.CurrentFileNumber;
            double[,] dataAcquired;
            List<IDataChannel> physicalChannels = new List<IDataChannel>();

            //
            // Save this run settings if desired
            //
            SaveSettingsIfNeeded(settings, settings.IVGeneralSettings.IsFileSavingRequired, settings.IVGeneralSettings.Path);

            //
            // apply initial voltage on the EM if needed
            //
            ApplyVoltageOnElectroMagnetIfNeeded(settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet);

            
            //
            // create the input and output tasks
            //
            m_ivInputTask = GetContinuousAITask(settings.IVGeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);
            m_ivInputTask.Stream.ReadRelativeTo = ReadRelativeTo.FirstSample;
            m_outputTask = GetContinuousAOTask(settings);

            //
            // initiate writer for the output and set initial bias
            //
            InitiateOutputWriter(m_outputTask, settings);
            
            //
            // Main loop for data aquisition
            //
            for (int i = 0; i < settings.IVGeneralSettings.TotalNumberOfCycles; i++)
            {
                //
                // Cancel the operatin if user asked for
                //
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                //
                // if we use EM, and we are asked to skip the first cycle (that is done by the stepper motor), 
                // move on to the next cycle.
                //
                if (i == 0 && settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet 
                            && settings.IVSteppingMethodSettings.IsEMSkipFirstCycleEnable)
                {
                    m_stepperMotor.Shutdown();
                    continue;
                }

                //
                // Change the gain power to 5 before reaching contact
                // to ensure full contact current
                //
                m_amplifier.ChangeGain(5);

                //
                // Reach to contact before we start openning the junction
                // If we use EM and we're after the first cycle, use the EM.
                // If user asked to stop than exit
                //
                isCancelled = (settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet && i > 0) ?
                               EMTryObtainShortCircuit(settings.IVSteppingMethodSettings.EMShortCircuitDelayTime, settings.IVGeneralSettings.ShortCircuitVoltage, worker, e) :
                               TryObtainShortCircuit(settings.IVGeneralSettings.ShortCircuitVoltage,settings.IVGeneralSettings.UseShortCircuitDelayTime,settings.IVGeneralSettings.ShortCircuitDelayTime,worker, e);
                if (isCancelled)
                {
                    break;
                }

                //
                // Configure the gain to the desired one before strating the measurement.
                // And also this is the time to switch the laser on.
                //
                int gainPower;
                Int32.TryParse(settings.IVGeneralSettings.Gain, out gainPower);
                m_amplifier.ChangeGain(gainPower);

                //
                // Start openning the junction.
                // If EM is enabled and we're after the first cycle, use the EM.
                //
                if (settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet)
                {
                    if (i == 0)
                    {
                        //
                        // we are on the first cycle and wish to open the junction by the stepper motor.
                        //
                        ObtainOpenJunctionByStepperMotor(settings.IVGeneralSettings.TriggerVoltage, worker, e);

                        //
                        // from now on we will be using the electroMagnet, so lets turn the stepper motor off and move to the next cycle
                        //
                        m_stepperMotor.Shutdown();
                        continue;
                    }
                    else
                    {
                        //
                        // we set the votlage to triangle wave and then open the junction by the EM
                        //
                        writer.BeginWriteMultiSample(false, m_functionGenerator.TriangleWave, null, null);
                        IV_EMBeginOpenJunction(settings);
                    }
                }
                else
                {
                    //
                    // we set the voltage to triangle wave and then open the junction by stepper motor
                    //
                    writer.BeginWriteMultiSample(false, m_functionGenerator.TriangleWave, null, null);
                    IV_StepperMotorBeginOpenJunction(settings);
                }

                //
                // Start the input task.
                //
                try
                {
                    m_ivInputTask.Start();
                }
                catch (DaqException ex)
                {
                    throw new SBJException("Error occured when tryin to start DAQ input task", ex);
                }

                //
                // start reading continuously. 
                // when the junction is opened, the opening thread will change m_quitJuncctionOpeningOperation to true.
                // set dataAquired to null otherwise it saves last cycle's data. 
                //
                reader = new AnalogMultiChannelReader(m_ivInputTask.Stream);
                dataAcquired = null;
                try
                {
                    while (!m_quitJunctionOpenningOperation)
                    {
                        dataAcquired = reader.ReadMultiSample(-1);
                    }

                    if (dataAcquired != null)
                    {
                        if (settings.ChannelsSettings.ActiveChannels.Count != dataAcquired.GetLength(0))
                        {
                            throw new SBJException("Number of data channels doesn't fit the recieved data.");
                        }
                    }
                }
                catch (DaqException)
                {
                    //
                    // Probably timeout.
                    // Ignore this cycle and rerun.
                    //
                    m_ivInputTask.Stop();
                    continue;
                }

                //
                // At this point the reader has returned with all the data and we can stop the input task.
                //
                m_ivInputTask.Stop();

                //
                // if we didn't acquire any data, there's no need to save anything.
                //
                if (dataAcquired == null)
                {
                    continue;
                }

                //
                // Assign the aquired data for each channel.
                // First clear all data from previous interation.
                //                
                ClearRawData(settings.ChannelsSettings.ActiveChannels);
                AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, dataAcquired);

                //
                // physical channel will include both simple and complex channels. 
                // 
                physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

                //
                // calculate the physical data for each channel
                //
                GetPhysicalData(physicalChannels);

                //
                // the IV acquisition is done, we need to return the output to constant voltage for the next cycle
                //
                writer.BeginWriteMultiSample(false, m_functionGenerator.ConstWave, null, null);

                // 
                // Increase file number by one
                // Save data if needed
                //
                finalFileNumber++;
                if (settings.IVGeneralSettings.IsFileSavingRequired)
                {
                    finalFileNumber = SaveData(settings.IVGeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
                }

                //
                // Signal UI we have the data
                //
                if (DataAquired != null)
                {
                    DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
                }     
            }

            //
            // Finish the measurement properly
            //
            if (settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet)
            {
                m_electroMagnet.Shutdown();
            }
            m_ivInputTask.Dispose();
            m_ivInputTask = null;
            m_outputTask.Dispose();
            m_outputTask = null;
            m_stepperMotor.Shutdown();
        }
Example #11
0
        /// <summary>
        /// Manually aquire data
        /// This method continuously poll the buffer for data until it is stopped by the user.
        /// </summary>
        /// <param name="settings">The settings for running the aquisition</param>
        /// <returns>True whether the operation was cacled by the user. False otherwise.</returns>
        public bool AquireDataContinuously(SBJControllerSettings settings, BackgroundWorker worker, DoWorkEventArgs e)
        {
            //
            // Apply voltage with desired tool: Task or Keithley
            //
            ApplyVoltageIfNeeded(settings.GeneralSettings.UseKeithley,
                                 settings.GeneralSettings.Bias,
                                 settings.GeneralSettings.BiasError,
                                 settings.GeneralSettings.Range,
                                 settings.GeneralSettings.AutoRange);
            bool isCancelled = false;
            int finalFileNumber = settings.GeneralSettings.CurrentFileNumber;

            //
            // The array is intialized with size for 1 minute sampling.
            //
            double[,] dataAquired = new double[1000, 1000];

            List<IDataChannel> physicalChannels = new List<IDataChannel>();

            //
            // Configure the laser if needed for this run
            //
            ConfigureLaserIfNeeded(settings);

            //
            // Save this run settings if desired
            //
            SaveSettingsIfNeeded(settings, settings.GeneralSettings.IsFileSavingRequired, settings.GeneralSettings.Path);

            //
            //apply initial voltage on the EM
            //
            ApplyVoltageOnElectroMagnetIfNeeded(settings.ElectromagnetSettings.IsEMEnable);

            //
            // Create the task
            //
            m_activeTriggeredTask = GetContinuousAITask(settings.GeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);

            //
            // If EM is enabled, and we are asked to skip the first cycle (that is done by the stepper motor), 
            // then return.
            //
            if (settings.ElectromagnetSettings.IsEMEnable && settings.ElectromagnetSettings.IsEMSkipFirstCycleEnable)
            {
                m_stepperMotor.Shutdown();
                return false;
            } 

            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOn();
            }
           

            //
            // Start the task and wait for the data
            //
            try
            {
                m_activeTriggeredTask.Start();
            }
            catch (DaqException ex)
            {
                throw new SBJException("Error occured when tryin to start DAQ task", ex);
            }

            AnalogMultiChannelReader reader = new AnalogMultiChannelReader(m_activeTriggeredTask.Stream);
            List<List<double>> fullData = new List<List<double>>(settings.ChannelsSettings.ActiveChannels.Count);

            for (int i = 0; i < fullData.Capacity; i++)
            {
                fullData.Add(new List<double>());
            }

            try
            {
                //
                // Before getting all the data clear the lists.
                //
                ClearRawData(settings.ChannelsSettings.ActiveChannels);

                //
                // As long as the user didn't ask to stop the acquisition 
                // (which is signaled by the stop of the stepper motion)
                // we coninue sampling.
                //
                while (!worker.CancellationPending)
                {
                    //
                    // Read all available data points in the buffer that
                    // were not read so far.
                    //
                    dataAquired = reader.ReadMultiSample(-1);
                    fullData = AccumulateData(fullData, dataAquired);                    
                    dataAquired = null;                  
                }
            }
            catch (DaqException)
            {
                //
                // In case of an error just return
                //
                m_activeTriggeredTask.Stop();
                m_activeTriggeredTask.Dispose();
                if (m_LaserController != null)
                {
                    m_LaserController.TurnOff();
                }
                if (m_taborFirstEOMController != null)
                {
                    m_taborFirstEOMController.TurnOff();
                }
                if (m_taborSecondEOMController != null)
                {
                    m_taborSecondEOMController.TurnOff();
                }
                return false;
            }

            //
            // At this point the user had requested to stop the data aquisition.
            // By signaling "stop". We can stop the task.
            //            
            m_activeTriggeredTask.Stop();

            //
            // Assign the aquired data for each channel after an average process
            //                    
            AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, ConvertDataToMatrix(fullData));

            //
            // physical channel will include both simple and complex channels. 
            // 
            physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

            //
            // calculate the physical data for each channel
            //
            GetPhysicalData(physicalChannels);

            // 
            // Increase file number by one
            // Save data if needed
            //
            finalFileNumber++;
            if (settings.GeneralSettings.IsFileSavingRequired)
            {
                finalFileNumber = SaveData(settings.GeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
            }

            //
            // Signal UI we have the data
            //
            if (DataAquired != null)
            {
                DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
            }


            //
            // Finish the measurement properly
            //
            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOff();
            }
            if (settings.ElectromagnetSettings.IsEMEnable)
            {
                m_electroMagnet.Shutdown();
            }
            if (settings.LaserSettings.IsFirstEOMOn)
            {
                m_taborFirstEOMController.TurnOff();
            }
            if (settings.LaserSettings.IsSecondEOMOn)
            {
                m_taborSecondEOMController.TurnOff();
            }

            m_activeTriggeredTask.Dispose();
            m_stepperMotor.Shutdown();

            return (isCancelled || e.Cancel);
        }
Example #12
0
        /// <summary>
        /// Manually aquire data
        /// This method continuously poll the buffer for data until it is stopped by the user.
        /// </summary>
        /// <param name="settings">The settings for running the aquisition</param>
        /// <returns>True whether the operation was cacled by the user. False otherwise.</returns>
        public bool AquireDataManually(SBJControllerSettings settings, BackgroundWorker worker, DoWorkEventArgs e)
        {
            //
            // Apply voltage with desired tool: Task or Keithley
            //
            ApplyVoltageIfNeeded(settings.GeneralSettings.UseKeithley,
                                 settings.GeneralSettings.Bias,
                                 settings.GeneralSettings.BiasError,
                                 settings.GeneralSettings.Range,
                                 settings.GeneralSettings.AutoRange);

            bool isCancelled = false;
            int finalFileNumber = settings.GeneralSettings.CurrentFileNumber;
       
            //
            // The array is intialized with size for 1 minute sampling.
            //
            double[,] dataAquired = new double[1000, 1000];

            List<IDataChannel> physicalChannels = new List<IDataChannel>();

            //
            // Configure the laser if needed for this run
            //
            ConfigureLaserIfNeeded(settings);

            //
            // Save this run settings if desired
            //
            SaveSettingsIfNeeded(settings, settings.GeneralSettings.IsFileSavingRequired, settings.GeneralSettings.Path);

            //
            //apply initial voltage on the EM
            //
            ApplyVoltageOnElectroMagnetIfNeeded(settings.ElectromagnetSettings.IsEMEnable);

            //
            // Create the task
            //
            m_activeTriggeredTask = GetContinuousAITask(settings.GeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);
            
            //
            // If EM is enabled, and we are asked to skip the first cycle (that is done by the stepper motor), 
            // then return.
            //
            if (settings.ElectromagnetSettings.IsEMEnable && settings.ElectromagnetSettings.IsEMSkipFirstCycleEnable)
            {
                m_stepperMotor.Shutdown();
                return false;
            }

            //
            // Turn off the laser before we reach contact
            //
            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOff();
                Thread.Sleep(5000);
            }

            //
            // Change the gain power to 5 before reaching contact
            // to ensure full contact current
            //
            if (settings.GeneralSettings.UseDefaultGain)
            {
                m_amplifier.ChangeGain(5);
            }

            //
            // Reach to contact before we start openning the junction
            // If EM is enabled and we're after the first cycle, use the EM.
            // If user asked to stop than exit
            //
            isCancelled = (settings.ElectromagnetSettings.IsEMEnable) ?
                           EMTryObtainShortCircuit(settings.ElectromagnetSettings.EMShortCircuitDelayTime, 
                                                   settings.GeneralSettings.ShortCircuitVoltage, worker, e) :
                           TryObtainShortCircuit(settings.GeneralSettings.ShortCircuitVoltage, settings.GeneralSettings.UseShortCircuitDelayTime,settings.GeneralSettings.ShortCircuitDelayTime, worker, e);
            if (isCancelled)
            {
                return false;
            }

            //
            // Configure the gain to the desired one before strating the measurement.
            // And also this is the time to switch the laser on.
            //
            if (settings.GeneralSettings.UseDefaultGain)
            {
                int gainPower;
                Int32.TryParse(settings.GeneralSettings.Gain, out gainPower);
                m_amplifier.ChangeGain(gainPower);
            }


            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOn();
            }

            //
            // Start openning the junction.
            // If EM is enabled then use it.
            //
            if (settings.ElectromagnetSettings.IsEMEnable)
            {
                m_stepperMotor.Shutdown();
                EMBeginOpenJunction(settings, worker, e);                
            }
            else
            {
                BeginOpenJunction(settings, worker, e);
            }

            //
            // Start the task and wait for the data
            //
            try
            {
                m_activeTriggeredTask.Start();
            }
            catch (DaqException ex)
            {
                throw new SBJException("Error occured when tryin to start DAQ task", ex);
            }

            AnalogMultiChannelReader reader = new AnalogMultiChannelReader(m_activeTriggeredTask.Stream);
            List<List<double>> averagedData = new List<List<double>>(settings.ChannelsSettings.ActiveChannels.Count);

            for (int i = 0; i < averagedData.Capacity; i++)
            {
                averagedData.Add(new List<double>());
            }

            try
            {
                //
                // Before getting all the data clear the lists.
                //
                ClearRawData(settings.ChannelsSettings.ActiveChannels);              

                //
                // As long as the user didn't ask to stop the acquisition 
                // (which is signaled by the stop of the stepper motion)
                // we coninue sampling.
                //
                while (!m_quitJunctionOpenningOperation)
                {
                    //
                    // Read all available data points in the buffer that
                    // were not read so far.
                    //
                    dataAquired = reader.ReadMultiSample(-1);

                    //
                    // Get average for the acquired the data and assign to variable
                    //
                    List<double> averageDataValues = GetAverageDataValue(dataAquired);
                    for (int i = 0; i < averageDataValues.Count; i++)
                    {                        
                        averagedData[i].Add(averageDataValues[i]);
                    }
                      
                    dataAquired = null;
 
                    //
                    // Cancel the operatin if user asked for
                    // We do it at the end of the loop to make sure we 
                    // saved all the data we have available.
                    //
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        break;
                    }
                }                
            }
            catch (DaqException)
            {
                //
                // In case of an error just return
                //
                m_activeTriggeredTask.Stop();
                m_activeTriggeredTask.Dispose();
                if (m_LaserController != null)
                {
                m_LaserController.TurnOff();
                }
                if (m_taborFirstEOMController != null)
                {
                    m_taborFirstEOMController.TurnOff();
                }
                if (m_taborSecondEOMController != null)
                {
                    m_taborSecondEOMController.TurnOff();
                }
                return false;
            }

            //
            // At this point the user had requested to stop the data aquisition.
            // By signaling "stop". We can stop the task.
            //            
            m_activeTriggeredTask.Stop();

            //
            // Assign the aquired data for each channel after an average process
            //                    
            AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, ConvertDataToMatrix(GetAveragedData(averagedData, 5000)));

            //
            // physical channel will include both simple and complex channels. 
            // 
            physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

            //
            // calculate the physical data for each channel
            //
            GetPhysicalData(physicalChannels);

            // 
            // Increase file number by one
            // Save data if needed
            //
            finalFileNumber++;
            if (settings.GeneralSettings.IsFileSavingRequired)
            {
                finalFileNumber = SaveData(settings.GeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
            }

            //
            // Signal UI we have the data
            //
            if (DataAquired != null)
            {
                DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
            }
            

            //
            // Finish the measurement properly
            //
            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOff();
            }
            if (settings.ElectromagnetSettings.IsEMEnable)
            {
                m_electroMagnet.Shutdown();
            }
            if (settings.LaserSettings.IsFirstEOMOn)
            {
                m_taborFirstEOMController.TurnOff();
            }
            if (settings.LaserSettings.IsSecondEOMOn)
            {
                m_taborSecondEOMController.TurnOff();
            }

            m_activeTriggeredTask.Dispose();
            m_stepperMotor.Shutdown();

            return (isCancelled || e.Cancel);
        }
Example #13
0
        /// <summary>
        /// Reach to position specified by conductance value and then stop and aqcuire data until asked to stop.
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="worker"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private bool ReachToPositionByMovingUp(SBJControllerSettings settings, BackgroundWorker worker, DoWorkEventArgs e)
        {
            double[,] dataAcquired = new double[1000, 1000];
            int finalFileNumber = settings.GeneralSettings.CurrentFileNumber;
            List<IDataChannel> physicalChannels = new List<IDataChannel>();


            for (int i = 0; i < settings.GeneralSettings.TotalNumberOfCycles; i++)
            {
                //
                // Cancel the operatin if user asked for
                //
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                //
                // This flag is used to signal us when the user asked to stop the real time data acquisition
                //
                m_quitRealTimeOperation = false;
                m_activeTriggeredTask = GetMultipleChannelsTriggeredTask(settings, null, RunDirection.Break, m_triggerSlope, m_triggerVoltage, worker, e);
                m_activeTriggeredTask.EveryNSamplesReadEventInterval = settings.GeneralSettings.TotalSamples;
                m_activeTriggeredTask.Done += new TaskDoneEventHandler(OnTaskDoneOpenning);
                m_activeTriggeredTask.Control(TaskAction.Verify);
                m_triggerSlope = m_activeTriggeredTask.Triggers.ReferenceTrigger.AnalogEdge.Slope;
                m_triggerVoltage = m_activeTriggeredTask.Triggers.ReferenceTrigger.AnalogEdge.Level;

                //
                // physical channel will include both simple and complex channels. 
                // 
                physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

                //
                // Assign the aquired data for each channel.
                // First clear all data from previous interation.
                //                
                ClearRawData(settings.ChannelsSettings.ActiveChannels);

                //
                // Create the tasks: One for triggering us to stop and the other for start monitoring the data
                //
                m_realTimeTask = GetContinuousAITask(settings.GeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);
                AnalogMultiChannelReader realTimeReader = new AnalogMultiChannelReader(m_realTimeTask.Stream);

                //
                // Start closing the junction.
                // If EM is enabled use the EM.
                //
                if (settings.ElectromagnetSettings.IsEMEnable)
                {
                    EMTryObtainShortCircuit(settings.ElectromagnetSettings.EMShortCircuitDelayTime, settings.GeneralSettings.ShortCircuitVoltage, worker, e);
                }
                else
                {
                    TryObtainShortCircuit(settings.GeneralSettings.ShortCircuitVoltage, settings.GeneralSettings.UseShortCircuitDelayTime,settings.GeneralSettings.ShortCircuitDelayTime, worker, e);
                }

                //
                // Start openning the junction. ASync operation.
                // If EM is enabled use the EM.
                //
                if (settings.ElectromagnetSettings.IsEMEnable)
                {
                    EMBeginOpenJunction(settings, worker, e);
                }
                else
                {
                    BeginOpenJunction(settings, worker, e);
                }

                //
                // Cancel the operatin if user asked for
                //
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                //
                // Start the triggered task. 
                //
                m_activeTriggeredTask.Start();

                //
                // If the user asked to stop the operation on the external thread then
                // WaitUntilDone will throw an expection. We can ignore that and return.
                //
                try
                {
                    m_activeTriggeredTask.WaitUntilDone();
                }
                catch (DaqException)
                {
                    //
                    // We got here if the user asked to stop the operation
                    //
                    break;
                }

                //
                // We reach this point only after we reached the desired conductance value.
                // As long as the user didn't ask to stop the operation continue recording the data.
                //
                while (!m_quitRealTimeOperation)
                {
                    //
                    // Read operation implicity start the task without the need to call Start() method.
                    //
                    try
                    {
                        dataAcquired = realTimeReader.ReadMultiSample(-1);
                    }
                    catch (DaqException)
                    {
                        continue;
                    }


                    if (dataAcquired.Length == 0)
                    {
                        continue;
                    }
                    //
                    // Assign the aquired data for each channel.
                    //                            
                    AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, dataAcquired);

                    //
                    // calculate the physical data for each channel
                    //
                    GetPhysicalData(physicalChannels);

                    //
                    // Signal UI we have the data
                    //
                    if (DataAquired != null)
                    {
                        DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
                    }
                }

                if (DoneReadingData != null)
                {
                    DoneReadingData(this, null);
                }
                m_realTimeTask.Stop();
                m_realTimeTask.Dispose();

                // 
                // Increase file number by one
                // Save data if needed
                //
                finalFileNumber++;
                if (settings.GeneralSettings.IsFileSavingRequired)
                {
                    finalFileNumber = SaveData(settings.GeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
                }
            }

            m_activeTriggeredTask.Dispose();
            m_realTimeTask.Dispose();
            m_triggerSlope = 0;
            m_triggerVoltage = 0;
            return e.Cancel;
        }
Example #14
0
        // Look at the recording hardware settings and create NI Tasks that reflect the user's choices
        private void UpdateRecordingSettings()
        {
            //resets channel counts for input streams
            updateChannelCount();

            // update the recordingSettings object
            recordingSettings.RefreshForm();

            // Set spike buffer lengths
            spikeBufferLength = Convert.ToInt32(Properties.Settings.Default.ADCPollingPeriodSec * Properties.Settings.Default.RawSampleFrequency);
            lfpBufferLength = Convert.ToInt32(Properties.Settings.Default.ADCPollingPeriodSec * Properties.Settings.Default.LFPSampleFrequency);
            eegBufferLength = Convert.ToInt32(Properties.Settings.Default.ADCPollingPeriodSec * Properties.Settings.Default.EEGSamplingRate);
            // Enable spike detector saving while stopped
            spikeDet.EnableFileMenu();

            // update recording type to nominal
            isNormalRecording = true;

            // Refresh all the NI Tasks
            try
            {

                if (spikeTask != null)
                {
                    bool cantReset = true;

                    //Hack to prevent lock up
                    DateTime startTime = DateTime.Now;
                    while (cantReset)
                    {
                        cantReset = false;
                        for (int i = 0; i < spikeTask.Count; i++)
                            cantReset = cantReset || bwIsRunning[i];
                        System.Threading.Thread.Sleep(100);

                        // Exit the loop if we are waiting for more than a second
                        if ((DateTime.Now - startTime).TotalSeconds > 0.5)
                            break;
                    }
                    for (int i = 0; i < spikeTask.Count; ++i)
                        spikeTask[i].Dispose();
                    spikeTask.Clear(); spikeTask = null;
                }
                if (stimTimeTask != null) { stimTimeTask.Dispose(); stimTimeTask = null; }
                if (stimIvsVTask != null) { stimIvsVTask.Dispose(); stimIvsVTask = null; }
                if (serialOut != null) { serialOut.Close(); serialOut.Dispose(); }
                if (Properties.Settings.Default.UseCineplex)
                {
                    if (videoTask == null)
                    {
                        videoTask = new Task("videoTask");
                        videoTask.COChannels.CreatePulseChannelFrequency(Properties.Settings.Default.CineplexDevice + "/ctr0", "",
                            COPulseFrequencyUnits.Hertz, COPulseIdleState.Low, 0, 1000, 0.5);
                        videoTask.Control(TaskAction.Verify);
                        videoTask.Timing.ReferenceClockSource = "OnboardClock";
                        videoTask.Timing.ConfigureImplicit(SampleQuantityMode.ContinuousSamples, 10);
                        videoTask.Start();
                    }
                    checkBox_video.Enabled = true;
                }
                else
                    checkBox_video.Enabled = false;

                try
                {
                    if (Properties.Settings.Default.UseProgRef)
                    {
                        string serialOutPort = Properties.Settings.Default.SerialPortDevice;
                        serialOut = new SerialPort(serialOutPort, 38400, Parity.None, 8, StopBits.One);
                        serialOut.Open();
                        serialOut.Write("#0140/0\r"); //Reset everything to power-up state
                        groupBox_plexonProgRef.Visible = true;
                    }
                    else
                    {
                        groupBox_plexonProgRef.Visible = false;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("There was a problem when setting up the serial communicaiton port to the Plexon device:\r\n\r\n" + ex.Message);
                    groupBox_plexonProgRef.Visible = false;
                }

                this.drawOpenLoopStimPulse();

                //Add LFP tab, if applicable
                if (Properties.Settings.Default.UseLFPs && !tabControl.TabPages.Contains(tabPage_LFPs))
                {
                    tabPage_LFPs = new TabPage("LFPs");
                    tabControl.TabPages.Insert(2, tabPage_LFPs);
                }
                else if (!Properties.Settings.Default.UseLFPs && tabControl.TabPages.Contains(tabPage_LFPs))
                    tabControl.TabPages.Remove(tabPage_LFPs);

                //Add MUA tab, if applicable
                if (Properties.Settings.Default.ProcessMUA && !tabControl.TabPages.Contains(tabPage_MUA))
                {
                    tabPage_MUA = new TabPage("MUA");
                    tabControl.TabPages.Insert((Properties.Settings.Default.UseLFPs ? 3 : 2), tabPage_MUA);
                }
                else if (!Properties.Settings.Default.ProcessMUA && tabControl.TabPages.Contains(tabPage_MUA))
                    tabControl.TabPages.Remove(tabPage_MUA);

                //Add EEG tab, if applicable
                if (Properties.Settings.Default.UseEEG && !tabControl.TabPages.Contains(tabPage_EEG))
                {
                    tabPage_EEG = new TabPage("EEG");
                    int pageNum = 2;
                    if (Properties.Settings.Default.UseLFPs)
                        pageNum++;
                    if (Properties.Settings.Default.ProcessMUA)
                        pageNum++;
                    tabControl.TabPages.Insert(pageNum, tabPage_EEG);
                }
                else if (!Properties.Settings.Default.UseEEG && tabControl.TabPages.Contains(tabPage_EEG))
                    tabControl.TabPages.Remove(tabPage_EEG);

                ////Add Aux tab, if applicable
                //if ((Properties.Settings.Default.useAuxAnalogInput || Properties.Settings.Default.useAuxDigitalInput)
                //    && !tabControl.TabPages.Contains(tabPage_AuxInput))
                //{
                //    int pageNum = 2;
                //    if (Properties.Settings.Default.UseLFPs)
                //        pageNum++;
                //    if (Properties.Settings.Default.ProcessMUA)
                //        pageNum++;
                //    if (Properties.Settings.Default.UseEEG)
                //        pageNum++;
                //    tabControl.TabPages.Insert(pageNum, tabPage_AuxInput);
                //}
                //else if (!(Properties.Settings.Default.useAuxAnalogInput || Properties.Settings.Default.useAuxDigitalInput)
                //    && tabControl.TabPages.Contains(tabPage_AuxInput))
                //    tabControl.TabPages.Remove(tabPage_AuxInput);
                if (tabControl.TabPages.Contains(tabPage_AuxInput))
                    tabControl.TabPages.Remove(tabPage_AuxInput);

                //Add Referencing tab, if applicable
                if ((Properties.Settings.Default.UseProgRef || Properties.Settings.Default.UseFloatingRef)
                    && !tabControl.TabPages.Contains(tabPage_ProgRef))
                {
                    int pageNum = 2;
                    if (Properties.Settings.Default.UseLFPs)
                        pageNum++;
                    if (Properties.Settings.Default.ProcessMUA)
                        pageNum++;
                    if (Properties.Settings.Default.UseEEG)
                        pageNum++;
                    if (Properties.Settings.Default.useAuxAnalogInput || Properties.Settings.Default.useAuxDigitalInput)
                        pageNum++;

                    pageNum++; // Account for stimulation page
                    tabControl.TabPages.Insert(pageNum, tabPage_ProgRef);
                }
                else if (!(Properties.Settings.Default.UseProgRef || Properties.Settings.Default.UseFloatingRef)
                    && tabControl.TabPages.Contains(tabPage_ProgRef))
                    tabControl.TabPages.Remove(tabPage_ProgRef);

                //Add Impedance tab, if applicable
                if (Properties.Settings.Default.useImpedanceMeasurer && !tabControl.TabPages.Contains(tabPage_impedance))
                {
                    tabPage_MUA = new TabPage("Impedance Measurement");
                    tabControl.TabPages.Insert(tabControl.TabPages.Count, tabPage_impedance);
                }
                else if (!Properties.Settings.Default.useImpedanceMeasurer && tabControl.TabPages.Contains(tabPage_impedance))
                    tabControl.TabPages.Remove(tabPage_impedance);

                // Remove the Referencing and Diagnostics tabs since they are currently non functional
                //if (tabControl.TabPages.Contains(tabPage_ProgRef))
                //{
                //    tabControl.TabPages.Remove(tabPage_ProgRef);
                //}
                if (tabControl.TabPages.Contains(tabPage_diagnostics))
                {
                    tabControl.TabPages.Remove(tabPage_diagnostics);
                }

                Console.WriteLine("UpdateRecordingSettings finished");
            }
            catch (DaqException exception)
            {
                MessageBox.Show(exception.Message); //Display Errors
                reset();
            }
        }
        public void Configure( double clockFrequency, bool loop, bool fullWidth,
                                    bool lowGroup, int length, bool internalClock, bool triggered)
        {
            this.clockFrequency = clockFrequency;
            this.length = length;

            pgTask = new Task("pgTask");

            /**** Configure the output lines ****/

            // The underscore notation is the way to address more than 8 of the PatternList generator
            // lines at once. This is really buried in the NI-DAQ documentation !
            String chanString = "";
            if ((string)Environs.Hardware.GetInfo("PGType") == "dedicated")
            {
                if (fullWidth) chanString = device + "/port0_32";
                else
                {
                    if (lowGroup) chanString = device + "/port0_16";
                    else chanString = device + "/port3_16";
                }
            }
            // as far as I know you can only address the whole 32-bit port on the 6229 type integrated PatternList generators
            if ((string)Environs.Hardware.GetInfo("PGType") == "integrated")
            {
                chanString = device + "/port0";
            }

            DOChannel doChan = pgTask.DOChannels.CreateChannel(
                chanString,
                "pg",
                ChannelLineGrouping.OneChannelForAllLines
                );

            /**** Configure the clock ****/

            String clockSource = "";
            if ((string)Environs.Hardware.GetInfo("PGType") == "dedicated")
            {
                if (!internalClock) clockSource = (string)Environment.Environs.Hardware.GetInfo("PGClockLine");
                else clockSource = "";
            }

            if ((string)Environs.Hardware.GetInfo("PGType") == "integrated")
            {
                // clocking is more complicated for the 6229 style PG boards as they don't have their own internal clock.

                // if external clocking is required it's easy:
                if (!internalClock) clockSource = (string)Environment.Environs.Hardware.GetInfo("PGClockLine");
                else
                {
                    // if an internal clock is requested we generate it using the card's timer/counters.
                    counterTask = new Task();
                    counterTask.COChannels.CreatePulseChannelFrequency(
                        device + (string)Environs.Hardware.GetInfo("PGClockCounter"),
                        "PG Clock",
                        COPulseFrequencyUnits.Hertz,
                        COPulseIdleState.Low,
                        0.0,
                        clockFrequency,
                        0.5
                        );
                    counterTask.Timing.SampleQuantityMode = SampleQuantityMode.ContinuousSamples;
                    counterTask.Start();

                    clockSource = device + (string)Environs.Hardware.GetInfo("PGClockCounter") + "InternalOutput";
                }
            }

            /**** Configure regeneration ****/

            SampleQuantityMode sqm;
            if (loop)
            {
                sqm = SampleQuantityMode.ContinuousSamples;
                pgTask.Stream.WriteRegenerationMode = WriteRegenerationMode.AllowRegeneration;

            }
            else
            {
                sqm = SampleQuantityMode.FiniteSamples;
                pgTask.Stream.WriteRegenerationMode = WriteRegenerationMode.DoNotAllowRegeneration;

            }

            pgTask.Timing.ConfigureSampleClock(
                clockSource,
                clockFrequency,
                SampleClockActiveEdge.Rising,
                sqm,
                length
                );

            /**** Configure buffering ****/

            if ((string)Environs.Hardware.GetInfo("PGType") == "dedicated")
            {
                // these lines are critical - without them DAQMx copies the data you provide
                // as many times as it can into the on board FIFO (the cited reason being stability).
                // This has the annoying side effect that you have to wait for the on board buffer
                // to stream out before you can update the patterns - this takes ~6 seconds at 1MHz.
                // These lines tell the board and the software to use buffers as close to the size of
                // the PatternList as possible (on board buffer size is coerced to be related to a power of
                // two, so you don't quite get what you ask for).
                // note that 6229 type integrated PGs only have 2kB buffer, so this isn't needed for them (or allowed, in fact)
                pgTask.Stream.Buffer.OutputBufferSize = length;
                pgTask.Stream.Buffer.OutputOnBoardBufferSize = length;
            }

            /**** Configure triggering ****/
            if (triggered)
            {
                pgTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                    (string)Environs.Hardware.GetInfo("PGTrigger"),
                    DigitalEdgeStartTriggerEdge.Rising);
            }

            /**** Write configuration to board ****/

            pgTask.Control(TaskAction.Commit);
            writer = new DigitalSingleChannelWriter(pgTask.Stream);
        }