Ejemplo n.º 1
0
        public void UpdateListening()
        {
            if (Recording)
            {
                return;
            }

            var inputPorts  = Ports.OfType <NidaQmxChannel>().Where(p => p.Direction == ChannelDirection.Input && p.Status == DevicePortStatus.Active);
            var outputPorts = Ports.OfType <NidaQmxChannel>().Where(p => p.Direction == ChannelDirection.Output && p.Status == DevicePortStatus.Active);

            _listeningPorts = inputPorts.Concat(outputPorts).ToList();
            if (_listeningPorts.Count == 0)
            {
                return;
            }

            double maxMultiChannelRate;
            var    result = NidaQmxHelper.DAQmxGetDevAIMaxMultiChanRate(Name, out maxMultiChannelRate);

            if (result < 0)
            {
                OnError?.Invoke(this, new DeviceErrorArgs(NidaQmxHelper.GetError(result)));
                return;
            }

            SamplerateInput        = (int)(maxMultiChannelRate / inputPorts.Count());
            SamplesPerChannelInput = (int)(10000.0 * Math.Floor(SamplerateInput / 20.0 / 10000.0));

            foreach (var port in inputPorts)
            {
                port.Samplerate = SamplerateInput;
            }
        }
Ejemplo n.º 2
0
        public bool Stop()
        {
            if (!Recording)
            {
                return(false);
            }

            _stopThread = true;
            if (_pollThread != null && Thread.CurrentThread != _pollThread)
            {
                _pollThread.Join();
            }

            Console.WriteLine("Stop call von Thread " + Thread.CurrentThread.ManagedThreadId);
            var resultStopTask = NidaQmxHelper.DAQmxStopTask(_device.InputTaskHandle);

            if (resultStopTask < 0)
            {
                _device.ReportError(new DeviceErrorArgs(NidaQmxHelper.GetError(resultStopTask)));
            }

            Marshal.FreeHGlobal(Data);
            Data = IntPtr.Zero;

            Recording = false;

            return(true);
        }
Ejemplo n.º 3
0
        private bool RunTask(InOutPortFlags flags)
        {
            if (flags.HasFlag(InOutPortFlags.UseInput))
            {
                var result = NidaQmxHelper.DAQmxStartTask(_device.InputTaskHandle);
                if (result < 0)
                {
                    NidaQmxHelper.DAQmxClearTask(_device.InputTaskHandle);
                    _device.ReportError(new DeviceErrorArgs(NidaQmxHelper.GetError(result)));
                    return(false);
                }
            }

            //if (flags.HasFlag(InOutPortFlags.UseOutput)) {
            //    var result = NidaQmxHelper.DAQmxStartTask(_device.OutputTaskHandle);
            //    if (result < 0) {
            //        NidaQmxHelper.DAQmxStopTask(_device.InputTaskHandle);
            //        NidaQmxHelper.DAQmxClearTask(_device.InputTaskHandle);
            //        NidaQmxHelper.DAQmxClearTask(_device.OutputTaskHandle);
            //        _device.ReportError(new DeviceErrorArgs(NidaQmxHelper.GetError(result)));
            //        return false;
            //    }
            //}

            return(true);
        }
Ejemplo n.º 4
0
        public void Write(double[] data, int offset, int samples)
        {
            int written;

            Device.OutputBuffer.Write(ChannelNumber, data, offset, samples);

            if (Device.OutputBuffer.BufferReady)
            {
                unsafe
                {
                    fixed(double *ptr = Device.OutputBuffer.CurrentBuffer.Data)
                    {
                        var result = NidaQmxHelper.DAQmxWriteAnalogF64(
                            taskHandle:             Device.OutputTaskHandle,
                            numSampsPerChan:        Device.OutputBuffer.CurrentBuffer.SamplesPerChannel,
                            autoStart:              1,
                            timeout:                10,
                            dataLayout:             NidaQmxHelper.DaQmxValGroupByChannel,
                            writeArray:             new IntPtr(ptr),
                            sampsPerChanWritten:    out written,
                            reserved:               IntPtr.Zero
                            );

                        if (result < 0)
                        {
                            Device.ReportError(new DeviceErrorArgs(NidaQmxHelper.GetError(result)));
                        }
                    }
                }

                Device.OutputBuffer.MoveToNextBuffer();
            }
        }
