diff --git a/docs/source/api/migration.rst b/docs/source/api/migration.rst index bcdf3f2..fd1b51b 100644 --- a/docs/source/api/migration.rst +++ b/docs/source/api/migration.rst @@ -2,9 +2,8 @@ Migrating from the previous objects =================================== The ``NIDAQmx`` object of ``hardware/national_instruments/daqmxni.py`` (one object, one task, channels described by -mutable classes with a ``source`` attribute, ``update_task`` with several ``if`` on the type) is replaced by the API of -this section. There is no compatibility layer: the old names disappear with the old module, once the plugins of the -package use the new API. +mutable classes with a ``source`` attribute, ``update_task`` with several ``if`` on the type) was replaced by the API of +this section, and the module has been removed. There is no compatibility layer: the old names do not exist any more. Two lines of releases exist: @@ -151,7 +150,7 @@ In a PyMoDAQ plugin State of the package -------------------- -The AI, counter and ramp-output plugins already use the new API. The generic plugins (``NIDAQmx`` viewers and -actuator, which read ``config_daqmx.toml``) still use the old module ``daqmxni.py`` and are ported next, together with -the removal of the old module: until then, both may be found in the same checkout, but nothing new should be built on -``daqmxni.py``. +All the plugins of the package use the new API: the AI, counter and ramp-output plugins, the generic viewers +(``NIDAQmx`` analog and ``NIDAQmx_DI`` digital) and the generic actuators (``NIDAQmx`` analog and ``NIDAQmx_DO`` +digital). The old modules (``daqmxni.py``, ``NIDAQmx_base.py``, ``NIDAQmx_Viewer.py`` and ``NIDAQmx_Move.py``) have been +removed; code that still needs them has to stay on the ``pydaqmx`` line or be rewritten as shown above. diff --git a/docs/source/creating_plugin.rst b/docs/source/creating_plugin.rst index 5f6ab8f..b4f49e8 100644 --- a/docs/source/creating_plugin.rst +++ b/docs/source/creating_plugin.rst @@ -7,10 +7,10 @@ In order to create a plugin using a NI card to acquire some data or control an a Then you have to analyze the experiment that you want to perform and find the best type of controller that you should use: -* a single ``NIDAQmx`` object, if you need to perform only one type of task. +* a single task of :doc:`the API ` (``AnalogInputTask``, ``AnalogOutputTask``...), if you need to perform only one type of task. -* a dict of several ``NIDAQmx`` objects, like in the ``DAQmx_Counter`` example, if you will only use the NI card but need to combine several tasks. +* a ``TaskGroup`` of several tasks, like in the ``DAQmx_Counter`` example, if you will only use the NI card but need to combine several tasks. -* a dict of ``NIDAQmx`` objects and other hardware controllers, for example if you want to synchronise your acquisition with an actuator which will be triggered by the NI card. +* a ``TaskGroup`` and other hardware controllers, for example if you want to synchronise your acquisition with an actuator which will be triggered by the NI card. * Another more complicated object (that you will need to write!), like in the ``NIDAQmx_RampOutput`` example, if you need to share some resources of the NI card between different instrument plugins which control independent parameters/measurements. Beware in particular of the Scan extension which sends all the move commands at the same time. diff --git a/docs/source/docstring/hardware.rst b/docs/source/docstring/hardware.rst index 7b4a565..7be28e7 100644 --- a/docs/source/docstring/hardware.rst +++ b/docs/source/docstring/hardware.rst @@ -1,14 +1,5 @@ hardware - National Instruments =============================== -NIDAQmx object --------------- - -NIDAQmx Base module -------------------- - -NIDAQmx Actuator module ------------------------ - -NIDAQmx Viewer module ---------------------- +The hardware layer is the ``nidaqmx`` based API, documented in :doc:`../api/index`, and the helpers that the plugins +share (``NIDAQmx_AI.py``, ``output_actuator.py``, ``config_files.py``, ``channel_tree.py``, ``ramp_output.py``). diff --git a/docs/source/index.rst b/docs/source/index.rst index c527339..05f387f 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -22,7 +22,6 @@ This plugin is compatible with PymoDAQ 5. introduction user_guide api/index - nidaqmx library creating_plugin diff --git a/docs/source/nidaqmx.rst b/docs/source/nidaqmx.rst deleted file mode 100644 index 0a77dc1..0000000 --- a/docs/source/nidaqmx.rst +++ /dev/null @@ -1,42 +0,0 @@ -The NIDAQmx object (being replaced) -=================================== - -.. note:: - The plugins are being ported to :doc:`the Python API `, which replaces this object. Write new code with - the API; :doc:`api/migration` maps the names below to the new ones. This page describes the object while the - generic plugins still use it. - -The NIDAQmx object -================== - -You will find its definition in the file ``hardware/national_instruments/daqmxni.py``. This is building block for this plugin, this is the object that you will use as a controller inside your custom plugin. - -The ``NIDAQmx`` object has an attribute ``task``, which corresponds to a Task for the NIDAQmx driver. Each ``NIDAQmx`` can only handle a single task, but a task can be executed on several channels. You will find in the same file the definition of many different Channel classes, which are all the channel types that are available physically on such NI devices. - -The list of these channels is: - - - AChannel (Analog Channel) - - - AIChannel: Analog Input - - AIThermoChannel: Specific analog input for thermocouples - - AOChannel: Analog Output - - - Counter (Regular edge counter) - - - ClockCounter: a counter that you use as a clock - - SemiPeriodCounter: another specific type of counter which might be useful to count between state transitions of a signal - - - DigitalChannel - - - DOChannel: Digital Output - - DIChannel: Digital Input - -To use the ``NIDAQmx``, you therefore need to create Channels of the type you need, specifying the appropriate ``ClockSettings`` and ``TriggerSettings`` (these are also defined in the same file). Then, you pass these channels to the ``update_task`` method of the ``NIDAQmx``. The ``update_task`` method sets everything up, but if you are using channels as trigger or clock for other channels, you will need to connects them yourself after calling ``update_task``. - -Once the task is properly set up, you can start it with the method ``start()`` of the ``NIDAQmx`` object. Depending on the task you are performing, several convenient methods with self-explaining names are available to read or write data: - - - ``read(number_of_samples_per_channel)``: direct measurement (such as in the 0Dviewer) - - ``register_callback(callback, event, nsamples)``: Measurement using the NI card's buffer (such as in the 1Dviewer) - - ``write(data, auto_start)`` - -You can also stop the task with the ``stop()`` method. diff --git a/docs/source/user_guide.rst b/docs/source/user_guide.rst index a2d53ff..cad1225 100644 --- a/docs/source/user_guide.rst +++ b/docs/source/user_guide.rst @@ -27,7 +27,7 @@ For any other use, you will need to create your own move or viewer based on this Working principle of the plugins -------------------------------- -The controller object, which is usually the wrapper to your hardware, will always be a ``NIDAQmx`` object. These are defined in ``hardware\national_instruments\daqmxni.py``. Such an object contains a **task**, which is configured and then sent to the NI device. Beware that a task can only contain one channel type. The channel types are Analog Output, Analog Input, Digital Output, Digital Input or Counter. As a consequence, if you need to combine several of them, your controller will be a bit more complicated. It might be a dict containing several ``NIDAQmx`` objects, as in the counter example, or you might even need to create a specific object to handle these ``NIDAQmx`` objects, as in the ramp output example. More details about these two situations are given in the following sections. +The controller object, which is usually the wrapper to your hardware, is a **task** of :doc:`the API ` (``AnalogInputTask``, ``AnalogOutputTask``, ``DigitalTask``, ``CounterInputTask`` or ``CounterOutputTask``), built from a ``TaskConfig`` that describes its channels, its clock and its start trigger. Beware that a task can only contain one type of channel: analog input, analog output, digital input or output, or counter. As a consequence, if you need to combine several of them, your controller will be a bit more complicated. It might be a ``TaskGroup`` of several tasks started together, as in the counter example, or you might even need to create a specific object to handle these tasks, as in the ramp output example. More details about these two situations are given in the following sections. .. toctree:: :maxdepth: 1 diff --git a/docs/source/user_guide/counter_details.rst b/docs/source/user_guide/counter_details.rst index ae18826..398f7f4 100644 --- a/docs/source/user_guide/counter_details.rst +++ b/docs/source/user_guide/counter_details.rst @@ -2,13 +2,13 @@ Details about the implementation of the 0D viewer DAQmx_Counter =============================================================== Two counters are used for one measurement: a first one counts the edges and a second one gives the counting time. -These are two separate tasks, although the channels are connected together, so a single ``NIDAQmx`` object cannot be +These are two separate tasks, although the channels are connected together, so a single task cannot be the controller of the plugin. -The controller is a dict containing two ``NIDAQmx`` objects, ``clock`` and ``counter``, each with its own task: +The controller holds two tasks, ``clock`` and ``counter``, started together as a ``TaskGroup``: -* The clock is a ``ClockCounter`` channel (see ``daqmxni.py``), producing pulses at the clock frequency. -* The counter is a ``CIChannel`` counting edges, whose sample clock is the internal output of the clock channel +* The clock is a ``COPulseFreq`` channel of a ``CounterOutputTask``, producing pulses at the clock frequency. +* The counter is a ``CICountEdges`` channel of a ``CounterInputTask`` counting edges, whose sample clock is the internal output of the clock channel (``/Dev[X]/ctr[Y]InternalOutput``): one sample is taken at the first tick of the clock. **One grab** diff --git a/docs/source/user_guide/ramp_output_details.rst b/docs/source/user_guide/ramp_output_details.rst index ba7718d..a919f47 100644 --- a/docs/source/user_guide/ramp_output_details.rst +++ b/docs/source/user_guide/ramp_output_details.rst @@ -2,14 +2,14 @@ Details about the implementation of the NIDAQmx_RampOutput move =============================================================== Several channels are needed for a movement: an analog output and a counter used as a clock. As in the case of the -counter (see :doc:`counter_details`), they are separate tasks and a single ``NIDAQmx`` object is not enough. In +counter (see :doc:`counter_details`), they are separate tasks and a single task is not enough. In addition, with several axes, all the outputs must be in the same task, driven by the same clock, and each axis is a different instrument plugin: they share a controller, ``RampOutputController`` (``ramp_output.py``). The controller -------------- -It has two ``NIDAQmx`` objects, ``clock`` and ``analog``, and one ``AOChannel`` per axis. For each move: +It has two tasks, ``clock`` (a ``CounterOutputTask``) and ``analog`` (an ``AnalogOutputTask``), and one ``AOVoltage`` channel per axis. For each move: * the clock task generates ``n + 1`` pulses at the frequency ``1 / step time``; * the analog task has one output channel per axis, its sample clock is the internal output of the clock channel, and diff --git a/src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx_RampOutput.py b/src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx_RampOutput.py index 965b446..b01368b 100644 --- a/src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx_RampOutput.py +++ b/src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx_RampOutput.py @@ -4,13 +4,13 @@ DataActuator, main) from pymodaq.utils.logger import set_logger, get_module_name -from pymodaq_plugins_daqmx.hardware.national_instruments.daqmxni import NIDAQmx, ChannelType +from pymodaq_plugins_daqmx.hardware.national_instruments.api import ChannelKind, NIDAQSystem from pymodaq_plugins_daqmx.hardware.national_instruments.ramp_output import RampOutputController logger = set_logger(get_module_name(__file__)) -AO_CHANNELS = NIDAQmx.get_NIDAQ_channels(source_type=ChannelType.ANALOG_OUTPUT) -COUNTER_CHANNELS = NIDAQmx.get_NIDAQ_channels(source_type=ChannelType.COUNTER_OUTPUT) +AO_CHANNELS = NIDAQSystem().all_channels(ChannelKind.AO) +COUNTER_CHANNELS = NIDAQSystem().all_channels(ChannelKind.CO) class DAQ_Move_NIDAQmx_RampOutput(DAQ_Move_base): diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_Move.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_Move.py deleted file mode 100644 index db72c3c..0000000 --- a/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_Move.py +++ /dev/null @@ -1,188 +0,0 @@ -from easydict import EasyDict as edict -from .daqmxni import NIDAQmx -from pymodaq.utils.data import DataActuator -from pymodaq.utils.daq_utils import ThreadCommand, getLineInfo -from pymodaq.control_modules.move_utility_classes import DAQ_Move_base -from pymodaq.control_modules.move_utility_classes import comon_parameters_fun as actuator_params -from pymodaq_plugins_daqmx.hardware.national_instruments.NIDAQmx_base import DAQ_NIDAQmx_base -from pymodaq.utils.logger import set_logger, get_module_name -logger = set_logger(get_module_name(__file__)) - -class DAQ_NIDAQmx_Actuator(DAQ_Move_base, DAQ_NIDAQmx_base): - """ - Wrapper object to access the Mock fonctionnalities, similar wrapper for all controllers. - - =============== ============== - **Attributes** **Type** - *params* dictionnary - =============== ============== - """ - _controller_units = 'V' - is_multiaxes = False # set to True if this plugin is controlled for a multiaxis controller (with a unique communication link) - stage_names = [] # "list of strings of the multiaxes - - params = DAQ_NIDAQmx_base.params +[ - # elements to be added here as dicts in order to control your custom stage - ############ - {'title': 'MultiAxes:', 'name': 'multiaxes', 'type': 'group', 'visible': is_multiaxes, - 'children': [ - {'title': 'is Multiaxes:', 'name': 'ismultiaxes', 'type': 'bool', 'value': is_multiaxes, - 'default': False}, - {'title': 'Status:', 'name': 'multi_status', 'type': 'list', 'value': 'Master', - 'limits': ['Master', 'Slave']}, - {'title': 'Axis:', 'name': 'axis', 'type': 'list', 'limits': stage_names}, - - ]}] + actuator_params() - - def __init__(self, parent=None, params_state=None, control_type="Actuator"): - DAQ_Move_base.__init__(self, parent, params_state) # defines settings attribute and various other methods - DAQ_NIDAQmx_base.__init__(self) - - self.control_type = "Actuator" # could be "0D", "1D" or "Actuator" - self.settings.child('NIDAQ_type').setLimits(['Analog_Output', 'Digital_Output']) - - self.settings.child('clock_settings', 'Nsamples').setValue(1) - - def get_actuator_value(self) -> DataActuator: - """Get the current position from the hardware with scaling conversion. - - Returns - ------- - float: The position obtained after scaling conversion. - """ - ## TODO: Reimplement in your daq_move with NIDAQmx library - pos = self.target_position - ## - - pos = self.get_position_with_scaling(pos) - self.emit_status(ThreadCommand('check_position', [pos])) - return pos - - - def commit_settings(self, param): - """ - | Activate any parameter changes on the PI_GCS2 hardware. - | - | Called after a param_tree_changed signal from DAQ_Move_main. - - """ - ## TODO: Reimplement in your daq_move with NIDAQmx library - DAQ_NIDAQmx_base.commit_settings(self, param) - if param.parent() is not None: - if param.parent().name() == 'ao_channels': - device = param.opts['title'].split('/')[0] - self.settings.child('clock_settings', 'frequency').setOpts(max=self.getAOMaxRate(device)) - - volt_ranges = self.controller.getAOVoltageRange(device) - curr_ranges = self.controller.getA0CurrentRange(device) - try: - param.child('voltage_settings', 'volt_min').setValue(volt_ranges[0]) - param.child('voltage_settings', 'volt_max').setValue(volt_ranges[1]) - param.child('current_settings', 'curr_min').setValue(curr_ranges[0]) - param.child('current_settings', 'curr_max').setValue(curr_ranges[1]) - except: - pass - - def ini_stage(self, controller=None): - """Actuator communication initialization - - Parameters - ---------- - controller: (object) custom object of a PyMoDAQ plugin (Slave case). None if only one actuator by controller (Master case) - - Returns - ------- - self.status (edict): with initialization status: three fields: - * info (str) - * controller (object) initialized controller - * initialized: (bool): False if initialization failed otherwise True - - """ - try: - # initialize the stage and its controller status - # controller is an object that may be passed to other instances of DAQ_Move_Mock in case - # of one controller controlling multiactuators (or detector) - - self.status.update(edict(info="", controller=None, initialized=False)) - - # check whether this stage is controlled by a multiaxe controller (to be defined for each plugin) - # if multiaxes then init the controller here if Master state otherwise use external controller - if self.is_multiaxes and not self.is_master: - if controller is None: - raise Exception('no controller has been defined externally while this axe is a slave one') - else: - self.controller = controller - else: - self.controller = NIDAQmx() - - # actions to perform in order to set properly the settings tree options - self.commit_settings(self.settings.child('NIDAQ_type')) - - self.status.info = "Plugin Initialized" - self.status.controller = self.controller - self.status.initialized = True - return self.status - - except Exception as e: - self.emit_status(ThreadCommand('Update_Status', [getLineInfo() + str(e), 'log'])) - self.status.info = getLineInfo() + str(e) - self.status.initialized = False - return self.status - - def move_Abs(self, position): - """ Move the actuator to the absolute target defined by position - - Parameters - ---------- - position: (flaot) value of the absolute target positioning - """ - ## TODO: Reimplement in your daq_move with NIDAQmx library - raise NotImplementedError - - def move_done_callback(self, taskhandle, status, callbackdata): - ## TODO: Reimplement in your daq_move with NIDAQmx library - raise NotImplementedError - - def move_Rel(self, position): - """ Move the actuator to the relative target actuator value defined by position - - Parameters - ---------- - position: (flaot) value of the relative target positioning - """ - ## TODO: Reimplement in your daq_move with NIDAQmx library - raise NotImplementedError - - def move_Home(self): - """ - Send the update status thread command. - See Also - -------- - daq_utils.ThreadCommand - """ - ## TODO: Reimplement in your daq_move with NIDAQmx library - raise NotImplementedError - - def close(self): - """Terminate the communication protocol: close the current task of the controller""" - controller = getattr(self, 'controller', None) - if controller is not None: - controller.close() - - def stop_motion(self): - """ - Call the specific move_done function (depending on the hardware). - - See Also - -------- - move_done - """ - """Stop the current grab hardware wise if necessary""" - try: - DAQ_NIDAQmx_base.stop(self) - self.move_done() # to let the interface know the actuator stopped - logger.info("Motion stopped.") - except Exception: - pass - self.emit_status(ThreadCommand('Update_Status', ['Motion stopped.'])) - return '' diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_Viewer.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_Viewer.py deleted file mode 100644 index 1d885f7..0000000 --- a/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_Viewer.py +++ /dev/null @@ -1,401 +0,0 @@ -import traceback - -from pymodaq_plugins_daqmx.hardware.national_instruments.daqmxni import niDevice, niSystem, ProductCategory -from pymodaq_plugins_daqmx.hardware.national_instruments.NIDAQmx_base import NIDAQmx, DAQ_NIDAQmx_base, \ - TerminalConfiguration, UsageTypeAI, ChannelType, RTDType -from pymodaq.control_modules.viewer_utility_classes import DAQ_Viewer_base, comon_parameters as viewer_params -from pymodaq.utils.daq_utils import ThreadCommand -from pymodaq.utils.logger import set_logger, get_module_name - -from pymodaq_utils import config as utils_config -from pymodaq_plugins_daqmx import config as daqmx_config -from pathlib import WindowsPath - -logger = set_logger(get_module_name(__file__)) - - -def merge_dicts_recursive(original: dict, update: dict) -> dict: - """ - Recursively merges two dictionaries. - - Keys/values from `update` add or modify those in `original`. - - Empty values (None, {}, [], etc.) in `update` are ignored. - - Nested dictionaries are merged recursively. - """ - merged = original.copy() # Start with a copy of the original to avoid mutation - for key, value in update.items(): - # Skip empty values (None, empty dict, empty list, etc.) - if value is None or (isinstance(value, (dict, list, set)) and not value): - continue - - # If the key exists in both dictionaries and both values are dictionaries, - # recursively merge them - if key in merged and isinstance(merged[key], dict) and isinstance(value, dict): - merged[key] = merge_dicts_recursive(merged[key], value) - else: - # Otherwise, overwrite or add the value - merged[key] = value - return merged - - -class DAQ_NIDAQmx_Viewer(DAQ_Viewer_base, DAQ_NIDAQmx_base): - """ - ==================== ======================== - **Attributes** **Type** - *data_grabed_signal* instance of Signal - *params* dictionary list - *task* - ==================== ======================== - - See Also - -------- - refresh_hardware - """ - config_channels: list - controller: NIDAQmx - config_devices: list - config_modules: list - live: bool - Naverage: int - param_devices = NIDAQmx.get_NIDAQ_devices().device_names - params = viewer_params + [ - {'title': 'Devices :', 'name': 'devices', 'type': 'list', 'limits': param_devices, - 'value': param_devices[0] if param_devices else '' - }, - ] + DAQ_NIDAQmx_base.params - - def __init__(self, parent=None, params_state=None, control_type="0D"): - DAQ_Viewer_base.__init__(self, parent, params_state) # defines settings attribute and various other methods - DAQ_NIDAQmx_base.__init__(self) - - self.Naverage = None - self.live = False - self.control_type = control_type # could be "0D", "1D" - if self.control_type == "0D": - self.settings.child('NIDAQ_type').setLimits([ChannelType.ANALOG_INPUT.name, - ChannelType.COUNTER_INPUT.name, - ChannelType.DIGITAL_INPUT.name]) - elif self.control_type == "1D": - self.settings.child('NIDAQ_type').setLimits([ChannelType.ANALOG_INPUT.name]) - - self.settings.child('ao_settings').hide() - self.settings.child('ao_channels').hide() - - def ini_attributes(self): - super().ini_attributes() - self.config_channels = [] - self.config_devices = [] - self.config_modules = [] - self.live = False - self.Naverage = 1 - - def ini_detector(self, controller=None): - """ - Initialisation procedure of the detector. - - See Also - -------- - daq_utils.ThreadCommand - """ - try: - if self.is_master: - self.controller = NIDAQmx() - else: - self.controller = controller - self.controller.device = niDevice(self.settings["devices"]) - - # actions to perform in order to set properly the settings tree options - self.commit_settings(self.settings.child('NIDAQ_type')) - - info = "Plugin Initialized" - initialized = True - logger.info("Detector {} initialized".format(self.control_type)) - return info, initialized - - except Exception as e: - logger.info(traceback.format_exc()) - self.emit_status(ThreadCommand('Update_Status', [str(e), 'log'])) - info = str(e) - initialized = False - return info, initialized - - def commit_settings(self, param): - """ - Activate the parameters changes in the hardware. - - =============== ================================ =========================== - **Parameters** **Type** **Description** - *param* instance of pyqtgraph.parameter the parameter to activate - =============== ================================ =========================== - - See Also - -------- - update_NIDAQ_channels, update_task, refresh_hardware - """ - DAQ_NIDAQmx_base.commit_settings(self, param) - - if param.parent() is not None: - if param.parent().name() == 'ai_channels': - device = param.opts['title'].split('/')[0] - self.settings.child('clock_settings', 'frequency').setOpts(max=self.controller.getAIMaxSingleRate(device)) - volt_ranges = self.controller.getAIVoltageRange(device) - if volt_ranges: - param.child('voltage_settings', 'volt_min').setValue(volt_ranges[0]) - param.child('voltage_settings', 'volt_max').setValue(volt_ranges[1]) - curr_ranges = self.controller.getAICurrentRange(device) - if curr_ranges: - param.child('current_settings', 'curr_min').setValue(curr_ranges[0]) - param.child('current_settings', 'curr_max').setValue(curr_ranges[1]) - elif param.name() == 'devices': - self.controller.device = niDevice(self.settings["devices"]) - elif param.name() == 'load_config': - self.controller.configuration_sequence(self, self.controller.device) - self.settings.child('load_config').hide() - config_ai_channels = [ch for ch in self.config_channels if ch.source == ChannelType.ANALOG_INPUT] - for ch in config_ai_channels: # Browse configuration analog channels - self.settings.child('ai_channels').addNew(ch.name) - ch_par = [a for a in self.settings.child('ai_channels').childs if a.opts['title'] == ch.name][0] - ch_par.child("voltage_settings").show(ch.analog_type == UsageTypeAI.VOLTAGE) - ch_par.child("current_settings").show(ch.analog_type == UsageTypeAI.CURRENT) - ch_par.child("thermoc_settings").show(ch.analog_type == UsageTypeAI.TEMPERATURE_THERMOCOUPLE) - ch_par.child("rtd_settings").show(ch.analog_type == UsageTypeAI.TEMPERATURE_RTD) - match ch.analog_type: - case UsageTypeAI.VOLTAGE: - self.settings.child("ai_channels", ch_par.opts['name'], "ai_type").setValue("VOLTAGE") - self.settings.child("ai_channels", ch_par.opts['name'], "voltage_settings", - "volt_min").setValue( - ch.value_min) - self.settings.child("ai_channels", ch_par.opts['name'], "voltage_settings", - "volt_max").setValue( - ch.value_max) - self.settings.child("ai_channels", ch_par.opts['name'], "termination").setValue( - ch.termination.name) - case UsageTypeAI.CURRENT: - self.settings.child("ai_channels", ch_par.opts['name'], "ai_type").setValue("CURRENT") - self.settings.child("ai_channels", ch_par.opts['name'], "current_settings", - "curr_min").setValue( - ch.value_min) - self.settings.child("ai_channels", ch_par.opts['name'], "current_settings", - "curr_max").setValue( - ch.value_max) - self.settings.child("ai_channels", ch_par.opts['name'], "termination").setValue( - ch.termination.name) - case UsageTypeAI.TEMPERATURE_THERMOCOUPLE: - self.settings.child("ai_channels", ch_par.opts['name'], "ai_type").setValue( - "TEMPERATURE_THERMOCOUPLE") - self.settings.child("ai_channels", - ch_par.opts['name'], - "thermoc_settings", - "thermoc_type").setValue(ch.thermo_type.name) - self.settings.child("ai_channels", - ch_par.opts['name'], - "thermoc_settings", - "T_min").setValue(ch.value_min) - self.settings.child("ai_channels", - ch_par.opts['name'], - "thermoc_settings", - "T_max").setValue(ch.value_max) - self.settings.child("ai_channels", ch_par.opts['name'], "termination").setValue( - TerminalConfiguration.DEFAULT.name) - case UsageTypeAI.TEMPERATURE_RTD: - ch_par.child("rtd_settings", "c-vd_coeff.").show(ch.rtd_type == RTDType.CUSTOM) - self.settings.child("ai_channels", ch_par.opts['name'], "ai_type").setValue( - "TEMPERATURE_RTD") - self.settings.child("ai_channels", - ch_par.opts['name'], - "rtd_settings", - "min_value_in").setValue(ch.value_min) - self.settings.child("ai_channels", - ch_par.opts['name'], - "rtd_settings", - "max_value_in").setValue(ch.value_max) - self.settings.child("ai_channels", - ch_par.opts['name'], - "rtd_settings", - "temp_unit").setValue(ch.units.name) - self.settings.child("ai_channels", - ch_par.opts['name'], - "rtd_settings", - "resistance_config").setValue(ch.resistance_config.name) - self.settings.child("ai_channels", - ch_par.opts['name'], - "rtd_settings", - "r0").setValue(ch.r_0) - self.settings.child("ai_channels", - ch_par.opts['name'], - "rtd_settings", - "rtd_type").setValue(ch.rtd_type.name) - self.settings.child("ai_channels", - ch_par.opts['name'], - "rtd_settings", "c-vd_coeff.", - "a_c-vd_coeff").setValue(ch.a_cvd_coeff) - self.settings.child("ai_channels", - ch_par.opts['name'], - "rtd_settings", "c-vd_coeff.", - "b_c-vd_coeff").setValue(ch.b_cvd_coeff) - self.settings.child("ai_channels", - ch_par.opts['name'], - "rtd_settings", "c-vd_coeff.", - "c_c-vd_coeff").setValue(ch.c_cvd_coeff) - self.settings.child("ai_channels", - ch_par.opts['name'], - "rtd_settings", - "current_excit_src").setValue(ch.current_excit_source.name) - self.settings.child("ai_channels", - ch_par.opts['name'], - "rtd_settings", - "i_ex_value").setValue(ch.current_excit_val) - self.settings.child("ai_channels", ch_par.opts['name'], "termination").setValue( - TerminalConfiguration.DEFAULT.name) - self.channels = self.get_channels_from_settings() - self.set_max_frequency() # Set the acquisition frequency to the device maximum frequency - - elif param.name() == 'save_config' and param.value(): - logger.info("********** CONFIGURATION BACKING UP SEQUENCE INITIALIZED **********") - try: - config_dict = {'title': 'Configuration file of the DAQmx plugin', 'NIDAQ_Devices': {}} - devices_collection = niSystem.local().devices - - # CONFIGURATION OF THE "DEVICES" - for device in devices_collection: - if device.product_category == ProductCategory.COMPACT_DAQ_CHASSIS: - device_name = device.name - device_product = device.product_type - dev_dict_len = len(config_dict['NIDAQ_Devices']) - if dev_dict_len < 9: - toml_subsection_extension_name = "DEVICE0" + str(dev_dict_len + 1) - elif dev_dict_len < 99: - toml_subsection_extension_name = "DEVICE" + str(dev_dict_len + 1) - config_dict['NIDAQ_Devices'][toml_subsection_extension_name] = \ - {'title': "Configuration entry for a NIDAQmx device", 'name': device_name, - 'product': device_product} - - # CONFIGURATION OF THE MODULES - temporary_NIDAQ_devices_length = len(config_dict['NIDAQ_Devices']['DEVICE01']) # there is supposed at least one chassis to be plugged - modules_dict = {} - for device in devices_collection: - if device.product_category == ProductCategory.C_SERIES_MODULE: - cDAQ_chassis_name = device.compact_daq_chassis_device.name - for ni_daq_device in config_dict['NIDAQ_Devices']: - if config_dict['NIDAQ_Devices'][ni_daq_device]['name'] == cDAQ_chassis_name: - module_number = len(config_dict['NIDAQ_Devices'][ni_daq_device]) - temporary_NIDAQ_devices_length - toml_subsection_extension_name = "MODULE0" + str(module_number + 1) # there is supposed to be no more than 9 modules on a device - config_dict['NIDAQ_Devices'][ni_daq_device][toml_subsection_extension_name] = \ - {'title': 'Example of module plugged in a NIDAQmx device', - 'name': device.name, - 'product': device.product_type} - modules_dict[device.name] = {'chassis_id' : ni_daq_device, 'module_id': toml_subsection_extension_name} # <- à utiliser pour suites dev - - # CONFIGURATION OF THE DAQmx CHANNELS - cfs_list = self.get_channels_from_settings(from_all_devices=True) # "cfs" for "channels from settings" - abbrev_chan_type_dict = {ChannelType.ANALOG_INPUT : 'ai', - ChannelType.ANALOG_OUTPUT : 'ao', - ChannelType.COUNTER_INPUT : 'ci', - ChannelType.COUNTER_OUTPUT : 'co', - ChannelType.DIGITAL_INPUT : 'di', - ChannelType.DIGITAL_OUTPUT : 'do'} - for cfs in cfs_list: - config_string_to_write = "" - cfs_config_dict = {} - cfs_name = cfs.name - cfs_source = cfs.source.name - if cfs.source in [ChannelType.ANALOG_INPUT, ChannelType.ANALOG_OUTPUT]: - cfs_analog_type = cfs.analog_type.name - cfs_value_min = cfs.value_min - cfs_value_max = cfs.value_max - config_string_to_write += 'name = "' + str(cfs_name) + '"\n' + "" \ - 'source = "' + str(cfs_source) + '"\n' + "" \ - 'analog_type = "' + str(cfs_analog_type) + '"\n' + "" \ - 'value_min = ' + str(cfs_value_min) + '\n' + "" \ - 'value_max = ' + str(cfs_value_max) + '\n' - cfs_config_dict['name'] = cfs_name - cfs_config_dict['source'] = cfs_source - cfs_config_dict['analog_type'] = cfs_analog_type - cfs_config_dict['value_min'] = cfs_value_min - cfs_config_dict['value_max'] = cfs_value_max - if cfs.source == ChannelType.ANALOG_INPUT: - cfs_termination = cfs.termination.name - match cfs.analog_type: - case UsageTypeAI.CURRENT: - cfs_info = "Example of AI current channel" - cfs_config_dict['termination'] = cfs_termination - case UsageTypeAI.VOLTAGE: - cfs_info = "Example of AI voltage channel" - cfs_config_dict['termination'] = cfs_termination - case UsageTypeAI.TEMPERATURE_THERMOCOUPLE: - cfs_info = "Example of AI thermocouple channel" - cfs_thermo_type = cfs.thermo_type.name - cfs_config_dict['thermo_type'] = cfs_thermo_type - config_string_to_write += 'thermo_type = "' + str(cfs_thermo_type) + '"\n' - # The other AI type cases are still to implement - else: - pass # to complete (for analog outputs, and counter or digital channels) - cfs_config_dict['info'] = cfs_info - [module_name, physical_chan_name] = cfs_name.split('/') - chassis_id = modules_dict[module_name]['chassis_id'] - module_id = modules_dict[module_name]['module_id'] - abbrev_chan_type = abbrev_chan_type_dict[cfs.source] - if abbrev_chan_type not in config_dict['NIDAQ_Devices'][chassis_id][module_id]: - config_dict['NIDAQ_Devices'][chassis_id][module_id][abbrev_chan_type] = {} - chan_num_str = physical_chan_name.strip('ai') - if int(chan_num_str) < 10: - chan_id_num = "0" + chan_num_str - # if chan_type_dict_len < 9: - # chan_id_num = "0" + str(chan_type_dict_len + 1) - else : - chan_id_num = chan_num_str # there is supposed to be no more than 99 channels on one module - chan_id = abbrev_chan_type+chan_id_num - config_dict['NIDAQ_Devices'][chassis_id][module_id][abbrev_chan_type][physical_chan_name] = cfs_config_dict - - merged_config = merge_dicts_recursive(original=daqmx_config(), update=config_dict) - daqmx_config().update(merged_config) - daqmx_config.save() - config_file_path = daqmx_config.config_path - utils_config.create_toml_from_dict(daqmx_config(), config_file_path) - logger.info("********** CONFIGURATION BACKING UP SEQUENCE SUCCESSFULLY ENDED **********") - except Exception as err: - logger.info("Configuration sequence error, verify if your config matches the hardware: {}".format(err)) - param.setValue(not param.value()) # button mechanical action : it turns back to its value before user click - self.channels = self.get_channels_from_settings() - self.get_max_frequency() # Set the frequency 'max' option to the device maximum frequency and display it - - def get_max_frequency(self): - """ - Get the maximum frequency according to the material's limits and display the information. - This method is destined to be removed once set_max_frequency will work correctly. - """ - # Destined to be removed when set_max_frequency will work correctly - try: - max_freq = int(self.controller.getAIMaxSingleRate(self.controller.device.name)) - self.settings.child('clock_settings', 'max_freq').setValue(max_freq) - except: - pass - - def set_max_frequency(self): - """ - Set the maximum frequency applicable to the frequency parameter according to material's limits. - """ - # Opts 'max' get the right value but doesn't update the viewer which keep as max the initial max value - try: - max_freq = int(self.controller.getAIMaxSingleRate(self.controller.device.name)) - self.settings.child('clock_settings', 'frequency').setOpts(max=max_freq) - self.settings.child('clock_settings', 'frequency').emitStateChanged('max', max_freq) - self.settings.child('clock_settings', 'frequency')._emitOptionsChanged( - self.settings.child('clock_settings', 'frequency'), {'max': max_freq}) - except: - pass - - def stop(self): - """Stop the current grab hardware wise if necessary""" - try: - DAQ_NIDAQmx_base.stop(self) - self.live = False - logger.info("Acquisition stopped.") - except Exception: - pass - self.emit_status(ThreadCommand('Update_Status', ['Acquisition stopped.'])) - return '' - - def close(self): - self.live = False - self.stop() - self.controller.close() diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_base.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_base.py deleted file mode 100644 index da4a222..0000000 --- a/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_base.py +++ /dev/null @@ -1,507 +0,0 @@ -from qtpy import QtWidgets -from qtpy.QtCore import Signal -from pymodaq_utils.logger import set_logger, get_module_name -from pymodaq_gui.parameter import Parameter -from pymodaq_gui.parameter.pymodaq_ptypes import registerParameterType, GroupParameter -from pymodaq_plugins_daqmx.hardware.national_instruments.daqmxni import NIDAQmx, Edge, ChannelType, ClockSettings, \ - AIChannel, AIThermoChannel, AOChannel, CIChannel, COChannel, DOChannel, DIChannel, UsageTypeAI, UsageTypeAO, \ - ThermocoupleType, TerminalConfiguration, TriggerSettings, RTDType, TemperatureUnits, \ - ResistanceConfiguration, ExcitationSource , AI_RTD_Channel - - -logger = set_logger(get_module_name(__file__)) - - -class ScalableGroupAI(GroupParameter): - - """ - Generic parameter items holding Analog Input parameters - """ - - params = [{'title': 'AI type:', 'name': 'ai_type', 'type': 'list', 'visible': True, 'limits': [Uai.name for Uai in UsageTypeAI]}, - {'title': 'VOLTAGE:', 'name': 'voltage_settings', 'type': 'group', 'visible': False, 'children': [ - {'title': 'Voltage Min:', 'name': 'volt_min', 'type': 'float', 'value': -5, 'suffix': 'V'}, - {'title': 'Voltage Max:', 'name': 'volt_max', 'type': 'float', 'value': 5, 'suffix': 'V'}, - ]}, - {'title': 'CURRENT:', 'name': 'current_settings', 'type': 'group', 'visible': False, 'children': [ - {'title': 'Current Min:', 'name': 'curr_min', 'type': 'float', 'value': -1, 'suffix': 'A'}, - {'title': 'Current Max:', 'name': 'curr_max', 'type': 'float', 'value': 1, 'suffix': 'A'}, - ]}, - {'title': 'TEMPERATURE_THERMOCOUPLE:', 'name': 'thermoc_settings', 'type': 'group', 'visible': False, 'children': [ - {'title': 'Thc. type:', 'name': 'thermoc_type', 'type': 'list', - 'limits': [Th.name for Th in ThermocoupleType], 'value': 'K'}, - {'title': 'Temp. Min:', 'name': 'T_min', 'type': 'float', 'value': 0, 'suffix': '°C'}, - {'title': 'Temp. Max:', 'name': 'T_max', 'type': 'float', 'value': 50, 'suffix': '°C'}, - ]}, - {'title': 'TEMPERATURE_RTD:', 'name': 'rtd_settings', 'type': 'group', 'visible': False, - 'children': [ - {'title': 'Min. value in:', 'name': 'min_value_in', 'type': 'float', 'value': '0'}, - {'title': 'Max. value in:', 'name': 'max_value_in', 'type': 'float', 'value': '100'}, - {'title': 'Temp. unit:', 'name': 'temp_unit', 'type': 'list', - 'limits': [TemperatureUnits.DEG_C.name, TemperatureUnits.DEG_F.name], - 'value': TemperatureUnits.DEG_C.name}, - {'title': 'r0', 'name': 'r0', 'type': 'float', 'value': 100, 'suffix': 'Ω'}, - {'title': 'RTD type:', 'name': 'rtd_type', 'type': 'list', - 'limits': [rtd_type.name for rtd_type in RTDType], 'value': RTDType.PT_3750.name}, - {'title': 'Callendar-Van Dusen coefficients:', 'name': 'c-vd_coeff.', 'type': 'group', - 'visible': False, 'children': [ - # These coefficients are supposed to be used in a Callendar-Van Dusen equation in °C, - # cf. https://www.ni.com/docs/fr-FR/bundle/ni-daqmx/page/callendarvandusen.html (Oct. 2025) - {'title': 'A', 'name': 'a_c-vd_coeff', 'type': 'float', 'suffix': '°C⁻¹'}, - {'title': 'B', 'name': 'b_c-vd_coeff', 'type': 'float', 'suffix': '°C⁻²'}, - {'title': 'C', 'name': 'c_c-vd_coeff', 'type': 'float', 'suffix': '°C⁻⁴'}, - ]}, - {'title': 'Resistance config.', 'name': 'resistance_config', 'type': 'list', - 'limits': [rc.name for rc in ResistanceConfiguration], - 'value': ResistanceConfiguration.FOUR_WIRE.name}, - {'title': 'Curr. excit. src', 'name': 'current_excit_src', 'type': 'list', - 'limits': [excit_src.name for excit_src in ExcitationSource], - 'value': ExcitationSource.INTERNAL.name}, - {'title': 'Iex value', 'name': 'i_ex_value', 'type': 'float', 'value': 0.00100, 'suffix': 'A'}, - ]}, - {'title': 'Termination:', 'name': 'termination', 'type': 'list', - 'limits': [Te.name for Te in TerminalConfiguration]}, - ] - - def __init__(self, **opts): - opts['type'] = 'groupai' - opts['addText'] = "Add" - opts['addList'] = opts['limits'] - GroupParameter.__init__(self, **opts) - - def addNew(self, typ=None): - """ - Add a child. - - =============== =========== - **Parameters** **Type** - *typ* string - =============== =========== - """ - child = {'title': typ, 'name': '{}'.format(typ.replace("/", "_")), 'type': 'group', 'children': self.params, - 'removable': True, 'renamable': False} - - self.addChild(child) - - -registerParameterType('groupai', ScalableGroupAI, override=True) - - -class ScalableGroupAO(GroupParameter): - """ - Generic parameter items holding Analog Output parameters - """ - - params = [{'title': 'AO type:', 'name': 'ao_type', 'type': 'list', 'limits': [Uao.name for Uao in UsageTypeAO]}, - {'title': 'VOLTAGE:', 'name': 'voltage_settings', 'type': 'group', 'children': [ - {'title': 'Voltage Min:', 'name': 'volt_min', 'type': 'list', 'value': -10., 'suffix': 'V'}, - {'title': 'Voltage Max:', 'name': 'volt_max', 'type': 'list', 'value': 10., 'suffix': 'V'}, - ]}, - {'title': 'CURRENT:', 'name': 'current_settings', 'type': 'group', 'visible': False, 'children': [ - {'title': 'Current Min:', 'name': 'curr_min', 'type': 'float', 'value': -1, 'suffix': 'A'}, - {'title': 'Current Max:', 'name': 'curr_max', 'type': 'float', 'value': 1, 'suffix': 'A'}, - ]}, - ] - - def __init__(self, **opts): - opts['type'] = 'groupao' - opts['addText'] = "Add" - opts['addList'] = opts['limits'] - GroupParameter.__init__(self, **opts) - - def addNew(self, typ=None): - """ - Add a child. - - =============== =========== - **Parameters** **Type** - *typ* string - =============== =========== - """ - child = {'title': typ, 'name': 'ao{:02.0f}'.format(typ.replace("/", "_")), 'type': 'group', 'children': self.params, - 'removable': True, 'renamable': False} - - self.addChild(child) - - -registerParameterType('groupao', ScalableGroupAO, override=True) - - -class ScalableGroupCounter(GroupParameter): - """ - Generic parameter items holding Counter parameters - """ - - params = [{'title': 'Edge type:', 'name': 'edge', 'type': 'list', 'limits': [e.name for e in Edge]}, ] - - def __init__(self, **opts): - opts['type'] = 'groupcounter' - opts['addText'] = "Add" - opts['addList'] = opts['limits'] - GroupParameter.__init__(self, **opts) - - def addNew(self, typ=None): - """ - Add a child. - - =============== =========== - **Parameters** **Type** - *typ* string - =============== =========== - """ - child = {'title': typ, 'name': 'counter{:02.0f}'.format(typ.replace("/", "_")), 'type': 'group', 'children': self.params, - 'removable': True, 'renamable': False} - - self.addChild(child) - - -registerParameterType('groupcounter', ScalableGroupCounter, override=True) - - -class ScalableGroupDI(GroupParameter): - """ - Generic parameter items holding Digital Input parameters - """ - - params = [] - - def __init__(self, **opts): - opts['type'] = 'groupdi' - opts['addText'] = "Add" - opts['addList'] = opts['limits'] - GroupParameter.__init__(self, **opts) - - def addNew(self, typ=None): - """ - Add a child. - - =============== =========== - **Parameters** **Type** - *typ* string - =============== =========== - """ - child = {'title': typ, 'name': 'di{:02.0f}'.format(typ.replace("/", "_")), 'type': 'group', 'children': self.params, - 'removable': True, 'renamable': False} - self.addChild(child) - - -registerParameterType('groupdi', ScalableGroupDI, override=True) - - -class ScalableGroupDO(GroupParameter): - """ - Generic parameter items holding Digital Output parameters - """ - - params = [] - - def __init__(self, **opts): - opts['type'] = 'groupdo' - opts['addText'] = "Add" - opts['addList'] = opts['limits'] - GroupParameter.__init__(self, **opts) - - def addNew(self, typ=None): - """ - Add a child. - - =============== =========== - **Parameters** **Type** - *typ* string - =============== =========== - """ - child = {'title': typ, 'name': 'counter{:02.0f}'.format(typ.replace("/", "_")), 'type': 'group', 'children': self.params, - 'removable': True, 'renamable': False} - self.addChild(child) - - -registerParameterType('groupdo', ScalableGroupDO, override=True) - - -class DAQ_NIDAQmx_base: - """ - Base NIDAQmx class for using DAQmx objects from daqmxni.py in the DAQ_NIDAQmx_Move & DAQ_NIDAQmx_Viewer - """ - data_grabed_signal = Signal(list) - params = [{'title': 'Refresh hardware:', 'name': 'refresh_hardware', 'type': 'bool', 'value': False}, - {'title': 'Signal type:', 'name': 'NIDAQ_type', 'type': 'list', - 'limits': [Ds.name for Ds in ChannelType]}, - {'title': 'Save plugin config:', 'name': 'save_config', 'type': 'bool_push', 'value': False, - 'readonly': False, 'label': 'Save Config'}, - {'title': 'Plugin config:', 'name': 'load_config', 'type': 'bool_push', 'value': False, - 'readonly': False, 'label': 'Load Config'}, - {'title': 'NSamples To Read:', 'name': 'nsamplestoread', 'type': 'int', 'value': 10, 'default': 10, - 'min': 1}, - {'title': 'AO Settings:', 'name': 'ao_settings', 'type': 'group', 'children': [ - {'title': 'Waveform:', 'name': 'waveform', 'type': 'list', 'value': 'DC', - 'limits': ['DC', 'Sinus', 'Ramp']}, - {'title': 'Controlled param:', 'name': 'cont_param', 'type': 'list', 'value': 'offset', - 'limits': ['offset', 'amplitude', 'frequency']}, - {'title': 'Waveform Settings:', 'name': 'waveform_settings', 'type': 'group', 'visible': False, - 'children': [ - {'title': 'Offset:', 'name': 'offset', 'type': 'float', 'value': 0., }, - {'title': 'Amplitude:', 'name': 'amplitude', 'type': 'float', 'value': 1., }, - {'title': 'Frequency:', 'name': 'frequency', 'type': 'float', 'value': 10., }, - ]}, - ]}, - {'title': 'Clock Settings:', 'name': 'clock_settings', 'type': 'group', 'children': [ - {'title': 'Nsamples:', 'name': 'Nsamples', 'type': 'int', 'value': 10, 'default': 10, 'min': 1}, - {'title': 'Max frequency supported:', 'name': 'max_freq', 'type': 'float', 'value': 10., - 'readonly': True, 'suffix': 'Hz'}, - {'title': 'Frequency:', 'name': 'frequency', 'type': 'float', 'value': 10., 'default': 10., - 'min': 0., 'max': 10e5, 'suffix': 'Hz'}, - ] - }, - {'title': 'AI Channels:', 'name': 'ai_channels', 'type': 'groupai', - 'limits': NIDAQmx.get_NIDAQ_channels(source_type=ChannelType.ANALOG_INPUT)}, - {'title': 'AO Channels:', 'name': 'ao_channels', 'type': 'groupao', - 'limits': NIDAQmx.get_NIDAQ_channels(source_type=ChannelType.ANALOG_OUTPUT)}, - {'title': 'DO Channels:', 'name': 'do_channels', 'type': 'groupdo', - 'limits': NIDAQmx.get_NIDAQ_channels(source_type=ChannelType.DIGITAL_OUTPUT)}, - {'title': 'DI Channels:', 'name': 'di_channels', 'type': 'groupdi', - 'limits': NIDAQmx.get_NIDAQ_channels(source_type=ChannelType.DIGITAL_INPUT)}, - {'title': 'Counter Settings:', 'name': 'counter_settings', 'type': 'group', 'visible': True, 'children': [ - {'title': 'Counting time (ms):', 'name': 'counting_time', 'type': 'float', 'value': 100., - 'default': 100., 'min': 0.}, - {'title': 'CI Channels:', 'name': 'ci_channels', 'type': 'groupcounter', - 'limits': NIDAQmx.get_NIDAQ_channels(source_type=ChannelType.COUNTER_INPUT)}, - {'title': 'CO Channels:', 'name': 'co_channels', 'type': 'groupcounter', - 'limits': NIDAQmx.get_NIDAQ_channels(source_type=ChannelType.COUNTER_OUTPUT)}, - ]}, - {'title': 'Trigger Settings:', 'name': 'trigger_settings', 'type': 'group', 'visible': True, 'children': [ - {'title': 'Enable?:', 'name': 'enable', 'type': 'bool', 'value': False, }, - {'title': 'Trigger Source:', 'name': 'trigger_channel', 'type': 'list', - 'limits': NIDAQmx.getTriggeringSources()}, - {'title': 'Edge type:', 'name': 'edge', 'type': 'list', 'limits': [e.name for e in Edge], - 'visible': False}, - {'title': 'Level:', 'name': 'level', 'type': 'float', 'value': 1., 'visible': False} - ]} - ] - - def __init__(self): - super().__init__() - - self.timer = None - self.channels = None - self.clock_settings = None - self.trigger_settings = None - self.live = False - - def commit_settings(self, param: Parameter): - """ - Activate the parameters changes in the hardware. - - =============== ================================ =========================== - **Parameters** **Type** **Description** - *param* instance of pyqtgraph.parameter the parameter to activate - =============== ================================ =========================== - - See Also - -------- - update_NIDAQ_channels, update_task, DAQ_NIDAQ_source, refresh_hardware - """ - if param.name() == 'NIDAQ_devices': - self.controller.update_NIDAQ_channels() - - if param.name() == 'NIDAQ_type': - self.controller.update_NIDAQ_channels(param.value()) - if param.value() == ChannelType.ANALOG_INPUT.name: # analog input - self.settings.child('clock_settings').show() - self.settings.child('ai_channels').show() - self.settings.child('ao_channels').hide() - self.settings.child('ao_settings').hide() - self.settings.child('counter_settings').hide() - self.settings.child('do_channels').hide() - self.settings.child('di_channels').hide() - - elif param.value() == ChannelType.ANALOG_OUTPUT.name: # analog output - self.settings.child('clock_settings').show() - self.settings.child('ai_channels').hide() - self.settings.child('ao_channels').show() - self.settings.child('ao_settings').show() - self.settings.child('counter_settings').hide() - self.settings.child('do_channels').hide() - self.settings.child('di_channels').hide() - - elif param.value() == ChannelType.COUNTER_INPUT.name: # counter input - self.settings.child('clock_settings').hide() - self.settings.child('ai_channels').hide() - self.settings.child('ao_channels').hide() - self.settings.child('ao_settings').hide() - self.settings.child('counter_settings').show() - self.settings.child('counter_settings', 'ci_channels').show() - self.settings.child('counter_settings', 'co_channels').hide() - self.settings.child('do_channels').hide() - self.settings.child('di_channels').hide() - - elif param.value() == ChannelType.COUNTER_OUTPUT.name: # counter output - self.settings.child('clock_settings').hide() - self.settings.child('ai_channels').hide() - self.settings.child('ao_channels').hide() - self.settings.child('ao_settings').hide() - self.settings.child('counter_settings').show() - self.settings.child('counter_settings', 'co_channels').show() - self.settings.child('counter_settings', 'ci_channels').hide() - self.settings.child('do_channels').hide() - self.settings.child('di_channels').hide() - - elif param.value() == ChannelType.DIGITAL_INPUT.name: # Digital_Input - self.settings.child('clock_settings').show() - self.settings.child('ai_channels').hide() - self.settings.child('ao_channels').show() - self.settings.child('ao_settings').show() - self.settings.child('counter_settings').hide() - self.settings.child('do_channels').hide() - self.settings.child('di_channels').show() - - elif param.value() == ChannelType.DIGITAL_OUTPUT.name: # digital output - self.settings.child('clock_settings').show() - self.settings.child('ai_channels').hide() - self.settings.child('ao_channels').hide() - self.settings.child('ao_settings').hide() - self.settings.child('counter_settings').hide() - self.settings.child('do_channels').show() - self.settings.child('di_channels').hide() - - elif param.name() == 'refresh_hardware': - if param.value(): - self.controller.refresh_hardware() - QtWidgets.QApplication.processEvents() - self.settings.child('refresh_hardware').setValue(False) - - elif param.name() == 'ai_type': - param.parent().child('voltage_settings').show(param.value() == UsageTypeAI.VOLTAGE.name) - param.parent().child('current_settings').show(param.value() == UsageTypeAI.CURRENT.name) - param.parent().child('thermoc_settings').show(param.value() == UsageTypeAI.TEMPERATURE_THERMOCOUPLE.name) - param.parent().child('rtd_settings').show(param.value() == UsageTypeAI.TEMPERATURE_RTD.name) - - elif param.name() == 'rtd_type': - param.parent().child('c-vd_coeff.').show(param.value() == RTDType.CUSTOM.name) - - elif param.name() == 'ao_type': - param.parent().child('voltage_settings').show(param.value() == UsageTypeAI.VOLTAGE.name) - param.parent().child('current_settings').show(param.value() == UsageTypeAI.CURRENT.name) - - elif param.name() == 'trigger_channel': - param.parent().child('level').show('PF' not in param.opts['title']) - - if self.control_type == "0D": - self.settings.child('nsamplestoread').hide() - self.settings.child('clock_settings', 'Nsamples').setValue(1) - self.settings.child('clock_settings', 'Nsamples').setOpts(readonly=True) - self.settings.child('clock_settings', 'frequency').hide() - self.settings.child('clock_settings', 'max_freq').hide() - - def update_task(self): - """ - Update task according to channels from settings. - """ - self.channels = self.get_channels_from_settings() - self.clock_settings = ClockSettings(frequency=self.settings['clock_settings', 'frequency'], - Nsamples=self.settings['clock_settings', 'Nsamples'], - edge=Edge.RISING, - repetition=self.live, ) - self.trigger_settings = \ - TriggerSettings(trig_source=self.settings['trigger_settings', 'trigger_channel'], - enable=self.settings['trigger_settings', 'enable'], - edge=Edge[self.settings['trigger_settings', 'edge']], - level=self.settings['trigger_settings', 'level'], ) - if self.channels: - self.controller.update_task(self.channels, self.clock_settings, trigger_settings=self.trigger_settings) - else: - logger.warning("No channels assigned, task not created") - - def get_channels_from_settings(self, from_all_devices=False): - """ - Browse the viewer settings to gather all the channels that will be used. - """ - channels = [] - if self.settings['NIDAQ_type'] == ChannelType.ANALOG_INPUT.name: # analog input - source = ChannelType.ANALOG_INPUT - for channel in self.settings.child('ai_channels').children(): - analog_type = UsageTypeAI[channel['ai_type']] - if analog_type == UsageTypeAI.VOLTAGE: - channels.append(AIChannel(name=channel.opts['title'], - source=source, analog_type=analog_type, - value_min=channel['voltage_settings', 'volt_min'], - value_max=channel['voltage_settings', 'volt_max'], - termination=TerminalConfiguration[channel['termination']], )) - elif analog_type == UsageTypeAI.CURRENT: - channels.append(AIChannel(name=channel.opts['title'], - source=source, analog_type=analog_type, - value_min=channel['current_settings', 'curr_min'], - value_max=channel['current_settings', 'curr_max'], - termination=TerminalConfiguration[channel['termination']], )) - elif analog_type == UsageTypeAI.TEMPERATURE_THERMOCOUPLE: - channels.append(AIThermoChannel(name=channel.opts['title'], - source=source, analog_type=analog_type, - value_min=channel['thermoc_settings', 'T_min'], - value_max=channel['thermoc_settings', 'T_max'], - thermo_type=ThermocoupleType[ - channel['thermoc_settings', 'thermoc_type']], )) - elif analog_type == UsageTypeAI.TEMPERATURE_RTD: - channels.append(AI_RTD_Channel(name=channel.opts['title'], - source=source, analog_type=analog_type, - value_min=channel['rtd_settings', 'min_value_in'], - value_max=channel['rtd_settings', 'max_value_in'], - units=TemperatureUnits[channel['rtd_settings', 'temp_unit']], - rtd_type=RTDType[channel['rtd_settings', 'rtd_type']], - a_cvd_coeff=channel['rtd_settings', 'c-vd_coeff.', 'a_c-vd_coeff'], - b_cvd_coeff=channel['rtd_settings', 'c-vd_coeff.', 'b_c-vd_coeff'], - c_cvd_coeff=channel['rtd_settings', 'c-vd_coeff.', 'c_c-vd_coeff'], - resistance_config= - ResistanceConfiguration[channel['rtd_settings', 'resistance_config']], - current_excit_source= - ExcitationSource[channel['rtd_settings', 'current_excit_src']], - current_excit_val=channel['rtd_settings', 'i_ex_value'], - r_0=channel['rtd_settings', 'r0'], - )) - - elif self.settings['NIDAQ_type'] == ChannelType.ANALOG_OUTPUT.name: # analog output - source = ChannelType.ANALOG_OUTPUT - for channel in self.settings.child('ao_channels').children(): - analog_type = UsageTypeAO[channel['ao_type']] - channels.append(AOChannel(name=channel.opts['title'], - source=source, analog_type=analog_type, - value_min=channel['voltage_settings', 'volt_min'], - value_max=channel['voltage_settings', 'volt_max'], - )) - - elif self.settings['NIDAQ_type'] == ChannelType.COUNTER_INPUT.name: # counter input - source = ChannelType.COUNTER_INPUT - for channel in self.settings.child('counter_settings', 'ci_channels').children(): - channels.append(CIChannel(name=channel.opts['title'], - source=source, edge=Edge[channel['edge']])) - - elif self.settings['NIDAQ_type'] == ChannelType.COUNTER_OUTPUT.name: # counter output - source = ChannelType.COUNTER_OUTPUT - for channel in self.settings.child('counter_settings', 'co_channels').children(): - channels.append(COChannel(name=channel.opts['title'], - source=source, edge=Edge[channel['edge']])) - - elif self.settings['NIDAQ_type'] == ChannelType.DIGITAL_INPUT.name: # digital input - source = ChannelType.DIGITAL_INPUT - for channel in self.settings.child('di_channels').children(): - channels.append(DIChannel(name=channel.opts['title'], - source=source)) - - elif self.settings['NIDAQ_type'] == ChannelType.DIGITAL_OUTPUT.name: # Digital output - source = ChannelType.DIGITAL_OUTPUT - for channel in self.settings.child('do_channels').children(): - channels.append(DOChannel(name=channel.opts['title'], - source=source)) - if not from_all_devices: - channels = [ch for ch in channels if self.settings.child("devices").value() in ch.name] - return channels - - def stop(self): - """ - Stop the acquisition. - """ - if not not self.timer: - self.timer.stop() - QtWidgets.QApplication.processEvents() - self.controller.stop() - - - diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/daqmxni.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/daqmxni.py deleted file mode 100644 index 5585b37..0000000 --- a/src/pymodaq_plugins_daqmx/hardware/national_instruments/daqmxni.py +++ /dev/null @@ -1,698 +0,0 @@ -import traceback -import numpy as np -from pymodaq_utils.logger import set_logger, get_module_name -from nidaqmx.constants import AcquisitionType, VoltageUnits, CurrentUnits, CurrentShuntResistorLocation, \ - TemperatureUnits, CJCSource, CountDirection, Level, FrequencyUnits, TimeUnits, LineGrouping, UsageTypeAI, \ - UsageTypeAO, UsageTypeCI, UsageTypeCO, Edge, TerminalConfiguration, ThermocoupleType, ChannelType, \ - ProductCategory, RTDType, TemperatureUnits, ResistanceConfiguration, ExcitationSource -from nidaqmx.system import System as niSystem -from nidaqmx.system.device import Device as niDevice -from nidaqmx import Task as niTask -from nidaqmx.errors import DaqError, DAQmxErrors, DaqNotFoundError -from pymodaq_plugins_daqmx import config - - -logger = set_logger(get_module_name(__file__)) - - -class _NoDevices: - """Stands for the collection of devices when the NI-DAQmx driver is not installed: no device at all. - - The modules of the plugin build their settings when they are imported, which then must not fail on a computer - without the driver (for instance a continuous integration runner). - """ - device_names = [] - - def __iter__(self): - return iter(()) - - def __len__(self): - return 0 - - def __contains__(self, item): - return False - - -class ClockSettingsBase: - def __init__(self, Nsamples=1000, repetition=False): - - self.Nsamples = Nsamples - self.repetition = repetition - - -class ClockSettings(ClockSettingsBase): - def __init__(self, source=None, frequency=1000, Nsamples=1000, edge=Edge.RISING, repetition=False): - super().__init__(Nsamples, repetition) - self.source = source - assert edge in Edge - self.frequency = frequency - self.edge = edge - - -class ChangeDetectionSettings(ClockSettingsBase): - def __init__(self, Nsamples=1000, rising_channel='', falling_channel='', - repetition=False): - super().__init__(Nsamples, repetition) - self.rising_channel = rising_channel - self.falling_channel = falling_channel - - -class TriggerSettings: - def __init__(self, trig_source='', enable=False, edge=Edge.RISING, level=0.1): - assert edge in Edge - self.trig_source = trig_source - self.enable = enable - self.edge = edge - self.level = level - - -class Channel: - def __init__(self, name='', source=ChannelType.ANALOG_INPUT): - """ - Parameters - ---------- - - """ - self.name = name - assert source in ChannelType - self.source = source - - -class AChannel(Channel): - def __init__(self, analog_type=UsageTypeAI.VOLTAGE, value_min=-10., value_max=+10., **kwargs): - """ - Parameters - ---------- - min: (float) minimum value for the configured input channel (could be voltage, amps, temperature...) - max: (float) maximum value for the configured input channel - """ - super().__init__(**kwargs) - self.value_min = value_min - self.value_max = value_max - assert analog_type in UsageTypeAI or analog_type in UsageTypeAO - self.analog_type = analog_type - - -class AIChannel(AChannel): - def __init__(self, termination=TerminalConfiguration.DEFAULT, **kwargs): - super().__init__(**kwargs) - assert termination in TerminalConfiguration - self.termination = termination - - -class AIThermoChannel(AIChannel): - def __init__(self, thermo_type=ThermocoupleType.K, **kwargs): - super().__init__(**kwargs) - assert thermo_type in ThermocoupleType - self.thermo_type = thermo_type - -class AI_RTD_Channel(AIChannel): - def __init__(self, units = TemperatureUnits.DEG_C, resistance_config=ResistanceConfiguration.TWO_WIRE, r_0=float(100), - rtd_type=RTDType.PT_3750, a_cvd_coeff=float(0), b_cvd_coeff=float(0), c_cvd_coeff=float(0), - current_excit_source = ExcitationSource.INTERNAL, current_excit_val = 0.01, **kwargs): - super().__init__(**kwargs) - assert units in TemperatureUnits - self.units = units - assert resistance_config in ResistanceConfiguration - self.resistance_config = resistance_config - assert type(r_0) in [float, int] - self.r_0 = r_0 - assert rtd_type in RTDType - self.rtd_type = rtd_type - assert type(a_cvd_coeff) in [float, int] - self.a_cvd_coeff = a_cvd_coeff - assert type(b_cvd_coeff) in [float, int] - self.b_cvd_coeff = b_cvd_coeff - assert type(c_cvd_coeff) in [float, int] - self.c_cvd_coeff = c_cvd_coeff - assert current_excit_source in ExcitationSource - self.current_excit_source = current_excit_source - assert type(current_excit_val) in [float, int] - self.current_excit_val = current_excit_val - - -class AOChannel(AChannel): - def __init__(self, analog_type=UsageTypeAO.VOLTAGE, **kwargs): - kwargs.setdefault('source', ChannelType.ANALOG_OUTPUT) - super().__init__(analog_type=analog_type, **kwargs) - - -class CIChannel(Channel): - def __init__(self, edge=Edge.RISING, counter_type=UsageTypeCI.COUNT_EDGES, **kwargs): - super().__init__(**kwargs) - assert edge in Edge - assert counter_type in UsageTypeCI - self.edge = edge - self.counter_type = counter_type - - -class COChannel(Channel): - def __init__(self, edge=Edge.RISING, counter_type=UsageTypeCO.PULSE_FREQUENCY, **kwargs): - super().__init__(**kwargs) - assert edge in Edge - assert counter_type in UsageTypeCO - self.edge = edge - self.counter_type = counter_type - - -class ClockCounter(COChannel): - def __init__(self, clock_frequency=100, counter_type=UsageTypeCO.PULSE_FREQUENCY, **kwargs): - kwargs.setdefault('source', ChannelType.COUNTER_OUTPUT) - super().__init__(counter_type=counter_type, **kwargs) - self.clock_frequency = clock_frequency - - -class DigitalChannel(Channel): - def __init__(self, **kwargs): - super().__init__(**kwargs) - - -class DOChannel(DigitalChannel): - def __init__(self, **kwargs): - super().__init__(**kwargs) - - -class DIChannel(DigitalChannel): - def __init__(self, **kwargs): - super().__init__(**kwargs) - - -class NIDAQmx: - """Wrapper around the NIDAQmx package giving an easy-to-use object to instantiate channels and tasks""" - def __init__(self): - self.devices = [] - self.channels = [] - self._device = None - self._task = None - self.update_NIDAQ_devices() - self.update_NIDAQ_channels() - devices_info = [dev.name + ': ' + dev.product_type for dev in self.devices] - logger.info("Detected devices: {}".format(devices_info)) - - @property - def task(self): - return self._task - - @property - def device(self): - return self._device - - @device.setter - def device(self, device): - if device not in self.devices: - raise IOError(f'your device: {device} is not known or connected') - self._device = device - - def update_NIDAQ_devices(self): - self.devices = self.get_NIDAQ_devices() - - @classmethod - def get_NIDAQ_devices(cls): - """Get list of NI connected devices - - Returns - ------- - list - list of devices as strings to be used in subsequent commands - """ - try: - devices = niSystem.local().devices - if devices == ['']: - devices = [] - return devices - except DaqNotFoundError: # the NI-DAQmx driver is not installed - logger.warning('The NI-DAQmx driver is not installed: no NI device can be listed') - return _NoDevices() - except DaqError as e: - return e.error_code - - def update_NIDAQ_channels(self, source_type=None): - self.channels = self.get_NIDAQ_channels(self.devices.device_names, source_type=source_type) - - @classmethod - def get_NIDAQ_channels(cls, devices=None, source_type=None): - """Get the list of available channels for all NiDAq connected devices - - Parameters - ---------- - devices: list - list of strings, each one being a connected device - source_type: str - Channels possible types - - Returns - ------- - List of str containing device and channel names - - """ - if devices is None: - devices = cls.get_NIDAQ_devices().device_names - - if source_type is None: - source_type = ChannelType - if not isinstance(source_type, list): - source_type = [source_type] - channels_tot = [] - channels = [] - if not not devices: - for device in devices: - for source in source_type: - if source == ChannelType.ANALOG_INPUT: # analog input - channels = niDevice(device).ai_physical_chans.channel_names - elif source == ChannelType.ANALOG_OUTPUT: # analog output - channels = niDevice(device).ao_physical_chans.channel_names - elif source == ChannelType.COUNTER_INPUT: # counter input - channels = niDevice(device).ci_physical_chans.channel_names - elif source == ChannelType.COUNTER_OUTPUT: # counter output - channels = niDevice(device).co_physical_chans.channel_names - elif source == ChannelType.DIGITAL_INPUT: # digital input - channels = niDevice(device).di_lines.channel_names - elif source == ChannelType.DIGITAL_OUTPUT: # digital output - channels = niDevice(device).do_lines.channel_names - if channels != ['']: - channels_tot.extend(channels) - - return channels_tot - - def configuration_sequence(self, viewer, current_device): - """Configure each / modules / channels as giver by the user in the configuration file - - Read the .toml file to get the desired hardware configuration, - and send the nidaqmx a sequence which set up each channel. - """ - logger.info("********** CONFIGURATION SEQUENCE INITIALIZED **********") - try: - viewer.config_devices = [config["NIDAQ_Devices", dev].get('name') for dev in config["NIDAQ_Devices"] - if "Mod" not in config["NIDAQ_Devices", dev].get('name')] - for dev in config["NIDAQ_Devices"]: - if not isinstance(config["NIDAQ_Devices", dev], dict): - continue - elif 'Example' in dev: - continue - try: - device_name = config["NIDAQ_Devices", dev].get('name') - if device_name not in current_device.name: - continue - device_product = config["NIDAQ_Devices", dev].get('product') - device = niDevice(device_name) - assert device in self.devices and device.product_type == device_product, device.name - except AssertionError as err: - logger.error("Device {} not detected: {}".format(device_name, err)) - continue - for mod in config["NIDAQ_Devices", dev]: - if not isinstance(config["NIDAQ_Devices", dev, mod], dict): - continue - try: - module_name = config["NIDAQ_Devices", dev, mod].get('name') - if current_device.name not in module_name: - continue - module_product = config["NIDAQ_Devices", dev, mod].get('product') - module = niDevice(module_name) - assert module in self.devices and module.product_type == module_product, module.name - viewer.config_modules.append(config["NIDAQ_Devices", dev, mod].get('name')) - except AssertionError as err: - logger.error("Module {} not detected: {}".format(module_name, err)) - continue - for src in config["NIDAQ_Devices", dev, mod]: - if not isinstance(config["NIDAQ_Devices", dev, mod, src], dict): - continue - if src == "ai": - ai = config["NIDAQ_Devices", dev, mod, src] - for ch in ai.keys(): - name = module_name + "/" + str(ch) - source = ChannelType[ai[ch].get("source")] - analog_type = UsageTypeAI[ai[ch].get("analog_type")] - if analog_type == UsageTypeAI.VOLTAGE: - term = TerminalConfiguration[ai[ch].get("termination")] - viewer.config_channels.append(AIChannel - (name=name, - source=source, - analog_type=analog_type, - value_min=float(ai[ch].get("value_min")), - value_max=float(ai[ch].get("value_max")), - termination=term, - )) - elif analog_type == UsageTypeAI.CURRENT: - term = TerminalConfiguration[ai[ch].get("termination")] - viewer.config_channels.append(AIChannel - (name=name, - source=source, - analog_type=analog_type, - value_min=float(ai[ch].get("value_min")), - value_max=float(ai[ch].get("value_max")), - termination=term, - )) - elif analog_type == UsageTypeAI.TEMPERATURE_THERMOCOUPLE: - th = ThermocoupleType[ai[ch].get("thermo_type")] - viewer.config_channels.append(AIThermoChannel - (name=name, - source=source, - analog_type=analog_type, - value_min=float(ai[ch].get("value_min")), - value_max=float(ai[ch].get("value_max")), - thermo_type=th, - )) - elif analog_type == UsageTypeAI.TEMPERATURE_RTD: - units = TemperatureUnits[ai[ch].get("units")] - resistance_config = ResistanceConfiguration[ai[ch].get("resistance_config")] - r_0 = float(ai[ch].get("r_0")) - rtd_type = RTDType[ai[ch].get("rtd_type")] - a_cvd_coeff = float(ai[ch].get("a_cvd_coeff")) - b_cvd_coeff = float(ai[ch].get("b_cvd_coeff")) - c_cvd_coeff = float(ai[ch].get("c_cvd_coeff")) - current_excit_source = ExcitationSource[ai[ch].get("current_excit_source")] - current_excit_val = float(ai[ch].get("current_excit_val")) - viewer.config_channels.append(AI_RTD_Channel - (name=name, - source=source, - analog_type=analog_type, - value_min=float(ai[ch].get("value_min")), - value_max=float(ai[ch].get("value_max")), - units=units, - resistance_config=resistance_config, - r_0=r_0, - rtd_type=rtd_type, - a_cvd_coeff=a_cvd_coeff, - b_cvd_coeff=b_cvd_coeff, - c_cvd_coeff=c_cvd_coeff, - current_excit_source=current_excit_source, - current_excit_val=current_excit_val, - )) - logger.info("Devices from config: {}".format(viewer.config_devices)) - logger.info("Modules from config: {}".format(viewer.config_modules)) - logger.info("Channels from config: {}".format([ch.name for ch in viewer.config_channels])) - logger.info(" ********** CONFIGURATION SEQUENCE SUCCESSFULLY ENDED **********") - except AssertionError as err: - logger.error("Configuration entries <{}> does not match the hardware ".format(err)) - except Exception as err: - logger.info("Configuration sequence error, verify if your config matches the hardware: {}".format(err)) - - @classmethod - def getAOMaxRate(cls, device): - return niDevice(device).ao_max_rate - - @classmethod - def getAIMaxSingleRate(cls, device): - return niDevice(device).ai_max_single_chan_rate - - @classmethod - def getAIMaxMultiRate(cls, device): - return niDevice(device).ai_max_multi_chan_rate - - @classmethod - def isAnalogTriggeringSupported(cls, device): - return niDevice(device).anlg_trig_supported - - @classmethod - def isDigitalTriggeringSupported(cls, device): - return niDevice(device).dig_trig_supported - - @classmethod - def getTriggeringSources(cls, devices=None): - sources = [] - if devices is None: - devices = cls.get_NIDAQ_devices().device_names - - for device in devices: - try: - if cls.isDigitalTriggeringSupported(device): - string = niDevice(device).terminals - channels = [chan for chan in string if 'PFI' in chan] - if channels != ['']: - sources.extend(channels) - if cls.isAnalogTriggeringSupported(device): - channels = niDevice(device).ai_physical_chans.channel_names - if channels != ['']: - sources.extend(channels) - except DaqError as err: - logger.error("Daq error with device {}: {}".format(device, err)) - return sources - - def update_task(self, channels=[], clock_settings=ClockSettings(), trigger_settings=TriggerSettings()): - - try: - if self._task is not None: - if isinstance(self._task, niTask): - self._task.close() - - self._task = None - - self._task = niTask() - logger.info("TASK: {}".format(self._task)) - err_code = None - - # create all channels one task for one type of channels - for channel in channels: - if channel.source == ChannelType.ANALOG_INPUT: # analog input - try: - if channel.analog_type == UsageTypeAI.VOLTAGE: - self._task.ai_channels.add_ai_voltage_chan(channel.name, - "", - channel.termination, - channel.value_min, - channel.value_max, - VoltageUnits.VOLTS, - "") - - elif channel.analog_type == UsageTypeAI.CURRENT: - self._task.ai_channels.add_ai_current_chan(channel.name, - "", - channel.termination, - channel.value_min, - channel.value_max, - CurrentUnits.AMPS, - CurrentShuntResistorLocation.INTERNAL, - 0., - "") - - elif channel.analog_type == UsageTypeAI.TEMPERATURE_THERMOCOUPLE: - self._task.ai_channels.add_ai_thrmcpl_chan(channel.name, - "", - channel.value_min, - channel.value_max, - TemperatureUnits.DEG_C, - channel.thermo_type, - CJCSource.BUILT_IN, - 0., - "") - elif channel.analog_type == UsageTypeAI.TEMPERATURE_RTD: - ai_rtd_chan = self._task.ai_channels.add_ai_rtd_chan(channel.name, - "", - channel.value_min, - channel.value_max, - channel.units, - channel.rtd_type, - channel.resistance_config, - channel.current_excit_source, - channel.current_excit_val, - channel.r_0) - if ai_rtd_chan.ai_rtd_type == RTDType["CUSTOM"]: - # configuration of callendar-van dusen coefficients - ai_rtd_chan.ai_rtd_a = channel.a_cvd_coeff - ai_rtd_chan.ai_rtd_b = channel.b_cvd_coeff - ai_rtd_chan.ai_rtd_c = channel.c_cvd_coeff - except DaqError as e: - err_code = e.error_code - if err_code: - status = self.DAQmxGetErrorString(err_code) - raise IOError(status) - elif channel.source == ChannelType.ANALOG_OUTPUT: # Analog_Output - try: - if channel.analog_type == UsageTypeAO.VOLTAGE: - self._task.ao_channels.add_ao_voltage_chan(channel.name, "", - channel.value_min, - channel.value_max, - VoltageUnits.VOLTS, None) - - elif channel.analog_type == UsageTypeAO.CURRENT: - self._task.ao_channels.add_ao_current_chan(channel.name, "", - channel.value_min, - channel.value_max, - VoltageUnits.VOLTS, None) - except DaqError as e: - err_code = e.error_code - if not not err_code: - status = self.DAQmxGetErrorString(err_code) - raise IOError(status) - elif channel.source == ChannelType.COUNTER_INPUT: # counter input - try: - if channel.counter_type == UsageTypeCI.COUNT_EDGES: - self._task.ci_channels.add_ci_count_edges_chan(channel.name, "", - channel.edge, 0, - CountDirection.COUNT_UP) - elif channel.counter_type == UsageTypeCI.PULSE_WIDTH_DIGITAL_SEMI_PERIOD: - self._task.ci_channels.add_ci_semi_period_chan(channel.name, "counter task", - 0, # expected min - channel.value_max, # expected max - TimeUnits.TICKS, "") - - except DaqError as e: - err_code = e.error_code - - if not not err_code: - status = self.DAQmxGetErrorString(err_code) - raise IOError(status) - - if not not err_code: - status = self.DAQmxGetErrorString(err_code) - raise IOError(status) - elif channel.source == ChannelType.COUNTER_OUTPUT: # counter output - try: - if channel.counter_type == UsageTypeCO.PULSE_FREQUENCY: - self._task.co_channels.add_co_pulse_chan_freq(channel.name, "clock task", - FrequencyUnits.HZ, - Level.LOW, - 0, - channel.clock_frequency, - 0.5) - - except DaqError as e: - err_code = e.error_code - - if not not err_code: - status = self.DAQmxGetErrorString(err_code) - raise IOError(status) - - if not not err_code: - status = self.DAQmxGetErrorString(err_code) - raise IOError(status) - elif channel.source == ChannelType.DIGITAL_OUTPUT: - try: - self._task.do_channels.add_do_chan(channel.name, "", - LineGrouping.CHAN_PER_LINE) - except DaqError as e: - err_code = e.error_code - if not not err_code: - status = self.DAQmxGetErrorString(err_code) - raise IOError(status) - elif channel.source == ChannelType.DIGITAL_INPUT: # Digital_Input - try: - self._task.di_channels.add_di_chan(channel.name, "", - LineGrouping.CHAN_PER_LINE) - except DaqError as e: - err_code = e.error_code - if not not err_code: - status = self.DAQmxGetErrorString(err_code) - raise IOError(status) - - # configure the timing - if clock_settings.repetition: - mode = AcquisitionType.CONTINUOUS - else: - mode = AcquisitionType.FINITE - if clock_settings.Nsamples > 1 and isinstance(err_code, type(None)): - try: - if isinstance(clock_settings, ClockSettings): - self._task.timing.cfg_samp_clk_timing(clock_settings.frequency, - clock_settings.source, - clock_settings.edge, - mode, - clock_settings.Nsamples) - self._task.in_stream.input_buf_size = int(clock_settings.frequency)*10 - elif isinstance(clock_settings, ChangeDetectionSettings): - self._task.timing.cfg_change_detection_timing(clock_settings.rising_channel, - clock_settings.falling_channel, - mode, - clock_settings.Nsamples) - except DaqError as e: - err_code = e.error_code - if not not err_code: - status = self.DAQmxGetErrorString(err_code) - logger.error(traceback.format_exc()) - raise IOError(status) - - for channel in channels: - if not trigger_settings.enable: - if channel.source == ChannelType.COUNTER_INPUT: - pass # Maybe here adding the configuration fastCTr0 with Ctr1 etc...? - else: - pass - # err = self._task.triggers.start_trigger.disable_start_trig() - # if err != 0: - # raise IOError(self.DAQmxGetErrorString(err)) - else: - if 'PF' in trigger_settings.trig_source: - self._task.triggers.start_trigger.disable_start_trig() - elif 'ai' in trigger_settings.trig_source: - self._task.triggers.start_trigger.cfg_anlg_edge_start_trig( - trigger_settings.trig_source, - Edge[trigger_settings.edge], - trigger_settings.level) - else: - raise IOError('Unsupported Trigger source') - logger.info("Task's channels{}".format(self._task.ai_channels.channel_names)) - except Exception as e: - logger.error("Exception caught: {}".format(e)) - logger.error(traceback.format_exc()) - - def register_callback(self, callback, event='done', nsamples=1): - if event == 'done': - self._task.register_done_event(callback) - elif event == 'Nsamples': - self._task.register_every_n_samples_acquired_into_buffer_event(nsamples, callback) - - def readCounter(self): - return self._task.read() - - @classmethod - def getAIVoltageRange(cls, device='Dev1'): - return niSystem.local().devices[device].ai_voltage_rngs[-2:] # todo self.devices[device].ai_voltage_rngs - - @classmethod - def getAICurrentRange(cls, device='Dev1'): - return niSystem.local().devices[device].ai_current_rngs[-2:] # todo self.devices[device].ai_current_rngs - - @classmethod - def getAOVoltageRange(cls, device='Dev1'): - return niSystem.local().devices[device].ao_voltage_rngs[-2:] # todo self.devices[device].ao_voltage_rngs - - @classmethod - def getAOCurrentRange(cls, device='Dev1'): - return niSystem.local().devices[device].ao_current_rngs[-2:] # todo self.devices[device].ao_current_rngs - - def stop(self): - if self._task is not None: - self._task.stop() - - def start(self): - if self._task is not None: - self._task.start() - - def close(self): - """ - close the current task. - """ - if self._task is not None: - self._task.stop() - self._task.close() - self._task = None - - @classmethod - def DAQmxGetErrorString(cls, error_code): - if error_code is None: - return '' - else: - return DAQmxErrors(error_code).name - - def isTaskDone(self): - return self._task.is_task_done() - - def waitTaskDone(self, timeout=10.): - ret = self._task.wait_until_done(timeout) - if ret != 0: - logger.info(self.DAQmxGetErrorString(ret)) - - def refresh_hardware(self): - """ - Refresh the NIDAQ hardware from settings values. - - See Also - -------- - update_NIDAQ_devices, update_NIDAQ_channels - """ - self.update_NIDAQ_devices() - self.update_NIDAQ_channels() - - -if __name__ == '__main__': - pass diff --git a/tests/test_channels.py b/tests/test_channels.py deleted file mode 100644 index 158b07f..0000000 --- a/tests/test_channels.py +++ /dev/null @@ -1,27 +0,0 @@ -"""Tests of the description objects of the nidaqmx based interface (no hardware nor NI-DAQmx driver needed).""" -import pytest - -pytest.importorskip('nidaqmx') -pytest.importorskip('pymodaq') - -from nidaqmx.constants import ChannelType, Edge, UsageTypeCO - -from pymodaq_plugins_daqmx.hardware.national_instruments.daqmxni import ClockCounter - - -class TestClockCounter: - def test_can_be_instantiated(self): - clock = ClockCounter(clock_frequency=250., name='Dev1/ctr0') - - assert clock.name == 'Dev1/ctr0' - assert clock.clock_frequency == 250. - assert clock.counter_type == UsageTypeCO.PULSE_FREQUENCY - assert clock.edge == Edge.RISING - - def test_is_a_counter_output_channel_by_default(self): - assert ClockCounter(name='Dev1/ctr0').source == ChannelType.COUNTER_OUTPUT - - def test_source_can_be_overridden(self): - clock = ClockCounter(name='Dev1/ctr0', source=ChannelType.COUNTER_OUTPUT, edge=Edge.FALLING) - - assert clock.edge == Edge.FALLING