diff --git a/README.rst b/README.rst index 989c102..6cc013b 100644 --- a/README.rst +++ b/README.rst @@ -37,7 +37,8 @@ Below is the list of instruments included in this plugin Actuators +++++++++ -* **NIDAQmx**: General generation (voltage / current) with National Instrument materials +* **NIDAQmx**: One analog output (voltage / current) of a National Instrument device, set one point at a time +* **NIDAQmx_DO**: One digital output line (0 / 1, or a pulse to trigger an acquisition) * **NIDAQmx_RampOutput**: A quantity driven by an analog output, changed by voltage ramps timed by a counter used as a clock (value = voltage x conversion factor); several axes (x, y, z) can share the clock diff --git a/docs/source/user_guide.rst b/docs/source/user_guide.rst index 8bf87b3..a2d53ff 100644 --- a/docs/source/user_guide.rst +++ b/docs/source/user_guide.rst @@ -19,6 +19,7 @@ This user guide will first explain how to use these plugins, and then detail how user_guide/ai_use user_guide/ramp_output_use user_guide/nidaqmx_viewer_use + user_guide/nidaqmx_actuator_use user_guide/config_files For any other use, you will need to create your own move or viewer based on this plugin. See the :ref:`create_plugin` guide for a detailed procedure. diff --git a/docs/source/user_guide/nidaqmx_actuator_use.rst b/docs/source/user_guide/nidaqmx_actuator_use.rst new file mode 100644 index 0000000..5d23a12 --- /dev/null +++ b/docs/source/user_guide/nidaqmx_actuator_use.rst @@ -0,0 +1,35 @@ +Generic actuators NIDAQmx and NIDAQmx_DO +======================================== + +Two actuators drive **one output** of an NI device: ``NIDAQmx`` (``DAQ_Move_NIDAQmx``), an analog output (a level in +volts or amperes), and ``NIDAQmx_DO`` (``DAQ_Move_NIDAQmx_DO``), a digital line (0 or 1). They set the output to a value +on demand, one point at a time: there is no clock and no waveform (for voltage ramps, see ``NIDAQmx_RampOutput``). To +drive several outputs, use one actuator for each. The analog one has the *Simple* user interface (a value and a button); +the digital one has the *Binary* interface (one button for each level). + +How to use it +------------- + +1. Choose the **Output** in the list: the analog outputs (``Dev1/ao0``) of the computer for ``NIDAQmx``, the digital + lines (``Dev1/port0/line0``) for ``NIDAQmx_DO``. +2. For an analog output, choose the **Type** (``voltage`` or ``current``) and the range of the output (**Min** and + **Max**, in V or A). The unit of the actuator follows the type. +3. Move the actuator to the level you need. A level outside the range is cut to it, and the plugin says so. + +The level of an output cannot be read back from the device, so the value shown is the last level written. The output is +set to 0 (0 V, 0 A or low) when the actuator starts, when you choose another output or another type (the previous +output goes to 0 before the new one is driven) and when the actuator closes. + +Digital lines (``NIDAQmx_DO``) +------------------------------ + +A line is high for a value of 1 and low for 0. The *Pulse* option is for triggering something: a move to 1 then sets +the line high for the **Pulse width** (in ms) and sets it low again, so the position is 0 again afterwards (it is the real level of the line). As that is too fast to see, each pulse is written in the log and counted in the read-only **Pulses sent**. Wire the line +to a PFI terminal of the device (or of the chassis) and use that terminal as the *Terminal* of the start trigger of a +module of the generic viewers (:doc:`nidaqmx_viewer_use`) to start an acquisition with it. + +Using the same device with other plugins +---------------------------------------- + +An output is used by one task only: the same channel cannot be driven by two actuators, and the driver tells so (the +resource is reserved). Other channels, and the inputs of the same device, remain free. diff --git a/docs/source/user_guide/nidaqmx_viewer_use.rst b/docs/source/user_guide/nidaqmx_viewer_use.rst index 62fe727..5ed19eb 100644 --- a/docs/source/user_guide/nidaqmx_viewer_use.rst +++ b/docs/source/user_guide/nidaqmx_viewer_use.rst @@ -117,3 +117,22 @@ written, and is back to normal when it worked. After a failure the menu goes bac that is not in the tree. A file that cannot be read gives an error that names the file and the entry that is wrong. + +Digital input lines (``NIDAQmx_DI``) +------------------------------------ + +``DAQ_1DViewer_NIDAQmx_DI`` (in the 1D viewers, as ``NIDAQmx_DI``) is the same viewer for the digital input lines of +a device (``Dev1/port0/line0``), as 1D traces: a line is 0 or 1, so there is no mean and no 0D display. It differs +from the analog viewer in a few points: + +* The group ``Lines`` replaces ``Channels``: *Add* lists the lines of the computer, and a line has no type nor range, + only its ``read`` box. +* The group of each module (``Modules``) is the same, with the frequency and the clock, but the start trigger is + ``none`` or ``digital edge`` only: a digital input has no analog trigger. ``internal`` is the sample clock of the + digital task itself (``/Dev1/di/SampleClock``), which exists on the devices that can time their digital lines. If the + driver refuses it, choose a clock source: a PFI terminal wired to a clock, or the clock of another module. The + sample clock of an analog input (``/Dev1/ai/SampleClock``) is a different clock: it only runs while an analog + task of that device runs, at its rate, which is what you want to read lines in step with analog channels. +* Each module has its own task and gives its own data, named ``NI DI ``, with the lines as traces labelled + with their names. +* There is no live mode and no configuration file in this version. diff --git a/src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx.py b/src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx.py index 2f082b2..293f34e 100644 --- a/src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx.py +++ b/src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx.py @@ -1,10 +1,57 @@ -from ..hardware.national_instruments.NIDAQmx_Move import DAQ_NIDAQmx_Actuator +"""Generic actuator for one analog output of an NI device: a level in volts or amperes, set on demand. +There is no clock and no waveform (for voltage ramps, see ``DAQ_Move_NIDAQmx_RampOutput``; for a digital line, +``DAQ_Move_NIDAQmx_DO``). The common behaviour (zero at start, change and close, position = last level written) is in +``OutputActuator``. +""" +import numpy as np +from pymodaq.control_modules.daq_move_ui.utils import UiType +from pymodaq.control_modules.move_utility_classes import comon_parameters_fun, main +from pymodaq.utils.daq_utils import ThreadCommand -class DAQ_Move_NIDAQmx(DAQ_NIDAQmx_Actuator): - """ - Plugin for basic current or voltage control with NI modules (plugged in NI cDAQ or NI-USB). (in process) - """ - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) +from pymodaq_plugins_daqmx.hardware.national_instruments.api import (AnalogOutputTask, AOCurrent, AOVoltage, + ChannelKind, TaskConfig) +from pymodaq_plugins_daqmx.hardware.national_instruments.output_actuator import OutputActuator +ANALOG_TYPES = {'voltage': (AOVoltage, 'V'), 'current': (AOCurrent, 'A')} # type -> channel of the API, unit + + +class DAQ_Move_NIDAQmx(OutputActuator): + """One analog output: the level in V or A, cut to the range of the output.""" + _controller_units = 'V' + _epsilons = [1e-3] + ui_type = UiType.SIMPLE # a value to type and a button to set it + output_kind = ChannelKind.AO + rebuild_on = ('channel', 'type', 'min_val', 'max_val') + params = [ + {'title': 'Output:', 'name': 'channel', 'type': 'list', 'limits': [], 'tip': 'An analog output (Dev1/ao0)'}, + {'title': 'Type:', 'name': 'type', 'type': 'list', 'limits': list(ANALOG_TYPES), 'value': 'voltage'}, + {'title': 'Min:', 'name': 'min_val', 'type': 'float', 'value': -10., 'suffix': 'V', + 'tip': 'Lowest level of the output; the level asked is cut to the range'}, + {'title': 'Max:', 'name': 'max_val', 'type': 'float', 'value': 10., 'suffix': 'V'}, + ] + comon_parameters_fun(False, axis_names=OutputActuator._axis_names, epsilon=_epsilons) + + def make_task(self): + cls = ANALOG_TYPES[self.settings['type']][0] + return AnalogOutputTask(TaskConfig(channels=[cls(self.settings['channel'], self.settings['min_val'], + self.settings['max_val'])])) + + def send(self, level: float) -> None: + self.controller.write_analog(float(level)) + self.level = float(level) + + def show_settings(self) -> None: + unit = ANALOG_TYPES[self.settings['type']][1] + for name in ('min_val', 'max_val'): + self.settings.child(name).setOpts(suffix=unit) + self.axis_unit = unit + + def clip(self, level: float) -> float: + clipped = float(np.clip(level, self.settings['min_val'], self.settings['max_val'])) + if clipped != level: + self.emit_status(ThreadCommand('outofbounds')) + return clipped + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx_DO.py b/src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx_DO.py new file mode 100644 index 0000000..38557d5 --- /dev/null +++ b/src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx_DO.py @@ -0,0 +1,57 @@ +"""Generic actuator for one digital output line of an NI device: 0 (low) or 1 (high), or a pulse. + +The common behaviour (zero at start, change and close, position = last level written) is in ``OutputActuator``. +""" +import time + +from pymodaq.control_modules.daq_move_ui.utils import UiType +from pymodaq.control_modules.move_utility_classes import DataActuator, comon_parameters_fun, main +from pymodaq.utils.daq_utils import ThreadCommand + +from pymodaq_plugins_daqmx.hardware.national_instruments.api import ChannelKind, DigitalOut, DigitalTask, TaskConfig +from pymodaq_plugins_daqmx.hardware.national_instruments.output_actuator import OutputActuator + + +class DAQ_Move_NIDAQmx_DO(OutputActuator): + """One digital line: high for a value of 1 (from 0.5 on), low for 0. With ``pulse``, a move to 1 sets the line high + for ``pulse_width`` ms and then low again, to trigger something (wire the line to a PFI terminal).""" + _controller_units = '' + _epsilons = [0.1] + ui_type = UiType.BINARY # two buttons: one for each level + output_kind = ChannelKind.DO + params = [ + {'title': 'Line:', 'name': 'channel', 'type': 'list', 'limits': [], 'tip': 'A digital line (Dev1/port0/line0)'}, + {'title': 'Pulse:', 'name': 'pulse', 'type': 'bool', 'value': False, + 'tip': 'A move to 1 sets the line high for the pulse width, then low again'}, + {'title': 'Pulse width (ms):', 'name': 'pulse_width', 'type': 'float', 'value': 10., 'min': 0.}, + {'title': 'Pulses sent:', 'name': 'pulses', 'type': 'int', 'value': 0, 'readonly': True, + 'tip': 'The line is low again after a pulse, so the position does not show it: this counts them'}, + ] + comon_parameters_fun(False, axis_names=OutputActuator._axis_names, epsilon=_epsilons) + + def make_task(self): + return DigitalTask(TaskConfig(channels=[DigitalOut(self.settings['channel'])])) + + def send(self, level: float) -> None: + high = bool(level >= 0.5) + self.controller.write_digital(high) + self.level = float(high) + + def show_settings(self) -> None: + self.axis_unit = '' + + def drive(self, level: float) -> None: + if self.settings['pulse'] and level >= 0.5: + self.send(1.) + time.sleep(self.settings['pulse_width'] * 1e-3) + self.send(0.) + self.target_value = DataActuator(data=0., units=self.axis_unit) # the line is low again + self.settings.child('pulses').setValue(self.settings['pulses'] + 1) + self.emit_status(ThreadCommand('Update_Status', [ + f"Pulse {self.settings['pulses']} of {self.settings['pulse_width']:g} ms sent on " + f"{self.settings['channel']}", 'log'])) + else: + self.send(level) + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py index da1de89..460e1a1 100644 --- a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py +++ b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py @@ -35,11 +35,12 @@ # --- terminals -------------------------------------------------------------------------------------------------- -def _exporting_module(terminal: str) -> Optional[str]: - """The module that produces the signal ``terminal`` (``/Dev1/ai/SampleClock`` is produced by ``Dev1``), None for - any other terminal (``/Dev1/PFI0``, a wire). It tells which task has to be started before another one.""" +def _exporting_module(terminal: str, subsystem: str = 'ai') -> Optional[str]: + """The module that produces the signal ``terminal`` (``/Dev1/ai/SampleClock`` is produced by ``Dev1`` for the + subsystem ``ai``), None for any other terminal (``/Dev1/PFI0``, a wire). It tells which task has to be started + before another one.""" parts = (terminal or '').split('/') - return parts[1] if len(parts) > 3 and parts[0] == '' and parts[2] == 'ai' else None + return parts[1] if len(parts) > 3 and parts[0] == '' and parts[2] == subsystem else None # what the driver lists as terminals but cannot be a clock or a trigger source @@ -63,7 +64,8 @@ def is_clock_source(terminal: str) -> bool: return _CLOCK_SOURCE.match(terminal) is not None -def module_group(module: str, frequency: int, clocks: List[str], terminals: List[str], channels: List[str]) -> dict: +def module_group(module: str, frequency: int, clocks: List[str], terminals: List[str], channels: List[str], + trigger_types: List[str] = TRIGGER_TYPES) -> dict: """The settings of a module: its frequency, its clock and its start trigger.""" return {'title': module, 'name': module, 'type': 'group', 'children': [ {'title': 'Frequency:', 'name': 'frequency', 'type': 'int', 'value': frequency, 'min': 1, @@ -71,7 +73,7 @@ def module_group(module: str, frequency: int, clocks: List[str], terminals: List {'title': 'Clock:', 'name': 'clock', 'type': 'list', 'limits': clocks, 'value': CLOCK_INTERNAL, 'tip': 'The clock of the module, or a terminal (a clock wired in, or the clock that another module exports)'}, {'title': 'Start trigger:', 'name': 'trigger', 'type': 'group', 'children': [ - {'title': 'Type:', 'name': 'type', 'type': 'list', 'limits': TRIGGER_TYPES, 'value': 'none'}, + {'title': 'Type:', 'name': 'type', 'type': 'list', 'limits': trigger_types, 'value': 'none'}, {'title': 'Terminal:', 'name': 'terminal', 'type': 'list', 'limits': terminals, 'visible': False}, {'title': 'Channel:', 'name': 'channel', 'type': 'list', 'limits': channels, 'visible': False, 'tip': 'A channel of this module (it is acquired) or a dedicated analog trigger terminal'}, @@ -107,16 +109,28 @@ class DAQ_0DViewer_NIDAQmx(DAQ_Viewer_AIBase): 'limits': [], 'children': []}, ] data_name = 'NI AI' + # what distinguishes the subclasses for other inputs (the digital lines): the kind of channels of the tree (it + # also names the subsystem of the driver that exports the clock and the trigger of a module: ``/Dev1/ai/...``), + # the types of start trigger, and whether there are files + kind = ChannelKind.AI + trigger_types = TRIGGER_TYPES + has_configuration = True + + @property + def subsystem(self) -> str: + """The part of the terminal names that the driver gives to the subsystem of the channels (``ai``, ``di``).""" + return self.kind.value def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) system = NIDAQSystem() - self.settings.child('channels').setLimits(system.all_channels(ChannelKind.AI)) + self.settings.child('channels').setLimits(system.all_channels(self.kind)) self.terminals = {device: system.terminals(device) for device in system.devices()} # of each device self.files = ConfigFiles() self.loaded = MANUAL # the configuration whose channels are in the tree self.in_file = () # what the file describes (see `snapshot`), to tell if the tree still is the file - self.refresh_menu() + if self.has_configuration: + self.refresh_menu() # --- configuration files: menu, load, save ------------------------------------------------------------------ @@ -228,7 +242,7 @@ def sync_modules(self) -> None: for module in modules: lists = self.module_lists(module) if module not in group.names: - group.addChild(module_group(module, self.settings['frequency'], **lists)) + group.addChild(module_group(module, self.settings['frequency'], trigger_types=self.trigger_types, **lists)) continue self.set_limits(group.child(module, 'clock'), lists['clocks']) self.set_limits(group.child(module, 'trigger', 'terminal'), lists['terminals']) @@ -264,7 +278,7 @@ def module_lists(self, module: str) -> dict: only the devices that can reach the module offer terminals (see ``reachable_devices``).""" reachable = self.reachable_devices(module) others = [m for m in self.modules() if m != module and m in reachable] - own = f'/{module}/ai/' + own = f'/{module}/{self.subsystem}/' terminals = [t for device in reachable for t in self.terminals.get(device, []) if not t.startswith(own) and is_signal_terminal(t)] names = [child.opts['title'] for child in self.settings.child('channels').children() @@ -275,8 +289,8 @@ def module_lists(self, module: str) -> dict: apfi = [] # the clock sources of all the devices, and the sample clock that another module of the tree exports clocks = ([CLOCK_INTERNAL] + [t for t in terminals if is_clock_source(t)] - + [f'/{m}/ai/SampleClock' for m in others]) - starts = terminals + [f'/{m}/ai/StartTrigger' for m in others] + + [f'/{m}/{self.subsystem}/SampleClock' for m in others]) + starts = terminals + [f'/{m}/{self.subsystem}/StartTrigger' for m in others] return {'clocks': list(dict.fromkeys(clocks)), 'terminals': list(dict.fromkeys(starts)), 'channels': names + apfi} @@ -340,7 +354,7 @@ def acquisitions(self) -> List[Acquisition]: # the parameter of the trigger that names its source depends on the type of trigger key = {'digital edge': 'terminal', 'analog edge': 'channel'}.get(group['trigger', 'type']) sources = [clock] + ([group['trigger', key]] if key is not None else []) - waits = tuple(dict.fromkeys(m for m in (_exporting_module(source) for source in sources) + waits = tuple(dict.fromkeys(m for m in (_exporting_module(source, self.subsystem) for source in sources) if m not in (None, module) and m in by_module)) acquisitions.append(Acquisition(module, channels, group['frequency'], tuple(c.name for c in channels if c.name in unread), clock, trigger, waits)) @@ -400,9 +414,9 @@ def commit_settings(self, param: Parameter) -> None: param = self.own(param) parent = param.parent() in_a_channel = parent is not None and parent.parent() is self.settings.child('channels') - if param.name() == 'configuration' and parent is self.settings.child('config'): + if self.has_configuration and param.name() == 'configuration' and parent is self.settings.child('config'): self.load_configuration() - elif param.opts['type'] == 'ni_save': # the button has been clicked, after the dialog of the GUI + elif self.has_configuration and param.opts['type'] == 'ni_save': # the button has been clicked, after the dialog of the GUI param.opts.update(suffix=button.opts['suffix']) try: self.save_configuration(param) @@ -411,7 +425,7 @@ def commit_settings(self, param: Parameter) -> None: param.setValue(Status.ERROR) self.fail(error) if param.name() == 'type' and in_a_channel: # the type of a channel: its group is rebuilt - set_type(ChannelKind.AI, parent, param.value()) + set_type(self.kind, parent, param.value()) if param.name() == 'units' and in_a_channel: # the units of a temperature: the range follows update_suffixes(parent) if param.name() == 'type' and parent is not None and parent.name() == 'trigger': diff --git a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_1D/daq_1Dviewer_NIDAQmx_DI.py b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_1D/daq_1Dviewer_NIDAQmx_DI.py new file mode 100644 index 0000000..72cdc32 --- /dev/null +++ b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_1D/daq_1Dviewer_NIDAQmx_DI.py @@ -0,0 +1,45 @@ +"""Generic viewer of the digital input lines of any NI device, as 1D traces. + +It is the generic analog viewer with lines in place of channels: the same settings for each module (frequency, +clock, start trigger) and one clocked digital task for each module. A line is 0 or 1, so the data are traces and +never a mean (there is no 0D display). There is no live mode and no configuration file in this version. +""" +from copy import deepcopy + +import numpy as np +from pymodaq.control_modules.viewer_utility_classes import main + +from pymodaq_plugins_daqmx.daq_viewer_plugins.plugins_0D.daq_0Dviewer_NIDAQmx import DAQ_0DViewer_NIDAQmx +from pymodaq_plugins_daqmx.hardware.national_instruments.api import ChannelKind, DigitalTask + + +def _digital_params() -> list: + params = [] + for param in deepcopy(DAQ_0DViewer_NIDAQmx.params): + if param['name'] == 'config': # the files describe analog inputs + continue + if param['name'] == 'display': # traces only + param.update(limits=['1D'], value='1D', visible=False) + if param['name'] == 'channels': + param.update(title='Lines:', kind=ChannelKind.DI.value) + params.append(param) + return params + + +class DAQ_1DViewer_NIDAQmx_DI(DAQ_0DViewer_NIDAQmx): + """Digital input lines (``Dev1/port0/line0``) of any NI device, as 1D traces, one data for each module.""" + params = _digital_params() + data_name = 'NI DI' + kind = ChannelKind.DI + trigger_types = ['none', 'digital edge'] # there is no analog start trigger on a digital input + has_configuration = False + live_mode_available = False + task_class = DigitalTask + + def read_block(self, task) -> np.ndarray: + """The levels of the lines as floats (0. or 1.), shaped (lines, Nsamples).""" + return task.read_digital(self.task_samples()).astype(float) + + +if __name__ == '__main__': + main(__file__, init=False) diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_AI.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_AI.py index b2be98d..8a5a918 100644 --- a/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_AI.py +++ b/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_AI.py @@ -108,6 +108,11 @@ class DAQ_Viewer_AIBase(DAQ_Viewer_base): hardware_averaging = True live_mode_available = True # with live=True: one continuous task, one data per block of samples data_name = 'NI AI' + task_class = AnalogInputTask # the kind of task of an acquisition; a subclass for other inputs gives its own + + def read_block(self, task) -> np.ndarray: + """Run the finite acquisition of a started task: its samples as floats, shaped (nchannels, Nsamples).""" + return task.read_analog() def ini_attributes(self): self.controller = None # the task of this plugin, or the group of its tasks when it has several @@ -188,7 +193,7 @@ def update_tasks(self, streaming: bool = False) -> None: try: for acquisition in acquisitions: clock = ClockSettings(rate=acquisition.frequency, samples=samples, source=acquisition.clock) - tasks.append(AnalogInputTask(TaskConfig(channels=acquisition.channels, timing=clock, + tasks.append(self.task_class(TaskConfig(channels=acquisition.channels, timing=clock, trigger=acquisition.trigger))) except Exception: for task in reversed(tasks): @@ -215,7 +220,7 @@ def read_samples(self) -> List[np.ndarray]: for task in self.ordered_tasks(): task.start() started.append(task) - return [task.read_analog() for task in self.tasks] + return [self.read_block(task) for task in self.tasks] finally: for task in reversed(started): task.stop() diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/config_files.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/config_files.py index 7f35587..cc4de4a 100644 --- a/src/pymodaq_plugins_daqmx/hardware/national_instruments/config_files.py +++ b/src/pymodaq_plugins_daqmx/hardware/national_instruments/config_files.py @@ -15,7 +15,7 @@ from nidaqmx.constants import TerminalConfiguration, ThermocoupleType, UsageTypeAI from pymodaq_plugins_daqmx.hardware.national_instruments.api import ( - AICurrent, AIRtd, AIThermocouple, AIVoltage, ChannelKind) + AICurrent, AIRtd, AIThermocouple, AIVoltage, ChannelKind, DigitalIn) FORMAT_VERSION = 1 @@ -25,6 +25,7 @@ #: channel types of a configuration file, by the ``type`` key, for each kind of channel CHANNEL_TYPES = { ChannelKind.AI: {'voltage': AIVoltage, 'current': AICurrent, 'thermocouple': AIThermocouple, 'rtd': AIRtd}, + ChannelKind.DI: {'line': DigitalIn}, # in the settings tree only: the files describe analog inputs } diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/output_actuator.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/output_actuator.py new file mode 100644 index 0000000..d4a100f --- /dev/null +++ b/src/pymodaq_plugins_daqmx/hardware/national_instruments/output_actuator.py @@ -0,0 +1,108 @@ +"""Base class of the actuators that drive one output of an NI device, one point at a time. + +The output is driven on demand: there is no clock and no waveform. The level of an output cannot be read back, so the +position is the last level written. The output goes to 0 when the actuator starts, when its channel changes and when it +closes. The analog and the digital actuators (``DAQ_Move_NIDAQmx``, ``DAQ_Move_NIDAQmx_DO``) share all of this and only +differ by their settings, their task and the way a level is written. +""" +from pymodaq.control_modules.move_utility_classes import DAQ_Move_base, DataActuator, DataActuatorType +from pymodaq.utils.logger import get_module_name, set_logger + +from pymodaq_plugins_daqmx.hardware.national_instruments.api import ChannelKind, NIDAQSystem + +logger = set_logger(get_module_name(__file__)) + + +class OutputActuator(DAQ_Move_base): + """One output of an NI device. A subclass gives ``output_kind`` (the outputs offered), ``rebuild_on`` (the + settings that need a new task) and the methods ``make_task``, ``send`` and ``show_settings``.""" + is_multiaxes = False + _axis_names = ['output'] + data_actuator_type = DataActuatorType.DataActuator + output_kind = ChannelKind.AO + rebuild_on = ('channel',) # the settings that need a new task when they change + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.settings.child('channel').setLimits(NIDAQSystem().all_channels(self.output_kind)) + self.show_settings() + + def ini_attributes(self): + self.controller = None # the task of the output + self.level = 0. # the last level written + + # --- what a subclass gives ---------------------------------------------------------------------------------- + + def make_task(self): + """The task of the chosen output, built from the settings.""" + raise NotImplementedError + + def send(self, level: float) -> None: + """Drive the output to ``level`` on the task and keep it in ``self.level``.""" + raise NotImplementedError + + def show_settings(self) -> None: + """Show the settings that apply to the output, and set the unit of the actuator.""" + raise NotImplementedError + + def clip(self, level: float) -> float: + """The level that the output can take (an analog output has a range).""" + return level + + def drive(self, level: float) -> None: + """Bring the output to ``level`` (a digital line can pulse instead): sets ``self.target_value`` if it differs.""" + self.send(level) + + # --- the output --------------------------------------------------------------------------------------------- + + def open_output(self) -> None: + """Make the task of the chosen output and set the output to 0.""" + self.controller = self.make_task() + self.send(0.) + + def close_output(self) -> None: + """Set the output to 0 and release it: the channel is the one of this task only while it is open.""" + if self.controller is None: + return + try: + self.send(0.) + except Exception: # closing must go on: the channel has to be released + logger.warning('The output could not be set to 0', exc_info=True) + self.controller.close() + self.controller = None + + # --- the actuator ------------------------------------------------------------------------------------------- + + def ini_stage(self, controller=None): + self.show_settings() # the settings may have been given before the initialization + self.open_output() + return 'NI output ready', True + + def close(self): + self.close_output() + + def commit_settings(self, param): + if param.name() in self.rebuild_on and self.controller is not None: + self.close_output() # the old output goes to 0 before the new one is driven + self.show_settings() + self.open_output() + elif param.name() in self.rebuild_on: + self.show_settings() + + def get_actuator_value(self) -> DataActuator: + return DataActuator(data=self.level, units=self.axis_unit) + + def move_abs(self, value: DataActuator): + value = self.check_bound(value) + level = self.clip(float(value.value(self.axis_unit))) + self.target_value = DataActuator(data=level, units=self.axis_unit) + self.drive(level) + + def move_rel(self, value: DataActuator): + self.move_abs(DataActuator(data=self.level + float(value.value(self.axis_unit)), units=self.axis_unit)) + + def move_home(self): + self.move_abs(DataActuator(data=0., units=self.axis_unit)) + + def stop_motion(self): + pass # a level is written at once: there is nothing to stop diff --git a/tests/nidaqmx_double.py b/tests/nidaqmx_double.py index 1ac752c..3b2bcdc 100644 --- a/tests/nidaqmx_double.py +++ b/tests/nidaqmx_double.py @@ -14,7 +14,7 @@ KNOWN_COUNTERS = {f"Dev2/ctr{c}" for c in range(4)} KNOWN_AO_CHANNELS = {f"Dev2/ao{c}" for c in range(4)} -KNOWN_LINES = {f"Dev2/port0/line{c}" for c in range(8)} +KNOWN_LINES = {f"Dev2/port0/line{c}" for c in range(8)} | {f"Dev1/port0/line{c}" for c in range(4)} KNOWN_AI_CHANNELS = {f"Dev{d}/ai{c}" for d in (1, 2) for c in range(8)} diff --git a/tests/test_config_files.py b/tests/test_config_files.py index dc10fa9..a689aa7 100644 --- a/tests/test_config_files.py +++ b/tests/test_config_files.py @@ -136,11 +136,12 @@ def test_a_file_of_an_unknown_version_is_refused(tmp_path): def test_the_user_guide_describes_every_type_key_and_value_of_the_format(): import dataclasses import enum + from pymodaq_plugins_daqmx.hardware.national_instruments.api import ChannelKind from pymodaq_plugins_daqmx.hardware.national_instruments.config_files import CHANNEL_TYPES, channel_fields page = (Path(__file__).parent.parent / 'docs' / 'source' / 'user_guide' / 'config_files.rst').read_text() missing = [] - for types in CHANNEL_TYPES.values(): + for types in [CHANNEL_TYPES[ChannelKind.AI]]: # the files describe analog inputs for name, cls in types.items(): missing += [f'type {name}'] if f'``{name}``' not in page else [] for f in channel_fields(cls): diff --git a/tests/test_generic_actuator.py b/tests/test_generic_actuator.py new file mode 100644 index 0000000..eb25248 --- /dev/null +++ b/tests/test_generic_actuator.py @@ -0,0 +1,113 @@ +"""Behaviour of the generic NI output actuator (one analog output or digital line), with the driver doubled.""" +import pytest + +pytest.importorskip('nidaqmx') +pytest.importorskip('pymodaq') + +from pymodaq.utils.data import DataActuator +from pymodaq.utils.plugin_testing import make_actuator + +from pymodaq_plugins_daqmx.daq_move_plugins.daq_move_NIDAQmx import DAQ_Move_NIDAQmx +from pymodaq_plugins_daqmx.daq_move_plugins.daq_move_NIDAQmx_DO import DAQ_Move_NIDAQmx_DO + +from nidaqmx_double import driver, system_driver # noqa: F401 (pytest fixtures) + + +def output_tasks(driver): + return [t for t in driver if t.channels and t.channels[0][0] in ('ao_voltage', 'ao_current', 'do')] + + +def test_the_analog_actuator_offers_the_analog_outputs_and_the_digital_one_the_lines(qapp, driver, system_driver): + analog = make_actuator(DAQ_Move_NIDAQmx, channel='Dev2/ao0') + digital = make_actuator(DAQ_Move_NIDAQmx_DO, channel='Dev2/port0/line0') + assert 'Dev2/ao0' in analog.settings.child('channel').opts['limits'] + assert not [c for c in analog.settings.child('channel').opts['limits'] if '/port' in c] + assert 'Dev2/port0/line0' in digital.settings.child('channel').opts['limits'] + assert not [c for c in digital.settings.child('channel').opts['limits'] if '/ao' in c] + analog.close() + digital.close() + + +def test_an_analog_output_is_set_to_zero_at_start_and_moves_to_a_level(qapp, driver, system_driver): + plugin = make_actuator(DAQ_Move_NIDAQmx, channel='Dev2/ao0') + task = output_tasks(driver)[0] + assert task.channels[0][0] == 'ao_voltage' and task.writes == [(0., True)] + assert plugin.axis_unit == 'V' and plugin.get_actuator_value().value('V') == 0. + plugin.move_abs(DataActuator(data=2.5, units='V')) + assert task.writes[-1] == (2.5, True) and plugin.get_actuator_value().value('V') == pytest.approx(2.5) + plugin.move_rel(DataActuator(data=-1., units='V')) + assert task.writes[-1] == (1.5, True) + plugin.close() + + +def test_a_level_outside_the_range_of_the_output_is_cut_to_it(qapp, driver, system_driver): + plugin = make_actuator(DAQ_Move_NIDAQmx, channel='Dev2/ao0', min_val=-2., max_val=3.) + plugin.move_abs(DataActuator(data=7., units='V')) + assert output_tasks(driver)[0].writes[-1] == (3., True) + plugin.close() + + +def test_a_current_output_is_in_amperes(qapp, driver, system_driver): + plugin = make_actuator(DAQ_Move_NIDAQmx, channel='Dev2/ao1', type='current', min_val=0., max_val=0.02) + assert output_tasks(driver)[0].channels[0][0] == 'ao_current' and plugin.axis_unit == 'A' + plugin.close() + + +def test_the_output_goes_back_to_zero_when_the_plugin_closes(qapp, driver, system_driver): + plugin = make_actuator(DAQ_Move_NIDAQmx, channel='Dev2/ao0') + plugin.move_abs(DataActuator(data=4., units='V')) + task = output_tasks(driver)[0] + plugin.close() + assert task.writes[-1] == (0., True) and task.closed + + +def test_changing_the_channel_zeroes_the_old_output_and_drives_the_new_one(qapp, driver, system_driver): + plugin = make_actuator(DAQ_Move_NIDAQmx, channel='Dev2/ao0') + plugin.move_abs(DataActuator(data=4., units='V')) + plugin.settings.child('channel').setValue('Dev2/ao1') + plugin.commit_settings(plugin.settings.child('channel')) + old, new = output_tasks(driver)[:2] + assert old.writes[-1] == (0., True) and old.closed + assert new.channels[0][1] == 'Dev2/ao1' and new.writes == [(0., True)] + plugin.close() + + +def test_a_digital_line_is_driven_to_a_level_and_has_no_unit(qapp, driver, system_driver): + plugin = make_actuator(DAQ_Move_NIDAQmx_DO, channel='Dev2/port0/line1') + task = output_tasks(driver)[0] + assert task.channels[0][0] == 'do' and task.writes == [(False, True)] + assert plugin.axis_unit == '' + plugin.move_abs(DataActuator(data=1., units='')) + assert task.writes[-1] == (True, True) and plugin.get_actuator_value().value() == 1. + plugin.close() + assert task.writes[-1] == (False, True) and task.closed + + +def test_a_pulse_sets_the_line_high_for_a_while_then_low_again(qapp, driver, system_driver): + plugin = make_actuator(DAQ_Move_NIDAQmx_DO, channel='Dev2/port0/line1', pulse=True, pulse_width=1.) + task = output_tasks(driver)[0] + plugin.move_abs(DataActuator(data=1., units='')) + assert [w[0] for w in task.writes] == [False, True, False] + assert plugin.get_actuator_value().value() == 0. # the line is low again + plugin.close() + + +def test_each_pulse_is_logged_and_counted(qapp, driver, system_driver): + plugin = make_actuator(DAQ_Move_NIDAQmx_DO, channel='Dev2/port0/line1', pulse=True, pulse_width=1.) + sent = [] + plugin.emit_status = lambda status: status.command != 'update_settings' and sent.append(status) + assert plugin.settings['pulses'] == 0 and plugin.settings.child('pulses').opts['readonly'] + plugin.move_abs(DataActuator(data=1., units='')) + plugin.move_abs(DataActuator(data=1., units='')) + assert plugin.settings['pulses'] == 2 + assert [s.command for s in sent] == ['Update_Status', 'Update_Status'] + assert 'Dev2/port0/line1' in sent[0].attribute[0] and '1' in sent[0].attribute[0] + plugin.move_abs(DataActuator(data=0., units='')) # a move to 0 is no pulse + assert plugin.settings['pulses'] == 2 + plugin.close() + + +def test_each_actuator_asks_for_its_user_interface(): + from pymodaq.control_modules.daq_move_ui.utils import UiType + assert DAQ_Move_NIDAQmx.ui_type == UiType.SIMPLE + assert DAQ_Move_NIDAQmx_DO.ui_type == UiType.BINARY diff --git a/tests/test_generic_di_plugin.py b/tests/test_generic_di_plugin.py new file mode 100644 index 0000000..ef01c0d --- /dev/null +++ b/tests/test_generic_di_plugin.py @@ -0,0 +1,62 @@ +"""Behaviour of the generic NI digital input viewer (1D traces of lines, no hardware needed).""" +import pytest + +pytest.importorskip('nidaqmx') +pytest.importorskip('pymodaq') + +from pymodaq.utils.plugin_testing import make_detector, grab_and_wait + +from pymodaq_plugins_daqmx.daq_viewer_plugins.plugins_1D.daq_1Dviewer_NIDAQmx_DI import DAQ_1DViewer_NIDAQmx_DI + +from nidaqmx_double import driver, system_driver # noqa: F401 (pytest fixtures) + + +def test_the_tree_offers_the_digital_lines_of_the_computer(qapp, driver, system_driver): + plugin = make_detector(DAQ_1DViewer_NIDAQmx_DI, Nsamples=10) + group = plugin.settings.child('channels') + assert 'Dev1/port0/line0' in group.opts['addList'] and not [n for n in group.opts['addList'] if '/ai' in n] + plugin.close() + + +def test_the_lines_added_to_the_tree_give_a_trace_each(qapp, driver, system_driver): + plugin = make_detector(DAQ_1DViewer_NIDAQmx_DI, Nsamples=10) + group = plugin.settings.child('channels') + group.addNew('Dev2/port0/line1') + group.addNew('Dev2/port0/line0') + dte = grab_and_wait(plugin) + assert dte[0].dim == 'Data1D' and dte[0].name == 'NI DI Dev2' + assert dte[0].labels == ['Dev2/port0/line1', 'Dev2/port0/line0'] + assert [d.shape for d in dte[0].data] == [(10,), (10,)] + # in the double, the line of row c is high at the samples s with c + s even + assert [d.tolist() for d in dte[0].data] == [[1., 0.] * 5, [0., 1.] * 5] + assert [kind for kind, *_ in driver[-1].channels] == ['di', 'di'] + plugin.close() + + +def test_each_module_has_its_own_clocked_task_and_digital_trigger_only(qapp, driver, system_driver): + from nidaqmx.constants import Edge + plugin = make_detector(DAQ_1DViewer_NIDAQmx_DI, Nsamples=10) + group = plugin.settings.child('channels') + group.addNew('Dev1/port0/line0') + group.addNew('Dev2/port0/line0') + plugin.commit_settings(group) + modules = plugin.settings.child('modules') + assert modules.child('Dev1', 'trigger', 'type').opts['limits'] == ['none', 'digital edge'] + modules['Dev1', 'frequency'] = 500 + trigger = modules.child('Dev1', 'trigger') + trigger.child('type').setValue('digital edge') + plugin.commit_settings(trigger.child('type')) + trigger.child('terminal').setValue('/Dev1/PFI1') + dte = grab_and_wait(plugin) + assert [d.name for d in dte] == ['NI DI Dev1', 'NI DI Dev2'] + assert driver[0].timing_calls[0][1] == 500 and driver[1].timing_calls[0][1] == 1000 + assert driver[0].trigger_calls == [('dig_edge', '/Dev1/PFI1', Edge.RISING)] and driver[1].trigger_calls == [] + assert dte[0].axes[0].units == 's' + plugin.close() + + +def test_the_digital_viewer_has_no_live_mode_nor_configuration_menu(qapp, driver, system_driver): + plugin = make_detector(DAQ_1DViewer_NIDAQmx_DI) + assert not plugin.live_mode_available + assert 'config' not in plugin.settings.names + plugin.close()