Ejemplo n.º 5
0
        public void DestroyTask()
        {
            if (TaskHandle != 0)  //throw new InvalidOperationException("Task not yet created. First create a task");
            {
                NidaQmxHelper.DAQmxClearTask(TaskHandle);
                TaskHandle = 0;
            }

            SamplesPerChannel = 0;
            _nodes.Clear();
            State = SessionTaskState.None;
        }
Ejemplo n.º 6
0
        private bool ConfigureDevClock(InOutPortFlags flags)
        {
            if (flags.HasFlag(InOutPortFlags.UseInput))
            {
                var result = NidaQmxHelper.DAQmxCfgSampClkTiming(
                    activeEdge: NidaQmxHelper.DaQmxValRising,
                    sampleMode: NidaQmxHelper.DaQmxValContSamps,
                    sampsPerChan: (ulong)_device.SamplesPerChannelInput,
                    taskHandle: _device.InputTaskHandle,
                    source: "",
                    rate: _device.SamplerateInput
                    );

                if (result < 0)
                {
                    NidaQmxHelper.DAQmxClearTask(_device.InputTaskHandle);
                    _device.ReportError(new DeviceErrorArgs(NidaQmxHelper.GetError(result)));
                    return(false);
                }
            }

            if (flags.HasFlag(InOutPortFlags.UseOutput))
            {
                var result = NidaQmxHelper.DAQmxCfgSampClkTiming(
                    activeEdge: NidaQmxHelper.DaQmxValRising,
                    sampleMode: NidaQmxHelper.DaQmxValContSamps,
                    sampsPerChan: (ulong)_device.SamplesPerChannelOutput,
                    taskHandle: _device.OutputTaskHandle,
                    source: "",
                    rate: _device.SamplerateOutput
                    );

                if (result < 0)
                {
                    NidaQmxHelper.DAQmxClearTask(_device.InputTaskHandle);
                    NidaQmxHelper.DAQmxClearTask(_device.OutputTaskHandle);
                    _device.ReportError(new DeviceErrorArgs(NidaQmxHelper.GetError(result)));
                    return(false);
                }

                result = NidaQmxHelper.DAQmxCfgOutputBuffer(_device.OutputTaskHandle, _device.SamplesPerChannelOutput);
                if (result < 0)
                {
                    NidaQmxHelper.DAQmxClearTask(_device.InputTaskHandle);
                    NidaQmxHelper.DAQmxClearTask(_device.OutputTaskHandle);
                    _device.ReportError(new DeviceErrorArgs(NidaQmxHelper.GetError(result)));
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 7
0
 private void CleanupAndThrow(int code)
 {
     NidaQmxHelper.DAQmxClearTask(TaskHandle);
     TaskHandle        = 0;
     SamplesPerChannel = 0;
     _nodes.Clear();
     State = SessionTaskState.None;
     if (_counter != null)
     {
         _counter.Dispose();
     }
     throw new NidaqException(code);
 }
Ejemplo n.º 8
0
        public void StopSampling()
        {
            if (!Recording)
            {
                return;
            }

            NidaQmx2Singleton.Instance.Stop();
            NidaQmxHelper.DAQmxClearTask(InputTaskHandle);
            NidaQmxHelper.DAQmxClearTask(OutputTaskHandle);
            CreateTaskHandle();

            Recording = false;
        }
Ejemplo n.º 9
0
        public SettingsDigitalOut(NidaqSingleton.Device dev, string clockPath, int bufferLength, int prebufferLength)
        {
            InitializeComponent();
            numericUpDownBufferLength.Value    = bufferLength;
            numericUpDownPreBufferLength.Value = prebufferLength;
            comboBoxClockSource.Text           = clockPath;

            var terms  = new StringBuilder(10000);
            var result = NidaQmxHelper.DAQmxGetDevTerminals(dev.Name, terms, terms.Capacity - 1);

            if (result >= 0)
            {
                comboBoxClockSource.Items.AddRange(terms.ToString().Split(','));
            }
        }
Ejemplo n.º 10
0
        public SettingsDigitalIn(NidaqSingleton.Device dev, NidaqSessionDigitalIn.ClockSource clockSrc, string clockPath, int clockRate)
        {
            InitializeComponent();
            comboBoxClock.DataSource   = Enum.GetValues(typeof(NidaqSessionDigitalIn.ClockSource));
            comboBoxClock.SelectedItem = clockSrc;
            comboBoxClockSource.Text   = clockPath;
            textBoxClockRate.Text      = clockRate.ToString();

            var terms  = new StringBuilder(10000);
            var result = NidaQmxHelper.DAQmxGetDevTerminals(dev.Name, terms, terms.Capacity - 1);

            if (result >= 0)
            {
                comboBoxClockSource.Items.AddRange(terms.ToString().Split(','));
            }
        }
Ejemplo n.º 11
0
        public void Stop()
        {
            if (TaskHandle == 0)
            {
                throw new InvalidOperationException("Task not yet created. First create a task");
            }

            var result = NidaQmxHelper.DAQmxStopTask(TaskHandle);

            if (result < 0)
            {
                CleanupAndThrow(result, false);
            }

            State = SessionTaskState.Stopped;
        }
Ejemplo n.º 12
0
        public void DestroyTask()
        {
            if (TaskHandle == 0)
            {
                throw new InvalidOperationException("Task not yet created. First create a task");
            }

            NidaQmxHelper.DAQmxClearTask(TaskHandle);
            TaskHandle        = 0;
            SamplesPerChannel = 0;
            _nodes.Clear();
            if (_counter != null)
            {
                _counter.Dispose();
            }
            State = SessionTaskState.None;
        }
Ejemplo n.º 13
0
        private string[] GetDeviceNames()
        {
            var buffer = new StringBuilder(256 + 1);
            var result = NidaQmxHelper.DAQmxGetSysDevNames(buffer, buffer.Length - 1);

            if (result < 0)
            {
                throw new SystemException("Could not query nidaq device list");
            }

            if (buffer.ToString().Length > 0)
            {
                return(buffer.ToString()
                       .Split(',')
                       .Select(s => s.Trim()).ToArray());
            }

            return(null);
        }
Ejemplo n.º 14
0
        private void EveryNCallback()
        {
            var hPoll = start_polling(_device.InputTaskHandle, _device.SamplesPerChannelInput * _device.ListeningPorts.Count(), _device.SamplesPerChannelInput);

            while (!_stopThread)
            {
                var result = read_buffer(hPoll, Data, 8 * (_device.SamplesPerChannelInput * _device.ListeningPorts.Count()));
                switch (result)
                {
                case 2:
                    // queue empty, ignore
                    Thread.Sleep(1);
                    break;

                case 1:
                    _device.ReportError(new DeviceErrorArgs("Buffer too small"));
                    _stopThread = true;
                    break;

                case 0:
                    var channelData = Data;

                    // this can not be a foreach loop because listeningPorts may change.
                    // For example when there is a buffering problem and listeningPorts is cleared
                    foreach (var port in _device.ListeningPorts.OfType <NidaQmxChannelInput>())
                    {
                        port.DistributeData(channelData, _device.SamplesPerChannelInput);
                        channelData = IntPtr.Add(channelData, sizeof(double) * _device.SamplesPerChannelInput);
                    }

                    break;

                default:
                    // read error
                    _device.ReportError(new DeviceErrorArgs(NidaQmxHelper.GetError(result)));
                    _stopThread = true;
                    break;
                }
            }

            stop_polling(hPoll);
        }
Ejemplo n.º 15
0
        private void CleanupAndThrow(int code, bool doThrow = true)
        {
            NidaQmxHelper.DAQmxClearTask(TaskHandle);
            TaskHandle        = 0;
            SamplesPerChannel = 0;
            _nodes.Clear();
            State = SessionTaskState.None;

            if (doThrow)
            {
                throw new NidaqException(code);
            }
            else
            {
                Parent.SessionGraph.Context.Notify(
                    new NodeSystemLib2.Generic.GraphNotification(
                        NodeSystemLib2.Generic.GraphNotification.NotificationType.Error,
                        NidaQmxHelper.GetError(code)
                        )
                    );
            }
        }
Ejemplo n.º 16
0
        public void Stop()
        {
            if (TaskHandle == 0)
            {
                throw new InvalidOperationException("Task not yet created. First create a task");
            }

            var result = NidaQmxHelper.DAQmxStopTask(TaskHandle);

            if (result < 0)
            {
                CleanupAndThrow(result);
            }

            try {
                _counter.Stop();
            } catch (NationalInstruments.DAQmx.DaqException e) {
                CleanupAndThrow(e.Error);
            }

            State = SessionTaskState.Stopped;
        }
Ejemplo n.º 17
0
        private bool CreateTaskHandle()
        {
            int[] taskHandle = new int[1];
            var   result     = NidaQmxHelper.DAQmxCreateTask(null, taskHandle);

            if (result < 0)
            {
                OnError?.Invoke(this, new DeviceErrorArgs("Could not create input nidaq task"));
                return(false);
            }
            InputTaskHandle = taskHandle[0];

            result = NidaQmxHelper.DAQmxCreateTask(null, taskHandle);
            if (result < 0)
            {
                OnError?.Invoke(this, new DeviceErrorArgs("Could not create output nidaq task"));
                return(false);
            }
            OutputTaskHandle = taskHandle[0];

            return(true);
        }
Ejemplo n.º 18
0
        public List <IDevice> CreateDevices()
        {
            var buffer = new StringBuilder(256 + 1);
            var result = NidaQmxHelper.DAQmxGetSysDevNames(buffer, buffer.Length - 1);

            if (result < 0)
            {
                throw new SystemException("Could not query nidaq device list");
            }

            if (buffer.ToString().Length > 0)
            {
                return(buffer.ToString()
                       .Split(',')
                       .Select(s => s.Trim())
                       .Select(s => new NidaQmxDevice2(s, _gen))
                       .ToList <IDevice>());
            }
            else
            {
                return(new List <IDevice>());
            }
        }
Ejemplo n.º 19
0
        private void ProcessInputData(IReadOnlyList <INidaqMetric> listeningPorts, NILoop.HandleInfo taskInfo, IntPtr buffer, int sample_size_bytes, int hPoll)
        {
            var result = NILoop.read_buffer(hPoll, taskInfo.handle, buffer, sample_size_bytes * (taskInfo.samples_per_chan * listeningPorts.Count));

            switch (result)
            {
            case 3:
            case 1:
                // task not found
                SessionGraph.AsyncEmergencyStop(null);
                _stopThread = true;
                break;

            case 2:
                // queue empty, ignore
                Thread.Sleep(1);
                break;

            case 0:
                var channelData = buffer;

                foreach (var port in listeningPorts)
                {
                    ((IMetricInput)port).DistributeData(channelData, taskInfo.samples_per_chan);
                    channelData = IntPtr.Add(channelData, sample_size_bytes * taskInfo.samples_per_chan);
                }

                break;

            default:
                // read error
                System.Diagnostics.Debug.WriteLine(NidaQmxHelper.GetError(result));
                SessionGraph.AsyncEmergencyStop(null);
                _stopThread = true;
                break;
            }
        }
Ejemplo n.º 20
0
        public NidaQmxDevice2(string device, IIDGenerator idgen)
        {
            Name = device;

            var bufferInputChannelNames = new StringBuilder(256 + 1);
            var resultQueryAI           = NidaQmxHelper.DAQmxGetDevAIPhysicalChans(device, bufferInputChannelNames, bufferInputChannelNames.Length - 1);

            if (resultQueryAI < 0)
            {
                throw new SystemException("Could not query input channels for nidaq device " + device);
            }

            var bufferOutputChannelNames = new StringBuilder(256 + 1);
            var resultQueryAO            = NidaQmxHelper.DAQmxGetDevAOPhysicalChans(device, bufferOutputChannelNames, bufferOutputChannelNames.Length - 1);

            if (resultQueryAO < 0)
            {
                throw new SystemException("Could not query input channels for nidaq device " + device);
            }

            var ai = bufferInputChannelNames.ToString()
                     .Split(',')
                     .Select(s => (NidaQmxChannel) new NidaQmxChannelInput(this, s.Trim(), idgen));

            var ao = bufferOutputChannelNames.ToString()
                     .Split(',')
                     .Select(s => (NidaQmxChannel) new NidaQmxChannelOutput(this, s.Trim(), idgen));

            _channels = ai.Concat(ao).ToList();

            if (!CreateTaskHandle())
            {
                throw new SystemException("Could not acquire nidaq task handle");
            }

            Id = idgen.GetID();
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Creates a new DAQmx task and adds channels to it
        /// </summary>
        /// <param name="nodes">Graph nodes of type MetricAnalogInput</param>
        /// <exception cref="InvalidCastException">At least one element in <paramref name="nodes"/> not of type MetricAnalogInput</exception>
        /// <exception cref="InvalidOperationException">At least one element in <paramref name="nodes"/> not connected to the instance's specified device or task already created</exception>
        /// <exception cref="NidaqException">Task or channel could not be created</exception>
        public void CreateTask(IEnumerable <INidaqMetric> nodes)
        {
            if (TaskHandle != 0)
            {
                throw new InvalidOperationException("Task already created. First destroy the old task");
            }

            if (!nodes.All(n => n is MetricAnalogInput))
            {
                throw new InvalidCastException("all passed nodes must be of type MetricAnalogInput");
            }

            if (!nodes.All(n => n.Channel.Device == Device))
            {
                throw new InvalidOperationException("not all passed nodes are connected to device " + Device.Name);
            }

            foreach (var node in nodes.OfType <MetricAnalogInput>())
            {
                node.Samplerate = ClockRate;
            }

            // 1. create task
            var taskHandle = new int[1];
            var result     = NidaQmxHelper.DAQmxCreateTask(null, taskHandle);

            if (result < 0)
            {
                throw new NidaqException(result);
            }
            TaskHandle = taskHandle[0];

            // 2. create channels
            foreach (var input in nodes.OfType <MetricAnalogInput>())
            {
                result = NidaQmxHelper.DAQmxCreateAIVoltageChan(
                    maxVal:                 input.VMax,
                    minVal:                 input.VMin,
                    units:                  NidaQmxHelper.DaQmxValVolts,
                    terminalConfig:         (int)input.TerminalConfig,
                    physicalChannel:        input.Channel.Path,
                    taskHandle:             TaskHandle,
                    nameToAssignToChannel:  null,
                    customScaleName:        null
                    );
                if (result < 0)
                {
                    CleanupAndThrow(result);
                }
                _nodes.Add(input);
            }

            // 3. configure clock
            SamplesPerChannel = ClockRate / 5;
            result            = NidaQmxHelper.DAQmxCfgSampClkTiming(
                activeEdge:                 NidaQmxHelper.DaQmxValRising,
                sampleMode:                 NidaQmxHelper.DaQmxValContSamps,
                sampsPerChan:               (ulong)SamplesPerChannel,
                taskHandle:                 TaskHandle,
                source:                     "",
                rate:                       ClockRate
                );
            if (result < 0)
            {
                CleanupAndThrow(result);
            }

            State = SessionTaskState.Stopped;
        }
Ejemplo n.º 22
0
        private bool CreateVirtualChannel(InOutPortFlags flags)
        {
            // ------------------------------------

            if (flags.HasFlag(InOutPortFlags.UseInput))
            {
                var inputs = _device.ListeningPorts.Where(port => port.Direction == ChannelDirection.Input)
                             .Select(port => port.Name);

                if (inputs.Any())
                {
                    var inputPortStrings = string.Join(",", inputs);

                    var result = NidaQmxHelper.DAQmxCreateAIVoltageChan(
                        maxVal:                 10.0,
                        minVal:                 -10.0,
                        units:                  NidaQmxHelper.DaQmxValVolts,
                        terminalConfig:         NidaQmxHelper.DaQmxValRse,
                        physicalChannel:        inputPortStrings,
                        taskHandle:             _device.InputTaskHandle,
                        nameToAssignToChannel:  "chanI" + _device.Name,
                        customScaleName:        null
                        );

                    if (result < 0)
                    {
                        NidaQmxHelper.DAQmxClearTask(_device.InputTaskHandle);
                        _device.ReportError(new DeviceErrorArgs(NidaQmxHelper.GetError(result)));
                        return(false);
                    }
                }
            }

            // ------------------------------------

            if (flags.HasFlag(InOutPortFlags.UseOutput))
            {
                var outputs = _device.ListeningPorts.Where(port => port.Direction == ChannelDirection.Output)
                              .Select(port => port.Name);

                if (outputs.Any())
                {
                    var outputPortStrings = string.Join(",", outputs);

                    var channelNumber = 0;
                    foreach (var output in _device.ListeningPorts.Where(port => port.Direction == ChannelDirection.Output))
                    {
                        ((NidaQmxChannelOutput)output).ChannelNumber = channelNumber++;
                    }

                    var result = NidaQmxHelper.DAQmxCreateAOVoltageChan(
                        maxVal: 10.0,
                        minVal: -10.0,
                        units: NidaQmxHelper.DaQmxValVolts,
                        physicalChannel: outputPortStrings,
                        taskHandle: _device.OutputTaskHandle,
                        nameToAssignToChannel: "chanO" + _device.Name,
                        customScaleName: null
                        );

                    if (result < 0)
                    {
                        NidaQmxHelper.DAQmxClearTask(_device.OutputTaskHandle);
                        _device.ReportError(new DeviceErrorArgs(NidaQmxHelper.GetError(result)));
                        return(false);
                    }
                }
            }

            // ------------------------------------

            return(true);
        }
Ejemplo n.º 23
0
        public void CreateTask(IEnumerable <INidaqMetric> nodes)
        {
            if (TaskHandle != 0)
            {
                throw new InvalidOperationException("Task already created. First destroy the old task or task already created");
            }

            if (!nodes.All(n => n is MetricDigitalInput))
            {
                throw new InvalidCastException("all passed nodes must be of type MetricDigitalInput");
            }

            if (!nodes.All(n => n.Channel.Device == Device))
            {
                throw new InvalidOperationException("not all passed nodes are connected to device " + Device.Name);
            }

            // 1. create task
            if (Source == ClockSource.Intern)
            {
                _counter = new NidaqCounterOutput(Device.Name + "/ctr0", ClockRate);
            }

            var taskHandle = new int[1];
            var result     = NidaQmxHelper.DAQmxCreateTask(null, taskHandle);

            if (result < 0)
            {
                throw new NidaqException(result);
            }
            TaskHandle = taskHandle[0];

            // 2. create channels
            foreach (var input in nodes.OfType <MetricDigitalInput>())
            {
                result = NidaQmxHelper.DAQmxCreateDIChan(
                    lines: input.Channel.Path,
                    taskHandle: TaskHandle,
                    lineGrouping: NidaQmxHelper.DAQmx_Val_ChanForAllLines,
                    nameToAssignToChannel: null
                    );
                if (result < 0)
                {
                    CleanupAndThrow(result);
                }
                _nodes.Add(input);
            }

            // 3. configure clock
            SamplesPerChannel = ClockRate / 10;
            result            = NidaQmxHelper.DAQmxCfgSampClkTiming(
                activeEdge: NidaQmxHelper.DaQmxValRising,
                sampleMode: NidaQmxHelper.DaQmxValContSamps,
                sampsPerChan: (ulong)SamplesPerChannel,
                taskHandle: TaskHandle,
                source: (this.Source == ClockSource.Intern) ? ("/" + Device.Name + "/Ctr0InternalOutput") : ClockPath,
                rate: ClockRate
                );
            if (result < 0)
            {
                CleanupAndThrow(result);
            }

            State = SessionTaskState.Stopped;
        }
Ejemplo n.º 24
0
 public NidaqException(int code) : base(NidaQmxHelper.GetError(code))
 {
 }