Example #1
0
 public Task(IDataBindEngineClient c, TaskOps o, Task previousForClient)
 {
     client = c;
     op = o;
     PreviousForClient = previousForClient;
     status = Status.Pending;
 }
Example #2
0
        /// <summary>
        /// Start a constant output by the DAQ device. This function starts a task named "OutputTask",
        /// Don't forget to stop it when it's no longer needed.
        /// </summary>
        /// <param name="voltage">the requested voltage to apply</param>
        public void StartConstantOutputTask(double voltage)
        {
            int samplesPerChannel = 2500;
            int sampleRate = 2500;

            //
            // generate output array 
            //
            m_functionGenerator = new FunctionGenerator(samplesPerChannel, voltage, voltage);
            
            //
            // get the properties required for the output task
            //
            ContinuousAOTaskProperties outputProperties = new ContinuousAOTaskProperties(null, sampleRate, samplesPerChannel, voltage);
            
            //
            // create the output task
            //
            m_outputTask = m_daqController.CreateContinuousAOTask(outputProperties);

            //
            // create the writer of the output task
            //
            writer = new AnalogSingleChannelWriter(m_outputTask.Stream);

            //
            // write static voltage
            //
            writer.WriteMultiSample(true, m_functionGenerator.ConstWave);
        }
Example #3
0
 /*
  * Delete a Task
  *
  * @param: TaskDeleted : a callback
  * @param: tasklist : string
  * @param: t : Task
  */
 public void DeleteTask(Action<IRestResponse<Error>> TaskDeleted, string tasklist, Task t)
 {
     _oAuth.GetAccessCode(access_token =>
     {
         lock (_sync)
         {
             _requesting++;
             // building request
             _client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(access_token);
             var request = new RestRequest("/tasks/v1/lists/" + tasklist + "/tasks/" + t.Id, Method.DELETE);
             // serialize Task
             string taskJson = JsonConvert.SerializeObject(t, Formatting.None,
                 new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
             request.AddParameter("application/json; charset=utf-8", taskJson, ParameterType.RequestBody);
             LaunchTimer();
             _client.ExecuteAsync<Error>(request, response =>
             {
                 lock (_sync)
                 {
                     _requesting--;
                     // handle request's callback
                     ObservableCollection<Task> tasks = null;
                     _tasks.TryGetValue(tasklist, out tasks);
                     if (tasks != null && response.StatusCode == HttpStatusCode.NoContent && response.Data == null)
                     {
                         // delete the task
                         tasks.Remove(t);
                     }
                     if (TaskDeleted != null) TaskDeleted(response);
                 }
             });
         }
     });
 }
Example #4
0
        public async System.Threading.Tasks.Task TestCreateNewTask()
        {
            UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets
                {
                    ClientId = _clientId,
                    ClientSecret = _clientSecret
                },
                new[] { TasksService.Scope.Tasks },
                "user",
                CancellationToken.None);

            var service = new TasksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = _application
            });

            TaskLists lists = await service.Tasklists.List().ExecuteAsync();
            Assert.IsTrue(lists.Items.Count > 0);
            string listId = lists.Items[0].Id;

            Task newTask = new Task()
            {
                Title = "Test",   
            };

            Task result = await service.Tasks.Insert(newTask, listId).ExecuteAsync();
            Assert.AreEqual(newTask.Title, result.Title);
        }
 public override void AcquisitionStarting()
 {
     // initialise the output hardware
     outputTask = new Task("analog output");
     if (!Environs.Debug)
     {
         AnalogOutputChannel oc =
             (AnalogOutputChannel) Environs.Hardware.AnalogOutputChannels[(string)settings["channel"]];
         oc.AddToTask(outputTask, oc.RangeLow, oc.RangeHigh);
         writer = new AnalogSingleChannelWriter(outputTask.Stream);
         writer.WriteSingleSample(true, 0);
     }
     scanParameter = 0;
     //go gently to the correct start position
     if ((string)settings["scanMode"] == "up" || (string)settings["scanMode"] == "updown")
     {
         if ((string)settings["flyback"] == "overshoot") rampOutputToVoltage((double)settings["overshootVoltage"]);
         rampOutputToVoltage((double)settings["start"]);
     }
     if ((string)settings["scanMode"] == "down" || (string)settings["scanMode"] == "downup")
     {
         if ((string)settings["flyback"] == "overshoot") rampOutputToVoltage((double)settings["overshootVoltage"]);
         rampOutputToVoltage((double)settings["end"]);
     }
 }
 private static void PerformTask(Task t)
 {
     CurrentTaskId++;
     int tid = CurrentTaskId;
     try
     {
         Thread.BeginCriticalRegion(); // It is important that this task not be stopped here
         MinecraftModUpdater.Logger.Log(Logger.Level.Debug, "Running Task Id: " + tid.ToString());
         if (t != null)
         {
             t.Invoke();
             MinecraftModUpdater.Logger.Log(Logger.Level.Debug, "Task " + tid.ToString() + " Done");
         }
     }
     catch (Exception e)
     {
         MinecraftModUpdater.Logger.Log(Logger.Level.Error, "Error on task " + tid.ToString());
         MinecraftModUpdater.Logger.Log(e);
         MCModUpdaterExceptionHandler.HandleException(t, e);
     }
     finally
     {
         Thread.EndCriticalRegion(); // Thread can now be stopped.
     }
 }
        /// <summary>
        /// Gets all tasks from ProjectFile instance.
        /// </summary>
        /// <param name="projectFile">ProjectFile instance.</param>
        /// <returns>List of tasks.</returns>
        protected Task[] getAllProjectTasks(ProjectFile projectFile)
        {
            //get tasks
            java.util.List taskList = projectFile.AllTasks;

            //convert to array
            object[] allTaskObjs = taskList.toArray();

            //create alternate storage
            Task[] allTasks = new Task[allTaskObjs.Length];

            //then cast each object to a Task
            for(int o = 0; o < allTaskObjs.Length; o++)
            {
                //cast
                allTasks[o] = (Task)allTaskObjs[o];
                //then nullify the initial value, be nice to your memory and it WILL return the favor
                allTaskObjs[o] = null;
            }

            //nullify primary storage
            allTaskObjs = null;

            //then return the secondary list, otherwise permit a run-time exception
            //this is a wild bunch of magic anyways
            return allTasks;
        }
        //AND CAVITY VOLTAGE!!!
        //The photodiode inputs have been bundled into one task. We never read one photodiode without reading
        //the other.
        public void ConfigureReadAI(int numberOfMeasurements, bool autostart)
        {
            readAIsTask = new Task("readAI");

            channels = new Dictionary<string, AnalogInputChannel>();
            foreach (string s in analogInputs)
            {
                AnalogInputChannel channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[s];
                channels.Add(s, channel);
            }

            foreach (KeyValuePair<string, AnalogInputChannel> pair in channels)
            {
                pair.Value.AddToTask(readAIsTask, 0, 10);
            }

            if (autostart == false)
            {
                 readAIsTask.Timing.ConfigureSampleClock(
                    "",
                    40000,
                    SampleClockActiveEdge.Rising,
                    SampleQuantityMode.FiniteSamples, numberOfMeasurements);
                readAIsTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                    (string)Environs.Hardware.GetInfo(trigger),
                    DigitalEdgeStartTriggerEdge.Rising);
            }
            readAIsTask.Control(TaskAction.Verify);
            analogReader = new AnalogMultiChannelReader(readAIsTask.Stream);
        }
Example #9
0
        public void Read()
        {
            try {
                string[] channelNameList = DaqSystem.Local.GetPhysicalChannels(PhysicalChannelTypes.AI, PhysicalChannelAccess.External);
                if (channelNameList.Length > 0) {
                    Task task = new Task();
                    task.AIChannels.CreateVoltageChannel(channelNameList[0], "Voltage", AITerminalConfiguration.Differential, 0.0, 10.0, AIVoltageUnits.Volts);
                    task.Timing.ConfigureSampleClock("", 100000, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                    task.Control(TaskAction.Verify);

                    AnalogSingleChannelReader airead = new AnalogSingleChannelReader(task.Stream);
                    AnalogWaveform<double> waveform;
                    for(int i=0;i<repeat;i++){
                        waveform = airead.ReadWaveform(sampleRate);
                        datalist.AddRange(waveform.GetRawData());
                        Console.Out.WriteLine("Acquire " + i + "th try");
                    }
                    StreamWriter writer = new StreamWriter(File.Open("ai.txt", FileMode.Create));
                    int c = 0;
                    foreach (double d in datalist) {
                        writer.WriteLine(String.Format("{0} {1}",c,d));
                        c++;
                    }
                    writer.Close();
                }
            } catch (DaqException e) {
                Console.Out.WriteLine(e.Message);
            }
        }
Example #10
0
 public async System.Threading.Tasks.Task<Task> CreateTaskAsync(Task task, string listId)
 {
     if (_service == null)
     {
         throw new Exception("Service is not initialized");
     }
     return await _service.Tasks.Insert(task, listId).ExecuteAsync();
 }
 		public void Post(Task task)
		{
			lock (((ICollection)queue).SyncRoot)
			{
				queue.Add(task);
				newItemEvent.Set();
			}
		}
Example #12
0
        public void Enqueue(Action action)
        {
            var task = new Task
            {
                TaskWithoutState = action
            };

            queue.Enqueue(task);
        }
Example #13
0
        static void Main(string[] args)
        {
            Task task =new Task();
            Thread thread = new Thread(task.DoWork);
            thread.Start(1000);
            thread.Join();
            Console.WriteLine("Summ ={0}",task.Summ);

        }
 public void ConfigureCavityScan(int numberOfSteps, bool autostart)
 {
     outputCavityTask = new Task("CavityPiezoVoltage");
     cavityChannel =
                 (AnalogOutputChannel)Environs.Hardware.AnalogOutputChannels[cavityChannelName];
     cavityChannel.AddToTask(outputCavityTask, 0, 10);
     outputCavityTask.Control(TaskAction.Verify);
     cavityWriter = new AnalogSingleChannelWriter(outputCavityTask.Stream);
 }
Example #15
0
 public PooledTaskRunner(Task task, int maxIterationsPerRun)
 {
     this.maxIterationsPerRun = maxIterationsPerRun;
     this.task = task;
     this._shutdown = false;
     this.iterating = false;
     this.queued = true;
     ThreadPool.QueueUserWorkItem(new WaitCallback(Run), this);
 }
Example #16
0
        public MainClass ()
        {
            



            task = new Task (this);
            t = new Timer (task.go, null, 1000, 1000);
        }
Example #17
0
 public void Enqueue(WaitCallback waitCallback, object state, AsyncTaskResultCallback resultCallback)
 {
     var task = new Task
     {
         WaitCallback = waitCallback,
         State = state,
         ResultCallback = resultCallback
     };
     lock (taskQueue) taskQueue.Enqueue(task);
 }
Example #18
0
        public void Enqueue(Action<object> action, object state)
        {
            var task = new Task
            {
                TaskWithState = action,
                State = state
            };

            queue.Enqueue(task);
        }
 //The photodiode inputs have been bundled into one task. We never read one photodiode without reading
 //the other.
 public void ConfigureReadPhotodiodes(int numberOfMeasurements, bool autostart)
 {
     readPhotodiodesTask = new Task("ReadPhotodiodes");
     referenceLaserChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[masterPDChannelName];
     lockingLaserChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[slavePDChannelName];
     referenceLaserChannel.AddToTask(readPhotodiodesTask, 0, 10);
     lockingLaserChannel.AddToTask(readPhotodiodesTask, 0, 10);
     readPhotodiodesTask.Control(TaskAction.Verify);
     photodiodesReader = new AnalogMultiChannelReader(readPhotodiodesTask.Stream);
 }
Example #20
0
 public override void QueueTask(Task task)
 {
     lock (tasksLock)
        {
     DateTime executionTime = DateTime.Now;
     if (!scheduledTasks.ContainsKey(executionTime))
      scheduledTasks.Add(executionTime, new List<Task>());
     scheduledTasks[executionTime].Add(task);
     schedulerInterrupt.Set();
        }
 }
        internal SpikeFileOutput(string filenameBase, int numChannels, double samplingRate,
            int numSamplesPerWaveform, Task recordingTask, string extension, bool recordingUnits)
        {
            this.numChannels = numChannels;
            this.numSamplesPerWaveform = numSamplesPerWaveform;
            this.recordingUnits = recordingUnits;
            //Create output file
            outStream = createStream(filenameBase + extension, 256 * 1024);

            writeHeader(numChannels, samplingRate, recordingTask);
        }
Example #22
0
		public TaskRunner CreateTaskRunner(Task task, string name, ThreadPriority taskPriority)
		{
            if(this.dedicatedTaskRunner)
            {
                return new DedicatedTaskRunner(task, name, taskPriority);
            }
            else
            {
                return new PooledTaskRunner(task, this.maxIterationsPerRun);
            }
		}
 //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" + laserChannelName);
     laserChannel =
             (AnalogOutputChannel)Environs.Hardware.AnalogOutputChannels[laserChannelName];
     laserChannel.AddToTask(outputLaserTask, laserChannel.RangeLow, laserChannel.RangeHigh);
     outputLaserTask.Control(TaskAction.Verify);
     laserWriter = new AnalogSingleChannelWriter(outputLaserTask.Stream);
     laserWriter.WriteSingleSample(true, voltage);
     //outputLaserTask.Start();
 }
        public DedicatedTaskRunner(Task task)
        {
            if(task == null)
            {
                throw new NullReferenceException("Task was null");
            }

            this.task = task;

            this.theThread = new Thread(Run) {IsBackground = true};
            this.theThread.Start();
        }
Example #25
0
        public void AddTask(Action action, Thread thread, object key)
        {
            Task task = new Task(action, thread, key);

            lock (m_lock)
            {
                // Add the task to the queue
                m_tasks.Enqueue(task);
            }

            // Inform the thread there is something to do
            m_actionPending.Release();
        }
Example #26
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 #27
0
 public void StartJobAsync(Task task, TaskData taskData) {
   try {
     this.TaskId = task.Id;
     originalTaskData = taskData;
     Prepare(task);
     StartTaskInAppDomain(taskData);
   }
   catch (Exception) {
     // make sure to clean up if something went wrong
     DisposeAppDomain();
     throw;
   }
 }
Example #28
0
        public async System.Threading.Tasks.Task<Task> UpdateTaskAsync(Task task, string listId)
        {
            if (_service == null)
            {
                throw new Exception("Service is not initialized");
            }
            if (task.Status.Equals("needsAction"))
            {
                task.Completed = null;
            }

            return await _service.Tasks.Update(task, listId, task.Id).ExecuteAsync();
        }
 internal ClosedLoopOut(NRTask CLE, int fs, DataSrv DatSrv, StimSrv StimSrv, Task buffLoadTask, Logger Debugger, string NRFilePath, bool NRRecording, NeuroRighter NR)
 {
     this.CLE = CLE;
     this.outputSampFreq = fs;
     this.DatSrv = DatSrv;
     this.StimSrv = StimSrv;
     this.useManStimWave = false;
     this.buffLoadTask = buffLoadTask;
     this.Debugger = Debugger;
     this.NRFilePath = NRFilePath;
     this.NRRecording = NRRecording;
     this.NR = NR;
 }
        public void WaitingTask1()
        {
            var cdl = new CountDownLatch(1);
            var task = new Task(cdl);
            var runner = new Thread(task.DoSomething);

            runner.Start();
            Thread.Sleep(600);
            cdl.CountDown();
            runner.Join();

            Assert.IsTrue(task.Elapsed >= 500, "The task should cost more than 500 millis");
            Assert.IsTrue(task.Elapsed <= 700, "The task should cost less than 700 millis");
        }