diff --git a/CHANGELOG.md b/CHANGELOG.md index 3096de950..0f12334eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,7 @@ All notable changes to this project will be documented in this file. one for Python 3.9-3.12 (numpy>=1.22) and one for Python 3.13+ (numpy>=2.1). * The `nidaqmx` distribution package now specifies only a lower bound for `click`. * Clarify PyPy support and enable unit testing with PyPy. + * Adopt ni-python-styleguide for hand-written code. * ### Known Issues * ... diff --git a/generated/nidaqmx/__init__.py b/generated/nidaqmx/__init__.py index ec8ff6ed7..455cd5aee 100644 --- a/generated/nidaqmx/__init__.py +++ b/generated/nidaqmx/__init__.py @@ -1,5 +1,13 @@ -from nidaqmx.errors import DaqError, DaqReadError, DaqWriteError, DaqWarning, DaqResourceWarning -from nidaqmx.grpc_session_options import * +"""The NI-DAQmx API for Python.""" + +from nidaqmx.errors import ( + DaqError, + DaqReadError, + DaqResourceWarning, + DaqWarning, + DaqWriteError, +) +from nidaqmx.grpc_session_options import * # noqa: F403 - 'from nidaqmx.grpc_session_options import *' used; unable to detect undefined names (auto-generated noqa) from nidaqmx.scale import Scale from nidaqmx.task import Task from nidaqmx.types import CtrFreq, CtrTick, CtrTime @@ -11,7 +19,13 @@ __version__ = version(__name__) -__all__ = ["errors", "scale", "stream_readers", "stream_writers", "task"] +__all__ = [ # noqa: F405 - 'errors' may be undefined, or defined from star imports: nidaqmx.grpc_session_options (auto-generated noqa) + "errors", + "scale", + "stream_readers", + "stream_writers", + "task", +] # Do not add a null logging handler. If the application has not configured logging, the # default behavior is to log warnings and errors to stderr. diff --git a/generated/nidaqmx/__main__.py b/generated/nidaqmx/__main__.py index e0baada58..5bf245291 100644 --- a/generated/nidaqmx/__main__.py +++ b/generated/nidaqmx/__main__.py @@ -1,7 +1,8 @@ +"""'nidaqmx' command line utility.""" + from __future__ import annotations import logging -from typing import Optional import click @@ -16,12 +17,14 @@ count=True, help="Enable verbose logging. Repeat to increase verbosity.", ) -def main(verbosity: int) -> None: +def main( # noqa: D103 - Missing docstring in public function (auto-generated noqa) + verbosity: int, +) -> None: _configure_logging(verbosity) @main.command() -def installdriver(): +def installdriver(): # noqa: D103 - Missing docstring in public function (auto-generated noqa) _install_daqmx.installdriver() diff --git a/generated/nidaqmx/_bitfield_utils.py b/generated/nidaqmx/_bitfield_utils.py index eb04a4bcc..64494f82f 100644 --- a/generated/nidaqmx/_bitfield_utils.py +++ b/generated/nidaqmx/_bitfield_utils.py @@ -1,41 +1,38 @@ -def enum_bitfield_to_list(bitfield_value, bitfield_enum_type, - actual_enum_type): - """ - Converts a bitfield value to a list of enums. +def enum_bitfield_to_list(bitfield_value, bitfield_enum_type, actual_enum_type): + """Converts a bitfield value to a list of enums. Args: bitfield_value (int): Specifies the value of the bitfield. bitfield_enum_type (enum.Enum): Specifies the bitfield enum type from which to mask and extract the enum values. actual_enum_type (enum.Enum): Specifies the actual enum type. + Returns: List[enum.Enum]: Indicates the converted list of enums. """ supported_values = [] for bitfield_mask in bitfield_enum_type: if bitfield_value & bitfield_mask.value: - enum_value = next( - e for e in actual_enum_type if e.name == bitfield_mask.name) + enum_value = next(e for e in actual_enum_type if e.name == bitfield_mask.name) supported_values.append(enum_value) return supported_values def enum_list_to_bitfield(enum_list, bitfield_enum_type): - """ - Converts a list of enums to a bitfield value. + """Converts a list of enums to a bitfield value. Args: enum_list (List[enum.Enum]): Specifies the list of enums. bitfield_enum_type (enum.Enum): Specifies the bitfield enum type from which to mask and extract the enum values. + Returns: int: Indicates the value of the bitfield. """ bitfield_value = 0 for enum_value in enum_list: - bitfield_mask = next( - b for b in bitfield_enum_type if b.name == enum_value.name) + bitfield_mask = next(b for b in bitfield_enum_type if b.name == enum_value.name) bitfield_value |= bitfield_mask.value - return bitfield_value \ No newline at end of file + return bitfield_value diff --git a/generated/nidaqmx/_dotenvpath.py b/generated/nidaqmx/_dotenvpath.py index af092820d..19cad5a2d 100644 --- a/generated/nidaqmx/_dotenvpath.py +++ b/generated/nidaqmx/_dotenvpath.py @@ -70,4 +70,4 @@ def _get_package_path() -> Path: """Get the path of this package.""" module = sys.modules[__package__] assert module.__file__ and module.__file__.endswith("__init__.py") - return Path(module.__file__).parent \ No newline at end of file + return Path(module.__file__).parent diff --git a/generated/nidaqmx/_feature_toggles.py b/generated/nidaqmx/_feature_toggles.py index 20505ff59..9484031a6 100644 --- a/generated/nidaqmx/_feature_toggles.py +++ b/generated/nidaqmx/_feature_toggles.py @@ -4,9 +4,11 @@ import functools import sys -from decouple import AutoConfig, Undefined, undefined from enum import Enum from typing import TYPE_CHECKING, Callable, TypeVar + +from decouple import AutoConfig, Undefined, undefined + from nidaqmx._dotenvpath import get_dotenv_search_path from nidaqmx.errors import FeatureNotSupportedError @@ -36,6 +38,7 @@ def _config( cast: Callable[[str], _T] | Undefined = undefined, ) -> _T: ... + # Based on the recipe at https://docs.python.org/3/howto/enum.html class _OrderedEnum(Enum): def __ge__(self, other: Self) -> bool: @@ -156,4 +159,4 @@ def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T: # Define feature toggle constants here: # -------------------------------------- -WAVEFORM_SUPPORT = FeatureToggle("WAVEFORM_SUPPORT", CodeReadiness.INCOMPLETE) \ No newline at end of file +WAVEFORM_SUPPORT = FeatureToggle("WAVEFORM_SUPPORT", CodeReadiness.INCOMPLETE) diff --git a/generated/nidaqmx/_grpc_time.py b/generated/nidaqmx/_grpc_time.py index 77a818d43..9d56047d5 100644 --- a/generated/nidaqmx/_grpc_time.py +++ b/generated/nidaqmx/_grpc_time.py @@ -1,14 +1,11 @@ from __future__ import annotations -from datetime import timezone -from datetime import datetime as std_datetime -from datetime import tzinfo as dt_tzinfo -from hightime import datetime as ht_datetime -from hightime import timedelta as ht_timedelta -from typing import Optional, Union -from nidaqmx._time import _convert_to_desired_timezone +from datetime import datetime as std_datetime, timezone, tzinfo as dt_tzinfo from google.protobuf.timestamp_pb2 import Timestamp as GrpcTimestamp +from hightime import datetime as ht_datetime, timedelta as ht_timedelta + +from nidaqmx._time import _convert_to_desired_timezone # 66 years, 17 leap days = 24107 days = 2082844800 seconds _BIAS_FROM_1970_EPOCH = 2082844800 @@ -22,7 +19,10 @@ _EPOCH_1970 = ht_datetime(1970, 1, 1, tzinfo=timezone.utc) -def convert_time_to_timestamp(dt: std_datetime | ht_datetime, ts: GrpcTimestamp | None = None) -> GrpcTimestamp: + +def convert_time_to_timestamp( # noqa: D103 - Missing docstring in public function (auto-generated noqa) + dt: std_datetime | ht_datetime, ts: GrpcTimestamp | None = None +) -> GrpcTimestamp: seconds_since_1970 = 0 if ts is None: @@ -44,10 +44,13 @@ def convert_time_to_timestamp(dt: std_datetime | ht_datetime, ts: GrpcTimestamp ts.FromNanoseconds(seconds_since_1970 * _NS_PER_S + nanos) return ts -def convert_timestamp_to_time(ts: GrpcTimestamp, tzinfo: dt_tzinfo | None = None) -> ht_datetime: + +def convert_timestamp_to_time( # noqa: D103 - Missing docstring in public function (auto-generated noqa) + ts: GrpcTimestamp, tzinfo: dt_tzinfo | None = None +) -> ht_datetime: total_nanos = ts.ToNanoseconds() seconds, nanos = divmod(total_nanos, _NS_PER_S) # Convert the nanoseconds to yoctoseconds. total_yoctoseconds = int(round(_YS_PER_NS * nanos)) - dt = _EPOCH_1970 + ht_timedelta(seconds = seconds) + ht_timedelta(yoctoseconds=total_yoctoseconds) + dt = _EPOCH_1970 + ht_timedelta(seconds=seconds) + ht_timedelta(yoctoseconds=total_yoctoseconds) return _convert_to_desired_timezone(dt, tzinfo) diff --git a/generated/nidaqmx/_install_daqmx.py b/generated/nidaqmx/_install_daqmx.py index d63971ec1..97ca0bc76 100644 --- a/generated/nidaqmx/_install_daqmx.py +++ b/generated/nidaqmx/_install_daqmx.py @@ -1,24 +1,20 @@ from __future__ import annotations import contextlib -import errno import importlib.resources as pkg_resources import json import logging import os -import pathlib import re -import shutil import subprocess # nosec: B404 import sys import tempfile -import traceback -import requests import zipfile -from typing import Generator, List, Optional, Tuple +from typing import Generator from urllib.parse import urlparse import click +import requests if sys.platform.startswith("win"): import winreg @@ -37,8 +33,7 @@ def _parse_version(version: str) -> tuple[int, ...]: - """ - Split the version string into a tuple of integers. + """Split the version string into a tuple of integers. >>> _parse_version("23.8.0") (23, 8, 0) @@ -57,10 +52,7 @@ def _parse_version(version: str) -> tuple[int, ...]: def _get_daqmx_installed_version() -> str | None: - """ - Check for existing installation of NI-DAQmx. - - """ + """Check for existing installation of NI-DAQmx.""" if sys.platform.startswith("win"): try: _logger.debug("Reading the registry entries to get installed DAQmx version") @@ -101,7 +93,9 @@ def _get_daqmx_installed_version() -> str | None: commands_info = LINUX_COMMANDS[distribution] query_command = commands_info.get_daqmx_version # Run the package query command defined by _linux_installation_commands.py. - query_output = subprocess.run(query_command, stdout=subprocess.PIPE, text=True).stdout # nosec: B603 + query_output = subprocess.run( + query_command, stdout=subprocess.PIPE, text=True + ).stdout # nosec: B603 if distribution == "ubuntu": version_match = re.search(r"ii\s+ni-daqmx\s+(\d+\.\d+\.\d+)", query_output) @@ -127,13 +121,8 @@ def _get_daqmx_installed_version() -> str | None: # Creating a temp file that we then close and yield - this is used to allow subprocesses to access @contextlib.contextmanager -def _multi_access_temp_file( - *, suffix: str = ".exe", delete: bool = True -) -> Generator[str]: - """ - Context manager for creating a temporary file. - - """ +def _multi_access_temp_file(*, suffix: str = ".exe", delete: bool = True) -> Generator[str]: + """Context manager for creating a temporary file.""" try: temp_file = tempfile.NamedTemporaryFile(suffix=suffix, delete=False, mode="w") temp_file.close() @@ -161,8 +150,7 @@ def _multi_access_temp_file( def _load_data( json_data: str, platform: str ) -> tuple[str | None, str | None, str | None, list[str] | None]: - """ - Load data from JSON string and extract Windows metadata. + """Load data from JSON string and extract Windows metadata. >>> json_data = '{"Windows": [{"Location": "path/to/windows/driver", "Version": "24.0", "Release": "2024Q1", "supportedOS": ["Windows 11"]}], "Linux": []}' >>> _load_data(json_data, "Windows") @@ -188,7 +176,7 @@ def _load_data( Traceback (most recent call last): click.exceptions.ClickException: Unsupported os 'macOS' - """ + """ # noqa: W505 - doc line too long (159 > 100 characters) (auto-generated noqa) try: if platform == "Windows": metadata = json.loads(json_data).get("Windows", []) @@ -214,10 +202,7 @@ def _load_data( def _get_driver_details( platform: str, ) -> tuple[str | None, str | None, str | None, list[str] | None]: - """ - Parse the JSON data and retrieve the download link and version information. - - """ + """Parse the JSON data and retrieve the download link and version information.""" try: with pkg_resources.open_text(__package__, METADATA_FILE) as json_file: _logger.debug("Opening the metadata file %s.", METADATA_FILE) @@ -234,17 +219,14 @@ def _get_driver_details( def _install_daqmx_driver_windows_core(download_url: str) -> None: - """ - Download and launch NI-DAQmx Driver installation in an interactive mode - - """ + """Download and launch NI-DAQmx Driver installation in an interactive mode.""" _validate_download_url(download_url) try: with _multi_access_temp_file() as temp_file: _logger.info("Downloading Driver to %s", temp_file) response = requests.get(download_url, timeout=_NETWORK_TIMEOUT_IN_SECONDS) response.raise_for_status() - with open(temp_file, 'wb') as f: + with open(temp_file, "wb") as f: f.write(response.content) _logger.info("Installing NI-DAQmx") # Run the installer that we just downloaded from https://download.ni.com. @@ -263,10 +245,7 @@ def _install_daqmx_driver_windows_core(download_url: str) -> None: def _install_daqmx_driver_linux_core(download_url: str, release: str) -> None: - """ - Download NI Linux Device Drivers and install NI-DAQmx on Linux OS - - """ + """Download NI Linux Device Drivers and install NI-DAQmx on Linux OS.""" if sys.platform.startswith("linux"): _validate_download_url(download_url) try: @@ -274,7 +253,7 @@ def _install_daqmx_driver_linux_core(download_url: str, release: str) -> None: _logger.info("Downloading Driver to %s", temp_file) response = requests.get(download_url, timeout=_NETWORK_TIMEOUT_IN_SECONDS) response.raise_for_status() - with open(temp_file, 'wb') as f: + with open(temp_file, "wb") as f: f.write(response.content) with tempfile.TemporaryDirectory() as temp_folder: @@ -330,10 +309,7 @@ def _validate_download_url(download_url: str) -> None: def _ask_user_confirmation(user_message: str) -> bool: - """ - Prompt for user confirmation - - """ + """Prompt for user confirmation.""" while True: response = input(user_message + " (yes/no): ").strip().lower() if response in ["yes", "y"]: @@ -349,10 +325,7 @@ def _upgrade_daqmx_user_confirmation( latest_version: str, release: str, ) -> bool: - """ - Confirm with the user and return the user response. - - """ + """Confirm with the user and return the user response.""" _logger.debug("Entering _upgrade_daqmx_user_confirmation") installed_parts = _parse_version(installed_version) latest_parts = _parse_version(latest_version) @@ -371,10 +344,7 @@ def _fresh_install_daqmx_user_confirmation( latest_version: str, release: str, ) -> bool: - """ - Confirm with the user and return the user response. - - """ + """Confirm with the user and return the user response.""" _logger.debug("Entering _fresh_install_daqmx_user_confirmation") return _ask_user_confirmation( f"Latest NI-DAQmx version available is {latest_version} ({release}). Do you want to install?" @@ -382,10 +352,7 @@ def _fresh_install_daqmx_user_confirmation( def _is_distribution_supported() -> None: - """ - Raises an exception if the linux distribution and its version are not supported. - - """ + """Raises an exception if the linux distribution and its version are not supported.""" if sys.platform.startswith("linux"): dist_name = distro.id() dist_version = distro.version() @@ -409,10 +376,7 @@ def _is_distribution_supported() -> None: def _install_daqmx_driver(): - """ - Install the NI-DAQmx driver. - - """ + """Install the NI-DAQmx driver.""" if sys.platform.startswith("win"): _logger.info("Windows platform detected") platform = "Windows" @@ -443,9 +407,7 @@ def _install_daqmx_driver(): installed_version, latest_version, release ) else: - user_response = _fresh_install_daqmx_user_confirmation( - latest_version, release - ) + user_response = _fresh_install_daqmx_user_confirmation(latest_version, release) if user_response: if platform == "Linux": @@ -455,10 +417,7 @@ def _install_daqmx_driver(): def installdriver() -> None: - """ - Download and launch NI-DAQmx Driver installation in an interactive mode. - - """ + """Download and launch NI-DAQmx Driver installation in an interactive mode.""" try: _install_daqmx_driver() except click.ClickException: diff --git a/generated/nidaqmx/_lib.py b/generated/nidaqmx/_lib.py index b68489678..8fccba52b 100644 --- a/generated/nidaqmx/_lib.py +++ b/generated/nidaqmx/_lib.py @@ -1,35 +1,45 @@ from __future__ import annotations -from ctypes.util import find_library import ctypes -from numpy.ctypeslib import ndpointer -import platform +import locale import sys import threading -import locale +from ctypes.util import find_library +from typing import TYPE_CHECKING, cast + from decouple import config -from typing import cast, TYPE_CHECKING +from numpy.ctypeslib import ndpointer -from nidaqmx.errors import DaqNotFoundError, DaqNotSupportedError, DaqFunctionNotSupportedError +from nidaqmx.errors import ( + DaqFunctionNotSupportedError, + DaqNotFoundError, + DaqNotSupportedError, +) if TYPE_CHECKING: from typing_extensions import TypeAlias -_DAQ_NOT_FOUND_MESSAGE = "Could not find an installation of NI-DAQmx. Please ensure that NI-DAQmx " \ - "is installed on this machine or contact National Instruments for support." +_DAQ_NOT_FOUND_MESSAGE = ( + "Could not find an installation of NI-DAQmx. Please ensure that NI-DAQmx " + "is installed on this machine or contact National Instruments for support." +) -_DAQ_NOT_SUPPORTED_MESSAGE = "NI-DAQmx Python is not supported on this platform: {0}. Please " \ - "direct any questions or feedback to National Instruments." +_DAQ_NOT_SUPPORTED_MESSAGE = ( + "NI-DAQmx Python is not supported on this platform: {0}. Please " + "direct any questions or feedback to National Instruments." +) -_FUNCTION_NOT_SUPPORTED_MESSAGE = "The NI-DAQmx function \"{0}\" is not supported in this version " \ - "of NI-DAQmx. Visit ni.com/downloads to upgrade." +_FUNCTION_NOT_SUPPORTED_MESSAGE = ( + 'The NI-DAQmx function "{0}" is not supported in this version ' + "of NI-DAQmx. Visit ni.com/downloads to upgrade." +) -class c_bool32(ctypes.c_uint): - """ - Specifies a custom ctypes data type to represent 32-bit booleans. - """ +class c_bool32( # noqa: N801 - class name 'c_bool32' should use CapWords convention (auto-generated noqa) + ctypes.c_uint +): + """Specifies a custom ctypes data type to represent 32-bit booleans.""" # typeshed specifies that _SimpleCData[_T].value is an instance variable with type _T, so # accessing it with the descriptor protocol via its class results in "error: Access to generic @@ -47,12 +57,12 @@ def _setter(self, val): class CtypesByteString: - """ - Custom argtype that automatically converts unicode strings to encoding - used by the DAQmx C API DLL in Python 3. - """ + """Custom argtype that automatically converts unicode strings to encoding used by the C API.""" + @classmethod - def from_param(cls, param): + def from_param( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + cls, param + ): if isinstance(param, str): param = param.encode(lib_importer.encoding) return ctypes.c_char_p(param) @@ -62,9 +72,7 @@ def from_param(cls, param): def wrapped_ndpointer(*args, **kwargs): - """ - Specifies an ndpointer type that wraps numpy.ctypeslib.ndpointer and - allows a value of None to be passed to an argument of that type. + """Wraps numpy.ctypeslib.ndpointer in order to allow passing None. Taken from http://stackoverflow.com/questions/32120178 """ @@ -75,28 +83,29 @@ def from_param(cls, obj): return obj return base.from_param(obj) - return type(base.__name__, (base,), - {'from_param': classmethod(from_param)}) + return type(base.__name__, (base,), {"from_param": classmethod(from_param)}) class DaqFunctionImporter: - """ - Wraps the function getter function of a ctypes library. + """Wraps the function getter function of a ctypes library. Allows the NI-DAQmx Python API to fail elegantly if a function is not supported in the current version of the API. """ def __init__(self, library): + """Initialize a new DaqFunctionImporter.""" self._library = library self._lib_lock = threading.Lock() - def __getattr__(self, function): + def __getattr__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, function + ): try: cfunc = getattr(self._library, function) - if not hasattr(cfunc, 'arglock'): + if not hasattr(cfunc, "arglock"): with self._lib_lock: - if not hasattr(cfunc, 'arglock'): + if not hasattr(cfunc, "arglock"): cfunc.arglock = threading.Lock() return cfunc except AttributeError: @@ -121,19 +130,16 @@ def __getattr__(self, function): def get_encoding_from_locale() -> str: - """ - Gets the current locale encoding handling cases where it is unset. - """ + """Gets the current locale encoding handling cases where it is unset.""" _, encoding = locale.getlocale() - return encoding or 'ascii' + return encoding or "ascii" class DaqLibImporter: - """ - Encapsulates NI-DAQmx library importing and handle type parsing logic. - """ + """Encapsulates NI-DAQmx library importing and handle type parsing logic.""" def __init__(self): + """Initialize a new DaqLibImporter.""" self._windll = None self._cdll = None self._cal_handle = None @@ -141,35 +147,37 @@ def __init__(self): self._encoding = None @property - def windll(self): + def windll(self): # noqa: D102 - Missing docstring in public method (auto-generated noqa) if self._windll is None: self._import_lib() return self._windll @property - def cdll(self): + def cdll(self): # noqa: D102 - Missing docstring in public method (auto-generated noqa) if self._cdll is None: self._import_lib() return self._cdll @property - def task_handle(self) -> type: + def task_handle( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ) -> type: return TaskHandle @property - def cal_handle(self) -> type: + def cal_handle( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ) -> type: return CalHandle - + @property - def encoding(self): + def encoding(self): # noqa: D102 - Missing docstring in public method (auto-generated noqa) if self._encoding is None: self._import_lib() return self._encoding def _import_lib(self): - """ - Determines the location of and loads the NI-DAQmx CAI DLL. - """ + """Determines the location of and loads the NI-DAQmx CAI DLL.""" self._windll = None self._cdll = None self._encoding = None @@ -178,42 +186,44 @@ def _import_lib(self): cdll = None encoding = None - if sys.platform.startswith('win'): + if sys.platform.startswith("win"): def _load_lib(libname: str): windll = ctypes.windll.LoadLibrary(libname) cdll = ctypes.cdll.LoadLibrary(libname) - return windll, cdll - + return windll, cdll + # Feature Toggle to load nicaiu.dll or nicai_utf8.dll # The Feature Toggle can be set in the .env file - nidaqmx_c_library = config('NIDAQMX_C_LIBRARY', default=None) - + nidaqmx_c_library = config("NIDAQMX_C_LIBRARY", default=None) + if nidaqmx_c_library is not None: - try: - if nidaqmx_c_library=="nicaiu": + try: + if nidaqmx_c_library == "nicaiu": windll, cdll = _load_lib("nicaiu") encoding = get_encoding_from_locale() - elif nidaqmx_c_library=="nicai_utf8": + elif nidaqmx_c_library == "nicai_utf8": windll, cdll = _load_lib("nicai_utf8") - encoding = 'utf-8' + encoding = "utf-8" else: - raise ValueError(f"Unsupported NIDAQMX_C_LIBRARY value: {nidaqmx_c_library}") + raise ValueError( + f"Unsupported NIDAQMX_C_LIBRARY value: {nidaqmx_c_library}" + ) except OSError as e: - raise DaqNotFoundError(_DAQ_NOT_FOUND_MESSAGE) from e + raise DaqNotFoundError(_DAQ_NOT_FOUND_MESSAGE) from e else: try: windll, cdll = _load_lib("nicai_utf8") - encoding = 'utf-8' + encoding = "utf-8" except OSError: # Fallback to nicaiu.dll if nicai_utf8.dll cannot be loaded try: windll, cdll = _load_lib("nicaiu") encoding = get_encoding_from_locale() except OSError as e: - raise DaqNotFoundError(_DAQ_NOT_FOUND_MESSAGE) from e - elif sys.platform.startswith('linux'): - library_path = find_library('nidaqmx') + raise DaqNotFoundError(_DAQ_NOT_FOUND_MESSAGE) from e + elif sys.platform.startswith("linux"): + library_path = find_library("nidaqmx") if library_path is not None: cdll = ctypes.cdll.LoadLibrary(library_path) windll = cdll diff --git a/generated/nidaqmx/_lib_time.py b/generated/nidaqmx/_lib_time.py index 69444a3fb..8af8ebb38 100644 --- a/generated/nidaqmx/_lib_time.py +++ b/generated/nidaqmx/_lib_time.py @@ -2,16 +2,17 @@ import ctypes import functools -from datetime import timezone -from datetime import datetime as std_datetime -from datetime import tzinfo as dt_tzinfo -from hightime import datetime as ht_datetime -from hightime import timedelta as ht_timedelta -from typing import Optional, Union +from datetime import datetime as std_datetime, timezone, tzinfo as dt_tzinfo + +from hightime import datetime as ht_datetime, timedelta as ht_timedelta + from nidaqmx._time import _convert_to_desired_timezone + @functools.total_ordering -class AbsoluteTime(ctypes.Structure): +class AbsoluteTime( # noqa: D101 - Missing docstring in public class (auto-generated noqa) + ctypes.Structure +): # Please visit ni.com/info and enter the Info Code NI_BTF for detailed information. # The summary is: # * lsb - positive fractions (2^-64) of a second @@ -33,9 +34,10 @@ class AbsoluteTime(ctypes.Structure): _EPOCH_1904 = ht_datetime(1904, 1, 1, tzinfo=timezone.utc) - @classmethod - def from_datetime(cls, dt: std_datetime | ht_datetime) -> AbsoluteTime: + def from_datetime( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + cls, dt: std_datetime | ht_datetime + ) -> AbsoluteTime: seconds_since_1904 = 0 # Convert the subseconds. @@ -49,27 +51,37 @@ def from_datetime(cls, dt: std_datetime | ht_datetime) -> AbsoluteTime: ) else: seconds_since_1904 = int((dt - AbsoluteTime._EPOCH_1904).total_seconds()) - lsb = int( - round(AbsoluteTime._NUM_SUBSECONDS * dt.microsecond / AbsoluteTime._US_PER_S) - ) + lsb = int(round(AbsoluteTime._NUM_SUBSECONDS * dt.microsecond / AbsoluteTime._US_PER_S)) return AbsoluteTime(lsb=lsb, msb=seconds_since_1904) - def to_datetime(self, tzinfo: dt_tzinfo | None = None) -> ht_datetime: + def to_datetime( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, tzinfo: dt_tzinfo | None = None + ) -> ht_datetime: total_yoctoseconds = int( round(AbsoluteTime._YS_PER_S * self.lsb / AbsoluteTime._NUM_SUBSECONDS) ) - dt = AbsoluteTime._EPOCH_1904 + ht_timedelta(seconds=self.msb) + ht_timedelta(yoctoseconds=total_yoctoseconds) - return _convert_to_desired_timezone(dt,tzinfo) + dt = ( + AbsoluteTime._EPOCH_1904 + + ht_timedelta(seconds=self.msb) + + ht_timedelta(yoctoseconds=total_yoctoseconds) + ) + return _convert_to_desired_timezone(dt, tzinfo) - def __str__(self) -> str: + def __str__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, + ) -> str: return f"AbsoluteTime(lsb=0x{self.lsb:x}, msb=0x{self.msb:x})" - def __eq__(self, other) -> bool: + def __eq__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, other + ) -> bool: return self.msb == other.msb and self.lsb == other.lsb - def __lt__(self, other) -> bool: + def __lt__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, other + ) -> bool: if self.msb == other.msb: return self.lsb < other.lsb else: - return self.msb < other.msb \ No newline at end of file + return self.msb < other.msb diff --git a/generated/nidaqmx/_linux_installation_commands.py b/generated/nidaqmx/_linux_installation_commands.py index 8e26cd743..cacd90176 100644 --- a/generated/nidaqmx/_linux_installation_commands.py +++ b/generated/nidaqmx/_linux_installation_commands.py @@ -1,7 +1,8 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Callable, Dict, List, Tuple +from typing import Callable + def _get_version_ubuntu(dist_version: str) -> str: return dist_version.replace(".", "") @@ -57,8 +58,9 @@ def _get_version_rhel(dist_version: str) -> str: _DEBIAN_DAQMX_VERSION_COMMAND = ["dpkg", "-l", "ni-daqmx"] _RPM_DAQMX_VERSION_COMMAND = ["rpm", "-q", "ni-daqmx"] + @dataclass -class DistroInfo: +class DistroInfo: # noqa: D101 - Missing docstring in public class (auto-generated noqa) get_distro_version: Callable[[str], str] get_daqmx_version: list[str] install_commands: list[list[str]] @@ -77,10 +79,7 @@ class DistroInfo: def get_linux_installation_commands( _directory_to_extract_to: str, dist_name: str, dist_version: str, _release_string: str ) -> list[list[str]]: - """ - Get the installation commands for Linux based on the distribution. - - """ + """Get the installation commands for Linux based on the distribution.""" if dist_name not in LINUX_COMMANDS: raise ValueError(f"Unsupported distribution '{dist_name}'") diff --git a/generated/nidaqmx/_time.py b/generated/nidaqmx/_time.py index 06edadd50..0acdf7f12 100644 --- a/generated/nidaqmx/_time.py +++ b/generated/nidaqmx/_time.py @@ -1,15 +1,16 @@ from __future__ import annotations -from tzlocal import get_localzone -from datetime import timezone -from datetime import tzinfo as dt_tzinfo -from datetime import datetime as std_datetime -from hightime import datetime as ht_datetime -from typing import Optional, Union +from datetime import datetime as std_datetime, timezone, tzinfo as dt_tzinfo from zoneinfo import ZoneInfo +from hightime import datetime as ht_datetime +from tzlocal import get_localzone + + # theoretically the same as astimezone(), but with support for dates before 1970 -def _convert_to_desired_timezone(expected_time_utc: std_datetime | ht_datetime, tzinfo: dt_tzinfo | None = None) -> std_datetime | ht_datetime: +def _convert_to_desired_timezone( + expected_time_utc: std_datetime | ht_datetime, tzinfo: dt_tzinfo | None = None +) -> std_datetime | ht_datetime: # if timezone matches, no need to do conversion if expected_time_utc.tzinfo is tzinfo: return expected_time_utc @@ -22,9 +23,9 @@ def _convert_to_desired_timezone(expected_time_utc: std_datetime | ht_datetime, if isinstance(tzinfo, ZoneInfo): localized_time = expected_time_utc.replace(tzinfo=tzinfo) desired_expected_time = tzinfo.fromutc(localized_time) - return(desired_expected_time) + return desired_expected_time - # if the tzinfo passed in is a timedelta function, then we don't need to consider daylight savings + # if the tzinfo passed in is a timedelta function, then we don't need to consider daylight savings # noqa: W505 - doc line too long (102 > 100 characters) (auto-generated noqa) elif tzinfo.utcoffset(None) is not None: current_time_utc = ht_datetime.now(timezone.utc) desired_timezone_offset = current_time_utc.astimezone(tz=tzinfo).utcoffset() diff --git a/generated/nidaqmx/errors.py b/generated/nidaqmx/errors.py index 3dec1c60d..03c779acf 100644 --- a/generated/nidaqmx/errors.py +++ b/generated/nidaqmx/errors.py @@ -1,50 +1,48 @@ +"""NI-DAQmx error classes.""" + import warnings + import deprecation from nidaqmx.error_codes import DAQmxErrors, DAQmxWarnings -__all__ = ['DaqError', 'DaqReadError', 'DaqWriteError', 'DaqWarning', 'DaqResourceWarning'] +__all__ = ["DaqError", "DaqReadError", "DaqWriteError", "DaqWarning", "DaqResourceWarning"] class Error(Exception): - """ - Base error class for module. - """ + """Base error class for module.""" + pass class DaqNotFoundError(Error): - """ - Error raised when NI-DAQmx driver is not installed. - """ + """Error raised when NI-DAQmx driver is not installed.""" + pass class DaqNotSupportedError(Error): - """ - Error raised when DAQmx is not supported on this platform. - """ + """Error raised when DAQmx is not supported on this platform.""" + pass class DaqFunctionNotSupportedError(Error): - """ - Error raised when a specific function isn't supported by the installed - version of the NI-DAQmx driver. - """ + """Error raised when a specific function isn't supported by the installed NI-DAQmx driver.""" + pass class DaqError(Error): - """ - Error raised by any DAQmx method. - """ - def __init__(self, message, error_code, task_name=''): - """ + """Error raised by any DAQmx method.""" + + def __init__(self, message, error_code, task_name=""): + """Initialize a new DaqError. + Args: message (string): Specifies the error message. error_code (int): Specifies the NI-DAQmx error code. - """ + """ # noqa: D417 - Missing argument descriptions in the docstring (auto-generated noqa) self._error_code = int(error_code) try: @@ -54,93 +52,80 @@ def __init__(self, message, error_code, task_name=''): # If message is empty, we try to put at least some information in it if not message: - message = f'Description could not be found for the status code.\n\nStatus Code: {self._error_code}' + message = f"Description could not be found for the status code.\n\nStatus Code: {self._error_code}" if task_name: - message = f'{message}\n\nTask Name: {task_name}' - - # We do not know where the error description came from, so we add the status code if it is not already in the message + message = f"{message}\n\nTask Name: {task_name}" + + # We do not know where the error description came from, so we add the status code if it is not already in the message # noqa: W505 - doc line too long (125 > 100 characters) (auto-generated noqa) if str(self._error_code) not in message: - message = f'{message}\n\nStatus Code: {self._error_code}' + message = f"{message}\n\nStatus Code: {self._error_code}" super().__init__(message) @property def error_code(self): - """ - int: Specifies the NI-DAQmx error code. - """ + """int: Specifies the NI-DAQmx error code.""" return self._error_code @property def error_type(self): - """ - :class:`nidaqmx.error_codes.DAQmxErrors`: Specifies the NI-DAQmx - error type. - """ + """:class:`nidaqmx.error_codes.DAQmxErrors`: Specifies the NI-DAQmx error type.""" return self._error_type class DaqReadError(DaqError): - """ - Error raised by DAQmx write method that includes the amount of data that was - read. - """ - def __init__(self, message, error_code, samps_per_chan_read, task_name=''): - """ + """Error raised by DAQmx write method that includes the amount of data that was read.""" + + def __init__(self, message, error_code, samps_per_chan_read, task_name=""): + """Initialize a new DaqReadError. + Args: message (string): Specifies the error message. error_code (int): Specifies the NI-DAQmx error code. - """ + """ # noqa: D417 - Missing argument descriptions in the docstring (auto-generated noqa) super().__init__(message, error_code, task_name) self._samps_per_chan_read = samps_per_chan_read @property def samps_per_chan_read(self): - """ - int: Indicates the number of samples successfully read. - """ + """int: Indicates the number of samples successfully read.""" return self._samps_per_chan_read class DaqWriteError(DaqError): - """ - Error raised by DAQmx write method that includes the amount of data that was - written. - """ - def __init__(self, message, error_code, samps_per_chan_written, task_name=''): - """ + """Error raised by DAQmx write method that includes the amount of data that was written.""" + + def __init__(self, message, error_code, samps_per_chan_written, task_name=""): + """Initialize a new DaqWriteError. + Args: message (string): Specifies the error message. error_code (int): Specifies the NI-DAQmx error code. samps_per_chan_written (int): Specifies the number of samples written. - """ + """ # noqa: D417 - Missing argument descriptions in the docstring (auto-generated noqa) super().__init__(message, error_code, task_name) self._samps_per_chan_written = samps_per_chan_written @property def samps_per_chan_written(self): - """ - int: Indicates the number of samples successfully written. - """ + """int: Indicates the number of samples successfully written.""" return self._samps_per_chan_written - class DaqWarning(Warning): - """ - Warning raised by any NI-DAQmx method. - """ + """Warning raised by any NI-DAQmx method.""" + def __init__(self, message, error_code): - """ + """Initialize a new DaqWarning. + Args: message (string): Specifies the warning message. error_code (int): Specifies the NI-DAQmx error code. """ - super().__init__( - f'\nWarning {error_code} occurred.\n\n{message}') + super().__init__(f"\nWarning {error_code} occurred.\n\n{message}") self._error_code = int(error_code) @@ -151,51 +136,64 @@ def __init__(self, message, error_code): @property def error_code(self): - """ - int: Specifies the NI-DAQmx error code. - """ + """int: Specifies the NI-DAQmx error code.""" return self._error_code @property def error_type(self): - """ - :class:`nidaqmx.error_codes.DAQmxWarnings`: Specifies the NI-DAQmx - error type. - """ + """:class:`nidaqmx.error_codes.DAQmxWarnings`: Specifies the NI-DAQmx error type.""" return self._error_type + class DaqResourceWarning(ResourceWarning): + """Warning about DAQ resource usage, such as a leaking an NI-DAQmx task.""" + pass + warnings.filterwarnings("always", category=DaqWarning) warnings.filterwarnings("always", category=DaqResourceWarning) -@deprecation.deprecated(deprecated_in="0.8.0", details="This function will be removed in a future update.") + +@deprecation.deprecated( + deprecated_in="0.8.0", details="This function will be removed in a future update." +) def check_for_error(error_code, samps_per_chan_written=None, samps_per_chan_read=None): from nidaqmx._library_interpreter import LibraryInterpreter - return LibraryInterpreter().check_for_error(error_code, samps_per_chan_written, samps_per_chan_read) + + return LibraryInterpreter().check_for_error( + error_code, samps_per_chan_written, samps_per_chan_read + ) -@deprecation.deprecated(deprecated_in="0.8.0", details="This function will be removed in a future update.") +@deprecation.deprecated( + deprecated_in="0.8.0", details="This function will be removed in a future update." +) def is_string_buffer_too_small(error_code): import nidaqmx._library_interpreter + return nidaqmx._library_interpreter.is_string_buffer_too_small(error_code) -@deprecation.deprecated(deprecated_in="0.8.0", details="This function will be removed in a future update.") +@deprecation.deprecated( + deprecated_in="0.8.0", details="This function will be removed in a future update." +) def is_array_buffer_too_small(error_code): import nidaqmx._library_interpreter + return nidaqmx._library_interpreter.is_array_buffer_too_small(error_code) class RpcError(Error): - '''An error specific to sessions to the NI gRPC Device Server''' + """An error specific to sessions to the NI gRPC Device Server.""" def __init__(self, rpc_code, description): + """Initialize a new RpcError.""" self.rpc_code = rpc_code self.description = description try: import grpc + rpc_error = str(grpc.StatusCode(self.rpc_code)) except Exception: rpc_error = str(self.rpc_code) @@ -203,4 +201,4 @@ def __init__(self, rpc_code, description): class FeatureNotSupportedError(Exception): - """The feature is not supported at the current code readiness level.""" \ No newline at end of file + """The feature is not supported at the current code readiness level.""" diff --git a/generated/nidaqmx/grpc_session_options.py b/generated/nidaqmx/grpc_session_options.py index 16191fa13..fdabdc3b3 100644 --- a/generated/nidaqmx/grpc_session_options.py +++ b/generated/nidaqmx/grpc_session_options.py @@ -1,4 +1,7 @@ +"""NI-DAQmx gRPC session options.""" + from __future__ import annotations + from enum import IntEnum from typing import TYPE_CHECKING @@ -7,42 +10,44 @@ # This constant specifies the gRPC package and service used by this API. -# Customers can pass this value to the MeasurementLink discovery service to resolve the server instance that provides this interface. -GRPC_SERVICE_INTERFACE_NAME = 'nidaqmx_grpc.NiDAQmx' +# Customers can pass this value to the MeasurementLink discovery service to resolve the server instance that provides this interface. # noqa: W505 - doc line too long (133 > 100 characters) (auto-generated noqa) +GRPC_SERVICE_INTERFACE_NAME = "nidaqmx_grpc.NiDAQmx" # This constant specifies the API license key required by the NI gRPC Device Server that comes with # MeasurementLink 2023 Q1. -MEASUREMENTLINK_23Q1_NIDAQMX_PYTHON_API_KEY = '147D9BA7-BE75-4B29-8591-BA4A737AA8CF' +MEASUREMENTLINK_23Q1_NIDAQMX_PYTHON_API_KEY = "147D9BA7-BE75-4B29-8591-BA4A737AA8CF" class SessionInitializationBehavior(IntEnum): + """Specifies how to initialize sessions on the server.""" + AUTO = 0 - r''' + r""" The NI gRPC Device Server will attach to an existing session with the specified name if it exists, otherwise the server will initialize a new session. Note: When using the Session as a context manager and the context exits, the behavior depends on what happened when the constructor was called. If it resulted in a new session being initialized on the NI gRPC Device Server, then it will automatically close the server session. If it instead attached to an existing session, then it will detach from the server session and leave it open. - ''' + """ # noqa: W505 - doc line too long (123 > 100 characters) (auto-generated noqa) INITIALIZE_SERVER_SESSION = 1 - r''' + r""" Require the NI gRPC Device Server to initialize a new session with the specified name. Note: When using the Session as a context manager and the context exits, it will automatically close the server session. - ''' + """ # noqa: W505 - doc line too long (102 > 100 characters) (auto-generated noqa) ATTACH_TO_SERVER_SESSION = 2 - r''' + r""" Require the NI gRPC Device Server to attach to an existing session with the specified name. Note: When using the Session as a context manager and the context exits, it will detach from the server session and leave it open. - ''' + """ # noqa: W505 - doc line too long (109 > 100 characters) (auto-generated noqa) class GrpcSessionOptions: - '''Collection of options that specifies session behaviors related to gRPC.''' + """Collection of options that specifies session behaviors related to gRPC.""" def __init__( self, @@ -50,10 +55,10 @@ def __init__( session_name: str, *, api_key=MEASUREMENTLINK_23Q1_NIDAQMX_PYTHON_API_KEY, - initialization_behavior=SessionInitializationBehavior.AUTO + initialization_behavior=SessionInitializationBehavior.AUTO, ): - r'''Collection of options that specifies session behaviors related to gRPC. - Creates and returns an object you can pass to a Session constructor. + """Initialize a new GrpcSessionOptions. + Args: grpc_channel (grpc.Channel): Specifies the channel to the NI gRPC Device Server. session_name (str): User-specified name that identifies the driver session on the NI gRPC Device @@ -65,7 +70,7 @@ def __init__( initialization_behavior (enum): Specifies whether it is acceptable to initialize a new session or attach to an existing one, or if only one of the behaviors is desired. The driver session exists on the NI gRPC Device Server. - ''' + """ # noqa: W505 - doc line too long (108 > 100 characters) (auto-generated noqa) self.grpc_channel = grpc_channel self.session_name = session_name self.api_key = api_key diff --git a/generated/nidaqmx/stream_readers/__init__.py b/generated/nidaqmx/stream_readers/__init__.py index bd1beccb5..bfd21e0a0 100644 --- a/generated/nidaqmx/stream_readers/__init__.py +++ b/generated/nidaqmx/stream_readers/__init__.py @@ -1,5 +1,4 @@ -""" -NI-DAQmx stream readers. +"""NI-DAQmx stream readers. This package provides classes for reading samples from NI-DAQmx tasks. """ @@ -7,27 +6,32 @@ from __future__ import annotations from nidaqmx import DaqError - -from nidaqmx.stream_readers._analog_single_channel_reader import AnalogSingleChannelReader from nidaqmx.stream_readers._analog_multi_channel_reader import AnalogMultiChannelReader +from nidaqmx.stream_readers._analog_single_channel_reader import ( + AnalogSingleChannelReader, +) from nidaqmx.stream_readers._analog_unscaled_reader import AnalogUnscaledReader from nidaqmx.stream_readers._counter_reader import CounterReader -from nidaqmx.stream_readers._digital_single_channel_reader import DigitalSingleChannelReader -from nidaqmx.stream_readers._digital_multi_channel_reader import DigitalMultiChannelReader +from nidaqmx.stream_readers._digital_multi_channel_reader import ( + DigitalMultiChannelReader, +) +from nidaqmx.stream_readers._digital_single_channel_reader import ( + DigitalSingleChannelReader, +) from nidaqmx.stream_readers._power_readers import ( - PowerSingleChannelReader, - PowerMultiChannelReader, PowerBinaryReader, + PowerMultiChannelReader, + PowerSingleChannelReader, ) __all__ = [ - 'AnalogSingleChannelReader', - 'AnalogMultiChannelReader', - 'AnalogUnscaledReader', - 'CounterReader', - 'DigitalSingleChannelReader', - 'DigitalMultiChannelReader', - 'PowerSingleChannelReader', - 'PowerMultiChannelReader', - 'PowerBinaryReader', + "AnalogSingleChannelReader", + "AnalogMultiChannelReader", + "AnalogUnscaledReader", + "CounterReader", + "DigitalSingleChannelReader", + "DigitalMultiChannelReader", + "PowerSingleChannelReader", + "PowerMultiChannelReader", + "PowerBinaryReader", ] diff --git a/generated/nidaqmx/stream_readers/_analog_multi_channel_reader.py b/generated/nidaqmx/stream_readers/_analog_multi_channel_reader.py index 323b7a273..b75aba567 100644 --- a/generated/nidaqmx/stream_readers/_analog_multi_channel_reader.py +++ b/generated/nidaqmx/stream_readers/_analog_multi_channel_reader.py @@ -1,28 +1,22 @@ from __future__ import annotations import numpy -from nidaqmx import DaqError +from nitypes.waveform import AnalogWaveform +from nidaqmx import DaqError from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature -from nidaqmx.constants import FillMode, READ_ALL_AVAILABLE, ReallocationPolicy +from nidaqmx.constants import READ_ALL_AVAILABLE, FillMode, ReallocationPolicy from nidaqmx.error_codes import DAQmxErrors -from nitypes.waveform import AnalogWaveform - from nidaqmx.stream_readers._channel_reader_base import ChannelReaderBase class AnalogMultiChannelReader(ChannelReaderBase): - """ - Reads samples from one or more analog input channels in an NI-DAQmx - task. - """ + """Reads samples from one or more analog input channels in an NI-DAQmx task.""" def read_many_sample( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more floating-point samples from one or more analog - input channels in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more floating-point samples from one or more analog input channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -83,29 +77,32 @@ def read_many_sample( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (101 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) _, samps_per_chan_read = self._interpreter.read_analog_f64( - self._handle, number_of_samples_per_channel, - timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_one_sample(self, data, timeout=10): - """ - Reads a single floating-point sample from one or more analog - input channels in a task. + """Reads a single floating-point sample from one or more analog input channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -136,7 +133,9 @@ def read_one_sample(self, data, timeout=10): """ self._verify_array(data, 1, True, False) - self._interpreter.read_analog_f64(self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._interpreter.read_analog_f64( + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) @requires_feature(WAVEFORM_SUPPORT) def read_waveforms( @@ -146,9 +145,7 @@ def read_waveforms( reallocation_policy: ReallocationPolicy = ReallocationPolicy.TO_GROW, timeout: int = 10, ) -> int: - """ - Reads one or more floating-point samples from one or more analog - input channels into a list of waveforms. + """Reads one or more floating-point samples from one or more analog input channels into a list of waveforms. This read method optionally accepts a preallocated list of waveforms to hold the samples requested, which can be advantageous for performance and @@ -161,7 +158,7 @@ def read_waveforms( Args: waveforms (list[AnalogWaveform]): Specifies a list of AnalogWaveform objects to use for reading samples into. - The list must contain one waveform for each channel in the task. + The list must contain one waveform for each channel in the task. number_of_samples_per_channel (Optional[int]): Specifies the number of samples to read. @@ -194,35 +191,40 @@ def read_waveforms( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ + """ # noqa: W505 - doc line too long (116 > 100 characters) (auto-generated noqa) number_of_channels = self._in_stream.num_chans - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) if len(waveforms) != number_of_channels: raise DaqError( - f'The number of waveforms provided ({len(waveforms)}) does not match ' - f'the number of channels in the task ({number_of_channels}). Please provide ' - 'one waveform for each channel.', - DAQmxErrors.MISMATCHED_INPUT_ARRAY_SIZES, task_name=self._task.name) - + f"The number of waveforms provided ({len(waveforms)}) does not match " + f"the number of channels in the task ({number_of_channels}). Please provide " + "one waveform for each channel.", + DAQmxErrors.MISMATCHED_INPUT_ARRAY_SIZES, + task_name=self._task.name, + ) + for i, waveform in enumerate(waveforms): if waveform.start_index + number_of_samples_per_channel > waveform.capacity: if reallocation_policy == ReallocationPolicy.TO_GROW: waveform.capacity = waveform.start_index + number_of_samples_per_channel else: raise DaqError( - f'The waveform at index {i} does not have enough space ({waveform.capacity - waveform.start_index}) to hold ' - f'the requested number of samples ({number_of_samples_per_channel}). Please provide larger ' - 'waveforms or adjust the number of samples requested.', - DAQmxErrors.READ_BUFFER_TOO_SMALL, task_name=self._task.name) + f"The waveform at index {i} does not have enough space ({waveform.capacity - waveform.start_index}) to hold " + f"the requested number of samples ({number_of_samples_per_channel}). Please provide larger " + "waveforms or adjust the number of samples requested.", + DAQmxErrors.READ_BUFFER_TOO_SMALL, + task_name=self._task.name, + ) return self._interpreter.read_analog_waveforms( self._handle, diff --git a/generated/nidaqmx/stream_readers/_analog_single_channel_reader.py b/generated/nidaqmx/stream_readers/_analog_single_channel_reader.py index 0a8db41f5..5d67b0c6c 100644 --- a/generated/nidaqmx/stream_readers/_analog_single_channel_reader.py +++ b/generated/nidaqmx/stream_readers/_analog_single_channel_reader.py @@ -1,27 +1,22 @@ from __future__ import annotations import numpy -from nidaqmx import DaqError +from nitypes.waveform import AnalogWaveform +from nidaqmx import DaqError from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature -from nidaqmx.constants import FillMode, READ_ALL_AVAILABLE, ReallocationPolicy +from nidaqmx.constants import READ_ALL_AVAILABLE, FillMode, ReallocationPolicy from nidaqmx.error_codes import DAQmxErrors -from nitypes.waveform import AnalogWaveform - from nidaqmx.stream_readers._channel_reader_base import ChannelReaderBase class AnalogSingleChannelReader(ChannelReaderBase): - """ - Reads samples from an analog input channel in an NI-DAQmx task. - """ + """Reads samples from an analog input channel in an NI-DAQmx task.""" def read_many_sample( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more floating-point samples from a single analog - input channel in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more floating-point samples from a single analog input channel in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -69,6 +64,7 @@ def read_many_sample( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: @@ -76,22 +72,24 @@ def read_many_sample( NI-DAQmx returns a single value because this value is the same for all channels. """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, False, True) _, samps_per_chan_read = self._interpreter.read_analog_f64( - self._handle, number_of_samples_per_channel, - timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_one_sample(self, timeout=10): - """ - Reads a single floating-point sample from a single analog input - channel in a task. + """Reads a single floating-point sample from a single analog input channel in a task. Args: timeout (Optional[float]): Specifies the amount of time in @@ -103,6 +101,7 @@ def read_one_sample(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: float: @@ -112,15 +111,13 @@ def read_one_sample(self, timeout=10): @requires_feature(WAVEFORM_SUPPORT) def read_waveform( - self, + self, waveform: AnalogWaveform[numpy.float64], - number_of_samples_per_channel: int = READ_ALL_AVAILABLE, + number_of_samples_per_channel: int = READ_ALL_AVAILABLE, reallocation_policy: ReallocationPolicy = ReallocationPolicy.TO_GROW, - timeout: int = 10, + timeout: int = 10, ) -> int: - """ - Reads one or more floating-point samples from a single analog - input channel into a waveform. + """Reads one or more floating-point samples from a single analog input channel into a waveform. This read method optionally accepts a preallocated waveform to hold the samples requested, which can be advantageous for performance and @@ -165,24 +162,27 @@ def read_waveform( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) if waveform.start_index + number_of_samples_per_channel > waveform.capacity: if reallocation_policy == ReallocationPolicy.TO_GROW: waveform.capacity = waveform.start_index + number_of_samples_per_channel else: raise DaqError( - f'The provided waveform does not have enough space ({waveform.capacity - waveform.start_index}) to hold ' - f'the requested number of samples ({number_of_samples_per_channel}). Please provide a larger ' - 'waveform or adjust the number of samples requested.', - DAQmxErrors.READ_BUFFER_TOO_SMALL, task_name=self._task.name) + f"The provided waveform does not have enough space ({waveform.capacity - waveform.start_index}) to hold " + f"the requested number of samples ({number_of_samples_per_channel}). Please provide a larger " + "waveform or adjust the number of samples requested.", + DAQmxErrors.READ_BUFFER_TOO_SMALL, + task_name=self._task.name, + ) return self._interpreter.read_analog_waveform( self._handle, diff --git a/generated/nidaqmx/stream_readers/_analog_unscaled_reader.py b/generated/nidaqmx/stream_readers/_analog_unscaled_reader.py index db4a220d4..21aa028f6 100644 --- a/generated/nidaqmx/stream_readers/_analog_unscaled_reader.py +++ b/generated/nidaqmx/stream_readers/_analog_unscaled_reader.py @@ -1,22 +1,14 @@ from __future__ import annotations -from nidaqmx.constants import FillMode, READ_ALL_AVAILABLE - +from nidaqmx.constants import READ_ALL_AVAILABLE, FillMode from nidaqmx.stream_readers._channel_reader_base import ChannelReaderBase class AnalogUnscaledReader(ChannelReaderBase): - """ - Reads unscaled samples from one or more analog input channels in an - NI-DAQmx task. - """ - - def read_int16( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more unscaled 16-bit integer samples from one or - more analog input channels in a task. + """Reads unscaled samples from one or more analog input channels in an NI-DAQmx task.""" + + def read_int16(self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): + """Reads one or more unscaled 16-bit integer samples from one or more analog input channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -77,31 +69,32 @@ def read_int16( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (110 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) _, samps_per_chan_read = self._interpreter.read_binary_i16( - self._handle, number_of_samples_per_channel, - timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read - def read_int32( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more unscaled 32-bit integer samples from one or - more analog input channels in a task. + def read_int32(self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): + """Reads one or more unscaled 32-bit integer samples from one or more analog input channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -162,31 +155,32 @@ def read_int32( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (110 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) _, samps_per_chan_read = self._interpreter.read_binary_i32( - self._handle, number_of_samples_per_channel, - timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read - def read_uint16( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more unscaled 16-bit unsigned integer samples from - one or more analog input channels in a task. + def read_uint16(self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): + """Reads one or more unscaled 16-bit unsigned integer samples from one or more analog input channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -247,31 +241,32 @@ def read_uint16( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (119 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) _, samps_per_chan_read = self._interpreter.read_binary_u16( - self._handle, number_of_samples_per_channel, - timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read - def read_uint32( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more unscaled unsigned 32-bit integer samples from - one or more analog input channels in a task. + def read_uint32(self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): + """Reads one or more unscaled unsigned 32-bit integer samples from one or more analog input channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -332,21 +327,26 @@ def read_uint32( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (119 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) - _, samps_per_chan_read = self._interpreter.read_binary_u32( - self._handle, number_of_samples_per_channel, - timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + _, samps_per_chan_read = self._interpreter.read_binary_u32( + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read diff --git a/generated/nidaqmx/stream_readers/_channel_reader_base.py b/generated/nidaqmx/stream_readers/_channel_reader_base.py index af7a2db02..ba0300bbb 100644 --- a/generated/nidaqmx/stream_readers/_channel_reader_base.py +++ b/generated/nidaqmx/stream_readers/_channel_reader_base.py @@ -1,16 +1,15 @@ from __future__ import annotations from nidaqmx import DaqError - from nidaqmx.error_codes import DAQmxErrors + class ChannelReaderBase: - """ - Defines base class for all NI-DAQmx stream readers. - """ + """Defines base class for all NI-DAQmx stream readers.""" def __init__(self, task_in_stream): - """ + """Initialize a new ChannelReaderBase. + Args: task_in_stream: Specifies the input stream associated with an NI-DAQmx task from which to read samples. @@ -24,13 +23,12 @@ def __init__(self, task_in_stream): @property def verify_array_shape(self): - """ - bool: Indicates whether the size and shape of the user-defined - NumPy arrays passed to read methods are verified. Defaults - to True when this object is instantiated. + """bool: Specifies whether to verify the shape of NumPy arrays. - Setting this property to True may marginally adversely - impact the performance of read methods. + Defaults to True when this object is instantiated. + + Setting this property to True may marginally adversely + impact the performance of read methods. """ return self._verify_array_shape @@ -38,9 +36,9 @@ def verify_array_shape(self): def verify_array_shape(self, val): self._verify_array_shape = val - def _verify_array(self, data, number_of_samples_per_channel, - is_many_chan, is_many_samp): - """ + def _verify_array(self, data, number_of_samples_per_channel, is_many_chan, is_many_samp): + """Verify the shape of a NumPy array. + Verifies that the shape of the specified NumPy array can be used to read multiple samples from the current task which contains one or more channels, if the "verify_array_shape" property is @@ -64,8 +62,7 @@ def _verify_array(self, data, number_of_samples_per_channel, array_shape: tuple[int, ...] | None = None if is_many_chan: if is_many_samp: - array_shape = (number_of_channels, - number_of_samples_per_channel) + array_shape = (number_of_channels, number_of_samples_per_channel) else: array_shape = (number_of_channels,) else: @@ -74,19 +71,20 @@ def _verify_array(self, data, number_of_samples_per_channel, if array_shape is not None and data.shape != array_shape: raise DaqError( - 'Read cannot be performed because the NumPy array passed into ' - 'this function is not shaped correctly. You must pass in a ' - 'NumPy array of the correct shape based on the number of ' - 'channels in task and the number of samples per channel ' - 'requested.\n\n' - 'Shape of NumPy Array provided: {}\n' - 'Shape of NumPy Array required: {}' - .format(data.shape, array_shape), - DAQmxErrors.UNKNOWN, task_name=self._task.name) - - def _verify_array_digital_lines( - self, data, is_many_chan, is_many_line): - """ + "Read cannot be performed because the NumPy array passed into " + "this function is not shaped correctly. You must pass in a " + "NumPy array of the correct shape based on the number of " + "channels in task and the number of samples per channel " + "requested.\n\n" + "Shape of NumPy Array provided: {}\n" + "Shape of NumPy Array required: {}".format(data.shape, array_shape), + DAQmxErrors.UNKNOWN, + task_name=self._task.name, + ) + + def _verify_array_digital_lines(self, data, is_many_chan, is_many_line): + """Verify the shape of a NumPy array of digital lines. + Verifies that the shape of the specified NumPy array can be used to read samples from the current task which contains one or more channels that have one or more digital lines per channel, if the @@ -118,12 +116,13 @@ def _verify_array_digital_lines( if array_shape is not None and data.shape != array_shape: raise DaqError( - 'Read cannot be performed because the NumPy array passed into ' - 'this function is not shaped correctly. You must pass in a ' - 'NumPy array of the correct shape based on the number of ' - 'channels in task and the number of digital lines per ' - 'channel.\n\n' - 'Shape of NumPy Array provided: {}\n' - 'Shape of NumPy Array required: {}' - .format(data.shape, array_shape), - DAQmxErrors.UNKNOWN, task_name=self._task.name) + "Read cannot be performed because the NumPy array passed into " + "this function is not shaped correctly. You must pass in a " + "NumPy array of the correct shape based on the number of " + "channels in task and the number of digital lines per " + "channel.\n\n" + "Shape of NumPy Array provided: {}\n" + "Shape of NumPy Array required: {}".format(data.shape, array_shape), + DAQmxErrors.UNKNOWN, + task_name=self._task.name, + ) diff --git a/generated/nidaqmx/stream_readers/_counter_reader.py b/generated/nidaqmx/stream_readers/_counter_reader.py index f810dc640..67ef1911b 100644 --- a/generated/nidaqmx/stream_readers/_counter_reader.py +++ b/generated/nidaqmx/stream_readers/_counter_reader.py @@ -1,22 +1,17 @@ from __future__ import annotations -from nidaqmx.constants import FillMode, READ_ALL_AVAILABLE -from nidaqmx.types import CtrFreq, CtrTick, CtrTime - +from nidaqmx.constants import READ_ALL_AVAILABLE, FillMode from nidaqmx.stream_readers._channel_reader_base import ChannelReaderBase +from nidaqmx.types import CtrFreq, CtrTick, CtrTime class CounterReader(ChannelReaderBase): - """ - Reads samples from a counter input channel in an NI-DAQmx task. - """ + """Reads samples from a counter input channel in an NI-DAQmx task.""" def read_many_sample_double( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more floating-point samples from a single counter - input channel in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more floating-point samples from a single counter input channel in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -64,6 +59,7 @@ def read_many_sample_double( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: @@ -71,24 +67,30 @@ def read_many_sample_double( NI-DAQmx returns a single value because this value is the same for all channels. """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, False, True) _, samps_per_chan_read = self._interpreter.read_counter_f64_ex( - self._handle,number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_many_sample_pulse_frequency( - self, frequencies, duty_cycles, - number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): - """ - Reads one or more pulse samples in terms of frequency from a - single counter input channel in a task. + self, + frequencies, + duty_cycles, + number_of_samples_per_channel=READ_ALL_AVAILABLE, + timeout=10.0, + ): + """Reads one or more pulse samples in terms of frequency from a single counter input channel in a task. This read method accepts preallocated NumPy arrays to hold the samples requested, which can be advantageous for performance and @@ -144,34 +146,36 @@ def read_many_sample_pulse_frequency( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (111 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) - self._verify_array( - frequencies, number_of_samples_per_channel, False, True) - self._verify_array( - duty_cycles, number_of_samples_per_channel, False, True) + self._verify_array(frequencies, number_of_samples_per_channel, False, True) + self._verify_array(duty_cycles, number_of_samples_per_channel, False, True) _, _, samps_per_chan_read = self._interpreter.read_ctr_freq( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, frequencies, duty_cycles) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + frequencies, + duty_cycles, + ) + return samps_per_chan_read def read_many_sample_pulse_ticks( - self, high_ticks, low_ticks, - number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): - """ - Reads one or more pulse samples in terms of ticks from a single - counter input channel in a task. + self, high_ticks, low_ticks, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more pulse samples in terms of ticks from a single counter input channel in a task. This read method accepts preallocated NumPy arrays to hold the samples requested, which can be advantageous for performance and @@ -227,34 +231,36 @@ def read_many_sample_pulse_ticks( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) - self._verify_array( - high_ticks, number_of_samples_per_channel, False, True) - self._verify_array( - low_ticks, number_of_samples_per_channel, False, True) + self._verify_array(high_ticks, number_of_samples_per_channel, False, True) + self._verify_array(low_ticks, number_of_samples_per_channel, False, True) _, _, samps_per_chan_read = self._interpreter.read_ctr_ticks( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_ticks, low_ticks) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_ticks, + low_ticks, + ) + return samps_per_chan_read def read_many_sample_pulse_time( - self, high_times, low_times, - number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): - """ - Reads one or more pulse samples in terms of time from a single - counter input channel in a task. + self, high_times, low_times, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more pulse samples in terms of time from a single counter input channel in a task. This read method accepts preallocated NumPy arrays to hold the samples requested, which can be advantageous for performance and @@ -310,34 +316,36 @@ def read_many_sample_pulse_time( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (106 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) - self._verify_array( - high_times, number_of_samples_per_channel, False, True) - self._verify_array( - low_times, number_of_samples_per_channel, False, True) + self._verify_array(high_times, number_of_samples_per_channel, False, True) + self._verify_array(low_times, number_of_samples_per_channel, False, True) _, _, samps_per_chan_read = self._interpreter.read_ctr_time( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_times, low_times) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_times, + low_times, + ) + return samps_per_chan_read def read_many_sample_uint32( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more 32-bit unsigned integer samples from a single - counter input channel in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more 32-bit unsigned integer samples from a single counter input channel in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -385,29 +393,32 @@ def read_many_sample_uint32( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, False, True) _, samps_per_chan_read = self._interpreter.read_counter_u32_ex( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_one_sample_double(self, timeout=10): - """ - Reads a single floating-point sample from a single counter input - channel in a task. + """Reads a single floating-point sample from a single counter input channel in a task. Args: timeout (Optional[float]): Specifies the amount of time in @@ -419,6 +430,7 @@ def read_one_sample_double(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: float: Indicates a single floating-point sample from the task. @@ -426,9 +438,7 @@ def read_one_sample_double(self, timeout=10): return self._interpreter.read_counter_scalar_f64(self._handle, timeout) def read_one_sample_pulse_frequency(self, timeout=10): - """ - Reads a pulse sample in terms of frequency from a single counter - input channel in a task. + """Reads a pulse sample in terms of frequency from a single counter input channel in a task. Args: timeout (Optional[float]): Specifies the amount of time in @@ -440,6 +450,7 @@ def read_one_sample_pulse_frequency(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: nidaqmx.types.CtrFreq: @@ -450,9 +461,7 @@ def read_one_sample_pulse_frequency(self, timeout=10): return CtrFreq(freq, duty_cycle) def read_one_sample_pulse_ticks(self, timeout=10): - """ - Reads a pulse sample in terms of ticks from a single counter - input channel in a task. + """Reads a pulse sample in terms of ticks from a single counter input channel in a task. Args: timeout (Optional[float]): Specifies the amount of time in @@ -464,6 +473,7 @@ def read_one_sample_pulse_ticks(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: nidaqmx.types.CtrTick: @@ -474,9 +484,7 @@ def read_one_sample_pulse_ticks(self, timeout=10): return CtrTick(high_ticks, low_ticks) def read_one_sample_pulse_time(self, timeout=10): - """ - Reads a pulse sample in terms of time from a single counter - input channel in a task. + """Reads a pulse sample in terms of time from a single counter input channel in a task. Args: timeout (Optional[float]): Specifies the amount of time in @@ -488,6 +496,7 @@ def read_one_sample_pulse_time(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: nidaqmx.types.CtrTime: @@ -498,9 +507,7 @@ def read_one_sample_pulse_time(self, timeout=10): return CtrTime(high_time, low_time) def read_one_sample_uint32(self, timeout=10): - """ - Reads a single 32-bit unsigned integer sample from a single - counter input channel in a task. + """Reads a single 32-bit unsigned integer sample from a single counter input channel in a task. Args: timeout (Optional[float]): Specifies the amount of time in @@ -512,10 +519,11 @@ def read_one_sample_uint32(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates a single 32-bit unsigned integer sample from the task. - """ + """ # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) return self._interpreter.read_counter_scalar_u32(self._handle, timeout) diff --git a/generated/nidaqmx/stream_readers/_digital_multi_channel_reader.py b/generated/nidaqmx/stream_readers/_digital_multi_channel_reader.py index 68ae512d9..22c8ebd90 100644 --- a/generated/nidaqmx/stream_readers/_digital_multi_channel_reader.py +++ b/generated/nidaqmx/stream_readers/_digital_multi_channel_reader.py @@ -1,28 +1,22 @@ from __future__ import annotations import numpy -from nidaqmx import DaqError +from nitypes.waveform import DigitalWaveform +from nidaqmx import DaqError from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature -from nidaqmx.constants import FillMode, READ_ALL_AVAILABLE, ReallocationPolicy +from nidaqmx.constants import READ_ALL_AVAILABLE, FillMode, ReallocationPolicy from nidaqmx.error_codes import DAQmxErrors -from nitypes.waveform import DigitalWaveform - from nidaqmx.stream_readers._channel_reader_base import ChannelReaderBase class DigitalMultiChannelReader(ChannelReaderBase): - """ - Reads samples from one or more digital input channels in an NI-DAQmx - task. - """ + """Reads samples from one or more digital input channels in an NI-DAQmx task.""" def read_many_sample_port_byte( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more 8-bit unsigned integer samples from one or - more digital input channel in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more 8-bit unsigned integer samples from one or more digital input channel in a task. Use this method for devices with up to 8 lines per port. @@ -85,31 +79,34 @@ def read_many_sample_port_byte( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (109 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) _, samps_per_chan_read = self._interpreter.read_digital_u8( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_many_sample_port_uint16( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more 16-bit unsigned integer samples from one or - more digital input channels in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more 16-bit unsigned integer samples from one or more digital input channels in a task. Use this method for devices with up to 16 lines per port. @@ -172,30 +169,34 @@ def read_many_sample_port_uint16( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (111 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) _, samps_per_chan_read = self._interpreter.read_digital_u16( - self._handle, number_of_samples_per_channel, timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_many_sample_port_uint32( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more 32-bit unsigned integer samples from one or - more digital input channels in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more 32-bit unsigned integer samples from one or more digital input channels in a task. Use this method for devices with up to 32 lines per port. @@ -258,29 +259,34 @@ def read_many_sample_port_uint32( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (111 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) _, samps_per_chan_read = self._interpreter.read_digital_u32( - self._handle, number_of_samples_per_channel, timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_one_sample_multi_line(self, data, timeout=10): - """ - Reads a single boolean sample from one or more digital input - channels in a task. The channels can contain multiple digital - lines. + """Reads a single boolean sample from one or more digital input channels in a task. + + The channels can contain multiple digital lines. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -324,14 +330,14 @@ def read_one_sample_multi_line(self, data, timeout=10): """ self._verify_array_digital_lines(data, True, True) - _, samps_per_chan_read, num_bytes_per_samp= self._interpreter.read_digital_lines( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + _, samps_per_chan_read, num_bytes_per_samp = self._interpreter.read_digital_lines( + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def read_one_sample_one_line(self, data, timeout=10): - """ - Reads a single boolean sample from one or more digital input - channels in a task. The channel can contain only one digital - line. + """Reads a single boolean sample from one or more digital input channels in a task. + + The channel can contain only one digital line. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -361,13 +367,12 @@ def read_one_sample_one_line(self, data, timeout=10): """ self._verify_array_digital_lines(data, True, False) - _, samps_per_chan_read, num_bytes_per_samp= self._interpreter.read_digital_lines( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + _, samps_per_chan_read, num_bytes_per_samp = self._interpreter.read_digital_lines( + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def read_one_sample_port_byte(self, data, timeout=10): - """ - Reads a single 8-bit unsigned integer sample from one or more - digital input channels in a task. + """Reads a single 8-bit unsigned integer sample from one or more digital input channels in a task. Use this method for devices with up to 8 lines per port. @@ -397,16 +402,15 @@ def read_one_sample_port_byte(self, data, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. - """ + """ # noqa: W505 - doc line too long (106 > 100 characters) (auto-generated noqa) self._verify_array(data, 1, True, False) self._interpreter.read_digital_u8( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def read_one_sample_port_uint16(self, data, timeout=10): - """ - Reads a single 16-bit unsigned integer sample from one or more - digital input channels in a task. + """Reads a single 16-bit unsigned integer sample from one or more digital input channels in a task. Use this method for devices with up to 16 lines per port. @@ -436,16 +440,15 @@ def read_one_sample_port_uint16(self, data, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. - """ + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) self._verify_array(data, 1, True, False) self._interpreter.read_digital_u16( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def read_one_sample_port_uint32(self, data, timeout=10): - """ - Reads a single 32-bit unsigned integer sample from one or more - digital input channels in a task. + """Reads a single 32-bit unsigned integer sample from one or more digital input channels in a task. Use this method for devices with up to 32 lines per port. @@ -475,13 +478,13 @@ def read_one_sample_port_uint32(self, data, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. - """ + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) self._verify_array(data, 1, True, False) self._interpreter.read_digital_u32( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) - - + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) + @requires_feature(WAVEFORM_SUPPORT) def read_waveforms( self, @@ -490,15 +493,13 @@ def read_waveforms( reallocation_policy: ReallocationPolicy = ReallocationPolicy.TO_GROW, timeout: int = 10, ) -> list[DigitalWaveform[numpy.uint8]]: - """ - Reads one or more samples from one or more digital - input channels into a list of waveforms. + """Reads one or more samples from one or more digital input channels into a list of waveforms. - Args: + Args: waveforms (list[DigitalWaveform]): Specifies an existing list of DigitalWaveform objects to use for reading samples into. The list must contain one waveform - for each channel in the task. + for each channel in the task. number_of_samples_per_channel (Optional[int]): Specifies the number of samples to read. @@ -530,25 +531,28 @@ def read_waveforms( nidaqmx.constants.WAIT_INFINITELY, the method waits indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error - if it is unable to. + if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ + """ # noqa: W505 - doc line too long (102 > 100 characters) (auto-generated noqa) number_of_channels = self._in_stream.num_chans - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) if len(waveforms) != number_of_channels: raise DaqError( - f'The number of waveforms provided ({len(waveforms)}) does not match ' - f'the number of channels in the task ({number_of_channels}). Please provide ' - 'one waveform for each channel.', - DAQmxErrors.MISMATCHED_INPUT_ARRAY_SIZES, task_name=self._task.name) + f"The number of waveforms provided ({len(waveforms)}) does not match " + f"the number of channels in the task ({number_of_channels}). Please provide " + "one waveform for each channel.", + DAQmxErrors.MISMATCHED_INPUT_ARRAY_SIZES, + task_name=self._task.name, + ) for i, waveform in enumerate(waveforms): if waveform.start_index + number_of_samples_per_channel > waveform.capacity: @@ -556,10 +560,12 @@ def read_waveforms( waveform.capacity = waveform.start_index + number_of_samples_per_channel else: raise DaqError( - f'The waveform at index {i} does not have enough space ({waveform.capacity - waveform.start_index}) to hold ' - f'the requested number of samples ({number_of_samples_per_channel}). Please provide larger ' - 'waveforms or adjust the number of samples requested.', - DAQmxErrors.READ_BUFFER_TOO_SMALL, task_name=self._task.name) + f"The waveform at index {i} does not have enough space ({waveform.capacity - waveform.start_index}) to hold " + f"the requested number of samples ({number_of_samples_per_channel}). Please provide larger " + "waveforms or adjust the number of samples requested.", + DAQmxErrors.READ_BUFFER_TOO_SMALL, + task_name=self._task.name, + ) waveforms = self._interpreter.read_digital_waveforms( self._handle, diff --git a/generated/nidaqmx/stream_readers/_digital_single_channel_reader.py b/generated/nidaqmx/stream_readers/_digital_single_channel_reader.py index 79f2d96fb..12e5fd085 100644 --- a/generated/nidaqmx/stream_readers/_digital_single_channel_reader.py +++ b/generated/nidaqmx/stream_readers/_digital_single_channel_reader.py @@ -1,27 +1,22 @@ from __future__ import annotations import numpy -from nidaqmx import DaqError +from nitypes.waveform import DigitalWaveform +from nidaqmx import DaqError from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature -from nidaqmx.constants import FillMode, READ_ALL_AVAILABLE, ReallocationPolicy +from nidaqmx.constants import READ_ALL_AVAILABLE, FillMode, ReallocationPolicy from nidaqmx.error_codes import DAQmxErrors -from nitypes.waveform import DigitalWaveform - from nidaqmx.stream_readers._channel_reader_base import ChannelReaderBase class DigitalSingleChannelReader(ChannelReaderBase): - """ - Reads samples from a digital input channel in an NI-DAQmx task. - """ + """Reads samples from a digital input channel in an NI-DAQmx task.""" def read_many_sample_port_byte( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more 8-bit unsigned integer samples from a single - digital input channel in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more 8-bit unsigned integer samples from a single digital input channel in a task. Use this method for devices with up to 8 lines per port. @@ -71,31 +66,34 @@ def read_many_sample_port_byte( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (106 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, False, True) _, samps_per_chan_read = self._interpreter.read_digital_u8( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_many_sample_port_uint16( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more 16-bit unsigned integer samples from a single - digital input channel in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more 16-bit unsigned integer samples from a single digital input channel in a task. Use this method for devices with up to 16 lines per port. @@ -145,31 +143,34 @@ def read_many_sample_port_uint16( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, False, True) _, samps_per_chan_read = self._interpreter.read_digital_u16( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_many_sample_port_uint32( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more 32-bit unsigned integer samples from a single - digital input channel in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more 32-bit unsigned integer samples from a single digital input channel in a task. Use this method for devices with up to 32 lines per port. @@ -219,30 +220,34 @@ def read_many_sample_port_uint32( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, False, True) _, samps_per_chan_read = self._interpreter.read_digital_u32( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_one_sample_multi_line(self, data, timeout=10): - """ - Reads a single boolean sample from a single digital input - channel in a task. The channel can contain multiple digital - lines. + """Reads a single boolean sample from a single digital input channel in a task. + + The channel can contain multiple digital lines. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -273,13 +278,13 @@ def read_one_sample_multi_line(self, data, timeout=10): self._verify_array_digital_lines(data, False, True) _, samps_per_chan_read, num_bytes_per_samp = self._interpreter.read_digital_lines( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def read_one_sample_one_line(self, timeout=10): - """ - Reads a single boolean sample from a single digital input - channel in a task. The channel can contain only one digital - line. + """Reads a single boolean sample from a single digital input channel in a task. + + The channel can contain only one digital line. Args: timeout (Optional[float]): Specifies the amount of time in @@ -291,21 +296,21 @@ def read_one_sample_one_line(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: bool: Indicates a single boolean sample from the task. """ data = numpy.zeros(1, dtype=bool) - _, samps_per_chan_read, num_bytes_per_samp= self._interpreter.read_digital_lines( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + _, samps_per_chan_read, num_bytes_per_samp = self._interpreter.read_digital_lines( + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) return bool(data[0]) def read_one_sample_port_byte(self, timeout=10): - """ - Reads a single 8-bit unsigned integer sample from a single - digital input channel in a task. + """Reads a single 8-bit unsigned integer sample from a single digital input channel in a task. Use this method for devices with up to 8 lines per port. @@ -319,22 +324,22 @@ def read_one_sample_port_byte(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates a single 8-bit unsigned integer sample from the task. - """ + """ # noqa: W505 - doc line too long (102 > 100 characters) (auto-generated noqa) data = numpy.zeros(1, dtype=numpy.uint8) _, samps_per_chan_read = self._interpreter.read_digital_u8( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) return int(data[0]) def read_one_sample_port_uint16(self, timeout=10): - """ - Reads a single 16-bit unsigned integer sample from a single - digital input channel in a task. + """Reads a single 16-bit unsigned integer sample from a single digital input channel in a task. Use this method for devices with up to 16 lines per port. @@ -348,22 +353,22 @@ def read_one_sample_port_uint16(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates a single 16-bit unsigned integer sample from the task. - """ + """ # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) data = numpy.zeros(1, dtype=numpy.uint16) _, samps_per_read_chan = self._interpreter.read_digital_u16( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) return int(data[0]) def read_one_sample_port_uint32(self, timeout=10): - """ - Reads a single 32-bit unsigned integer sample from a single - digital input channel in a task. + """Reads a single 32-bit unsigned integer sample from a single digital input channel in a task. Use this method for devices with up to 32 lines per port. @@ -377,12 +382,13 @@ def read_one_sample_port_uint32(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates a single 32-bit unsigned integer sample from the task. - """ + """ # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) return self._interpreter.read_digital_scalar_u32(self._handle, timeout) @requires_feature(WAVEFORM_SUPPORT) @@ -393,14 +399,12 @@ def read_waveform( reallocation_policy: ReallocationPolicy = ReallocationPolicy.TO_GROW, timeout: float = 10.0, ) -> int: - """ - Reads one or more digital samples from a single digital input - channel into a waveform. + """Reads one or more digital samples from a single digital input channel into a waveform. Args: waveform (DigitalWaveform[numpy.uint8]): Specifies a preallocated DigitalWaveform object to hold the samples - requested. + requested. number_of_samples_per_channel (Optional[int]): Specifies the number of samples to read. @@ -433,6 +437,7 @@ def read_waveform( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: @@ -440,24 +445,26 @@ def read_waveform( NI-DAQmx returns a single value because this value is the same for all channels. """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) - + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) + if waveform.start_index + number_of_samples_per_channel > waveform.capacity: if reallocation_policy == ReallocationPolicy.TO_GROW: waveform.capacity = waveform.start_index + number_of_samples_per_channel else: raise DaqError( - f'The waveform does not have enough space ({waveform.capacity - waveform.start_index}) to hold ' - f'the requested number of samples ({number_of_samples_per_channel}). Please ' - 'provide a larger waveform or adjust the number of samples requested.', - DAQmxErrors.READ_BUFFER_TOO_SMALL, task_name=self._task.name) - + f"The waveform does not have enough space ({waveform.capacity - waveform.start_index}) to hold " + f"the requested number of samples ({number_of_samples_per_channel}). Please " + "provide a larger waveform or adjust the number of samples requested.", + DAQmxErrors.READ_BUFFER_TOO_SMALL, + task_name=self._task.name, + ) + return self._interpreter.read_digital_waveform( - self._handle, - number_of_samples_per_channel, - timeout, - waveform, - self._in_stream.waveform_attribute_mode + self._handle, + number_of_samples_per_channel, + timeout, + waveform, + self._in_stream.waveform_attribute_mode, ) diff --git a/generated/nidaqmx/stream_readers/_power_readers.py b/generated/nidaqmx/stream_readers/_power_readers.py index cbb37cc08..a1c6b4324 100644 --- a/generated/nidaqmx/stream_readers/_power_readers.py +++ b/generated/nidaqmx/stream_readers/_power_readers.py @@ -1,22 +1,21 @@ from __future__ import annotations -from nidaqmx.constants import FillMode, READ_ALL_AVAILABLE -from nidaqmx.types import PowerMeasurement - +from nidaqmx.constants import READ_ALL_AVAILABLE, FillMode from nidaqmx.stream_readers._channel_reader_base import ChannelReaderBase +from nidaqmx.types import PowerMeasurement class PowerSingleChannelReader(ChannelReaderBase): - """ - Reads samples from an analog input power channel in an NI-DAQmx task. - """ + """Reads samples from an analog input power channel in an NI-DAQmx task.""" def read_many_sample( - self, voltage_data, current_data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more floating-point power samples from a single analog - input power channel in a task. + self, + voltage_data, + current_data, + number_of_samples_per_channel=READ_ALL_AVAILABLE, + timeout=10.0, + ): + """Reads one or more floating-point power samples from a single analog input power channel in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -72,30 +71,34 @@ def read_many_sample( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (109 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(voltage_data, number_of_samples_per_channel, False, True) self._verify_array(current_data, number_of_samples_per_channel, False, True) _, _, samps_per_chan_read = self._interpreter.read_power_f64( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, voltage_data, current_data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + voltage_data, + current_data, + ) + return samps_per_chan_read def read_one_sample(self, timeout=10): - """ - Reads a single floating-point power sample from a single analog input - power channel in a task. + """Reads a single floating-point power sample from a single analog input power channel in a task. Args: timeout (Optional[float]): Specifies the amount of time in @@ -107,27 +110,27 @@ def read_one_sample(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: float: Indicates a single floating-point power sample from the task. - """ + """ # noqa: W505 - doc line too long (105 > 100 characters) (auto-generated noqa) voltage, current = self._interpreter.read_power_scalar_f64(self._handle, timeout) return PowerMeasurement(voltage=voltage, current=current) class PowerMultiChannelReader(ChannelReaderBase): - """ - Reads samples from one or more analog input power channels in an NI-DAQmx - task. - """ + """Reads samples from one or more analog input power channels in an NI-DAQmx task.""" def read_many_sample( - self, voltage_data, current_data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more floating-point power samples from one or more analog - input power channels in a task. + self, + voltage_data, + current_data, + number_of_samples_per_channel=READ_ALL_AVAILABLE, + timeout=10.0, + ): + """Reads one or more floating-point power samples from one or more analog input power channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -209,30 +212,34 @@ def read_many_sample( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (113 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(voltage_data, number_of_samples_per_channel, True, True) self._verify_array(current_data, number_of_samples_per_channel, True, True) _, _, samps_per_chan_read = self._interpreter.read_power_f64( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, voltage_data, current_data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + voltage_data, + current_data, + ) + return samps_per_chan_read def read_one_sample(self, voltage_data, current_data, timeout=10): - """ - Reads a single floating-point power sample from one or more analog - input channels in a task. + """Reads a single floating-point power sample from one or more analog input channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -268,27 +275,26 @@ def read_one_sample(self, voltage_data, current_data, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. - """ + """ # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) self._verify_array(voltage_data, 1, True, False) self._verify_array(current_data, 1, True, False) self._interpreter.read_power_f64( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, - voltage_data, current_data) + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, voltage_data, current_data + ) class PowerBinaryReader(ChannelReaderBase): - """ - Reads binary samples from one or more analog input power channels in an - NI-DAQmx task. - """ + """Reads binary samples from one or more analog input power channels in an NI-DAQmx task.""" def read_many_sample( - self, voltage_data, current_data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more binary int16 samples from one or more analog - input power channel in a task. + self, + voltage_data, + current_data, + number_of_samples_per_channel=READ_ALL_AVAILABLE, + timeout=10.0, + ): + """Reads one or more binary int16 samples from one or more analog input power channel in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -364,22 +370,28 @@ def read_many_sample( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (104 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(voltage_data, number_of_samples_per_channel, True, True) self._verify_array(current_data, number_of_samples_per_channel, True, True) _, _, samps_per_chan_read = self._interpreter.read_power_binary_i16( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, voltage_data, current_data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + voltage_data, + current_data, + ) + return samps_per_chan_read diff --git a/generated/nidaqmx/stream_writers/__init__.py b/generated/nidaqmx/stream_writers/__init__.py index eb2520747..aeba78e41 100644 --- a/generated/nidaqmx/stream_writers/__init__.py +++ b/generated/nidaqmx/stream_writers/__init__.py @@ -1,25 +1,34 @@ -""" -NI-DAQmx stream writers. +"""NI-DAQmx stream writers. This package provides classes for writing samples to NI-DAQmx tasks. """ from __future__ import annotations -from nidaqmx.stream_writers._analog_single_channel_writer import AnalogSingleChannelWriter from nidaqmx.stream_writers._analog_multi_channel_writer import AnalogMultiChannelWriter +from nidaqmx.stream_writers._analog_single_channel_writer import ( + AnalogSingleChannelWriter, +) from nidaqmx.stream_writers._analog_unscaled_writer import AnalogUnscaledWriter +from nidaqmx.stream_writers._channel_writer_base import ( + AUTO_START_UNSET, + UnsetAutoStartSentinel, +) from nidaqmx.stream_writers._counter_writer import CounterWriter -from nidaqmx.stream_writers._digital_single_channel_writer import DigitalSingleChannelWriter -from nidaqmx.stream_writers._digital_multi_channel_writer import DigitalMultiChannelWriter -from nidaqmx.stream_writers._channel_writer_base import UnsetAutoStartSentinel, AUTO_START_UNSET +from nidaqmx.stream_writers._digital_multi_channel_writer import ( + DigitalMultiChannelWriter, +) +from nidaqmx.stream_writers._digital_single_channel_writer import ( + DigitalSingleChannelWriter, +) __all__ = [ - 'AnalogSingleChannelWriter', - 'AnalogMultiChannelWriter', - 'AnalogUnscaledWriter', - 'CounterWriter', - 'DigitalSingleChannelWriter', - 'DigitalMultiChannelWriter', - 'UnsetAutoStartSentinel', - 'AUTO_START_UNSET'] + "AnalogSingleChannelWriter", + "AnalogMultiChannelWriter", + "AnalogUnscaledWriter", + "CounterWriter", + "DigitalSingleChannelWriter", + "DigitalMultiChannelWriter", + "UnsetAutoStartSentinel", + "AUTO_START_UNSET", +] diff --git a/generated/nidaqmx/stream_writers/_analog_multi_channel_writer.py b/generated/nidaqmx/stream_writers/_analog_multi_channel_writer.py index aa2213e4b..ba1d64e5a 100644 --- a/generated/nidaqmx/stream_writers/_analog_multi_channel_writer.py +++ b/generated/nidaqmx/stream_writers/_analog_multi_channel_writer.py @@ -1,18 +1,15 @@ from nidaqmx.constants import FillMode - -from nidaqmx.stream_writers._channel_writer_base import ChannelWriterBase, AUTO_START_UNSET +from nidaqmx.stream_writers._channel_writer_base import ( + AUTO_START_UNSET, + ChannelWriterBase, +) class AnalogMultiChannelWriter(ChannelWriterBase): - """ - Writes samples to one or more analog output channels in an NI-DAQmx - task. - """ + """Writes samples to one or more analog output channels in an NI-DAQmx task.""" def write_many_sample(self, data, timeout=10.0): - """ - Writes one or more floating-point samples to one or more analog - output channels in a task. + """Writes one or more floating-point samples to one or more analog output channels in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -42,24 +39,23 @@ def write_many_sample(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (101 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_analog_f64( - self._handle, data.shape[1], auto_start, timeout,FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample(self, data, timeout=10): - """ - Writes a single floating-point sample to one or more analog - output channels in a task. + """Writes a single floating-point sample to one or more analog output channels in a task. Args: data (numpy.ndarray): Contains a 1D NumPy array of @@ -82,9 +78,9 @@ def write_one_sample(self, data, timeout=10): and the number of samples successfully written. """ self._verify_array(data, True, False) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True return self._interpreter.write_analog_f64( - self._handle, 1, auto_start, timeout,FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) diff --git a/generated/nidaqmx/stream_writers/_analog_single_channel_writer.py b/generated/nidaqmx/stream_writers/_analog_single_channel_writer.py index ddaf08048..01f9d52bd 100644 --- a/generated/nidaqmx/stream_writers/_analog_single_channel_writer.py +++ b/generated/nidaqmx/stream_writers/_analog_single_channel_writer.py @@ -1,24 +1,22 @@ from __future__ import annotations -import numpy from typing import Any -from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature -from nidaqmx.constants import FillMode from nitypes.waveform import AnalogWaveform -from nidaqmx.stream_writers._channel_writer_base import ChannelWriterBase, AUTO_START_UNSET +from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature +from nidaqmx.constants import FillMode +from nidaqmx.stream_writers._channel_writer_base import ( + AUTO_START_UNSET, + ChannelWriterBase, +) class AnalogSingleChannelWriter(ChannelWriterBase): - """ - Writes samples to an analog output channel in an NI-DAQmx task. - """ + """Writes samples to an analog output channel in an NI-DAQmx task.""" def write_many_sample(self, data, timeout=10.0): - """ - Writes one or more floating-point samples to a single analog - output channel in a task. + """Writes one or more floating-point samples to a single analog output channel in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -44,6 +42,7 @@ def write_many_sample(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: @@ -51,17 +50,15 @@ def write_many_sample(self, data, timeout=10.0): successfully wrote. """ self._verify_array(data, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_analog_f64( - self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample(self, data, timeout=10): - """ - Writes a single floating-point sample to a single analog output - channel in a task. + """Writes a single floating-point sample to a single analog output channel in a task. Args: data (float): Specifies the floating-point sample to write @@ -81,20 +78,13 @@ def write_one_sample(self, data, timeout=10): not write all the submitted samples, it returns an error and the number of samples successfully written. """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - - return self._interpreter.write_analog_scalar_f64( - self._handle, auto_start, timeout, data) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + + return self._interpreter.write_analog_scalar_f64(self._handle, auto_start, timeout, data) @requires_feature(WAVEFORM_SUPPORT) - def write_waveform( - self, - waveform: AnalogWaveform[Any], - timeout: float = 10.0 - ) -> int: - """ - Writes a waveform to a single analog output channel in a task. + def write_waveform(self, waveform: AnalogWaveform[Any], timeout: float = 10.0) -> int: + """Writes a waveform to a single analog output channel in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -119,13 +109,11 @@ def write_waveform( once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote. """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False - return self._interpreter.write_analog_waveform( - self._handle, waveform, auto_start, timeout) - \ No newline at end of file + return self._interpreter.write_analog_waveform(self._handle, waveform, auto_start, timeout) diff --git a/generated/nidaqmx/stream_writers/_analog_unscaled_writer.py b/generated/nidaqmx/stream_writers/_analog_unscaled_writer.py index cc23eac3f..c1762e570 100644 --- a/generated/nidaqmx/stream_writers/_analog_unscaled_writer.py +++ b/generated/nidaqmx/stream_writers/_analog_unscaled_writer.py @@ -1,18 +1,15 @@ from nidaqmx.constants import FillMode - -from nidaqmx.stream_writers._channel_writer_base import ChannelWriterBase, AUTO_START_UNSET +from nidaqmx.stream_writers._channel_writer_base import ( + AUTO_START_UNSET, + ChannelWriterBase, +) class AnalogUnscaledWriter(ChannelWriterBase): - """ - Writes unscaled samples to one or more analog output channels in - an NI-DAQmx task. - """ + """Writes unscaled samples to one or more analog output channels in an NI-DAQmx task.""" def write_int16(self, data, timeout=10.0): - """ - Writes one or more unscaled 16-bit integer samples to one or - more analog output channels in a task. + """Writes one or more unscaled 16-bit integer samples to one or more analog output channels in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -40,24 +37,23 @@ def write_int16(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (110 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_binary_i16( - self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_int32(self, data, timeout=10.0): - """ - Writes one or more unscaled 32-bit integer samples to one or - more analog output channels in a task. + """Writes one or more unscaled 32-bit integer samples to one or more analog output channels in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -85,24 +81,23 @@ def write_int32(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (110 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_binary_i32( - self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_uint16(self, data, timeout=10.0): - """ - Writes one or more unscaled 16-bit unsigned integer samples to - one or more analog output channels in a task. + """Writes one or more unscaled 16-bit unsigned integer samples to one or more analog output channels in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -130,24 +125,23 @@ def write_uint16(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (119 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_binary_u16( - self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_uint32(self, data, timeout=10.0): - """ - Writes one or more unscaled 32-bit unsigned integer samples to - one or more analog output channels in a task. + """Writes one or more unscaled 32-bit unsigned integer samples to one or more analog output channels in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -175,16 +169,17 @@ def write_uint32(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (119 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_binary_u32( - self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) diff --git a/generated/nidaqmx/stream_writers/_channel_writer_base.py b/generated/nidaqmx/stream_writers/_channel_writer_base.py index 965736e5d..f631a220c 100644 --- a/generated/nidaqmx/stream_writers/_channel_writer_base.py +++ b/generated/nidaqmx/stream_writers/_channel_writer_base.py @@ -4,32 +4,33 @@ class UnsetAutoStartSentinel: """Sentinel class for unset auto_start parameter.""" - - def __init__(self): - raise RuntimeError("Cannot instantiate UnsetAutoStartSentinel. Use AUTO_START_UNSET instead.") + + def __init__(self): # noqa: D107 - Missing docstring in __init__ (auto-generated noqa) + raise RuntimeError( + "Cannot instantiate UnsetAutoStartSentinel. Use AUTO_START_UNSET instead." + ) AUTO_START_UNSET = object.__new__(UnsetAutoStartSentinel) class ChannelWriterBase: - """ - Defines base class for all NI-DAQmx stream writers. - """ + """Defines base class for all NI-DAQmx stream writers.""" def __init__(self, task_out_stream, auto_start=AUTO_START_UNSET): - """ + """Initialize a new ChannelWriterBase. + Args: task_out_stream: Specifies the output stream associated with an NI-DAQmx task which to write samples. auto_start (Optional[bool]): Specifies if the write method automatically starts the task if you did not explicitly start it with the DAQmx Start Task method. - - If you do not specify a value for this parameter, + + If you do not specify a value for this parameter, NI-DAQmx determines its value based on the type of write method used. If you use a one sample write method, the - value is True; conversely, if you use a many sample + value is True; conversely, if you use a many sample write method, the value is False. """ self._out_stream = task_out_stream @@ -42,16 +43,13 @@ def __init__(self, task_out_stream, auto_start=AUTO_START_UNSET): @property def auto_start(self): - """ - bool: Specifies if the write method automatically starts the - task if you did not explicitly start it with the DAQmx Start - Task method. - - If you do not specify a value for this parameter, NI-DAQmx - determines its value based on the type of write method used. - If you use a one sample write method, its value is True; - conversely, if you use a many sample write method, its value - is False. + """bool: Specifies whether the write method automatically starts the task, if needed. + + If you do not specify a value for this parameter, NI-DAQmx + determines its value based on the type of write method used. + If you use a one sample write method, its value is True; + conversely, if you use a many sample write method, its value + is False. """ return self._auto_start @@ -65,13 +63,12 @@ def auto_start(self): @property def verify_array_shape(self): - """ - bool: Indicates whether the size and shape of the user-defined - NumPy arrays passed to read methods are verified. Defaults - to True when this object is instantiated. + """bool: Specifies whether to verify the shape of NumPy arrays. + + Defaults to True when this object is instantiated. - Setting this property to True may marginally adversely - impact the performance of read methods. + Setting this property to True may marginally adversely + impact the performance of read methods. """ return self._verify_array_shape @@ -80,7 +77,8 @@ def verify_array_shape(self, val): self._verify_array_shape = val def _verify_array(self, data, is_many_chan, is_many_samp): - """ + """Verifies the shape of a NumPy array. + Verifies that the shape of the specified NumPy array can be used with the specified write method type, if the "verify_array_shape" property is set to True. @@ -106,19 +104,17 @@ def _verify_array(self, data, is_many_chan, is_many_samp): expected_num_dimensions = 1 if data.shape[0] != number_of_channels: - self._task._raise_invalid_write_num_chans_error( - number_of_channels, data.shape[0]) + self._task._raise_invalid_write_num_chans_error(number_of_channels, data.shape[0]) else: if is_many_samp: expected_num_dimensions = 1 if expected_num_dimensions is not None: - self._raise_error_if_invalid_write_dimensions( - expected_num_dimensions, len(data.shape)) + self._raise_error_if_invalid_write_dimensions(expected_num_dimensions, len(data.shape)) + + def _verify_array_digital_lines(self, data, is_many_chan, is_many_line): + """Verify the shape of a NumPy array of digital lines. - def _verify_array_digital_lines( - self, data, is_many_chan, is_many_line): - """ Verifies that the shape of the specified NumPy array can be used to read samples from the current task which contains one or more channels that have one or more digital lines per channel, if the @@ -141,36 +137,36 @@ def _verify_array_digital_lines( expected_num_dimensions = None if is_many_chan: if data.shape[0] != number_of_channels: - self._task._raise_invalid_write_num_chans_error( - number_of_channels, data.shape[0]) + self._task._raise_invalid_write_num_chans_error(number_of_channels, data.shape[0]) if is_many_line: expected_num_dimensions = 2 if data.shape[1] != number_of_lines: - self._task._raise_invalid_num_lines_error( - number_of_lines, data.shape[1]) + self._task._raise_invalid_num_lines_error(number_of_lines, data.shape[1]) else: expected_num_dimensions = 1 else: if is_many_line: expected_num_dimensions = 1 if data.shape[0] != number_of_lines: - self._task._raise_invalid_num_lines_error( - number_of_lines, data.shape[0]) + self._task._raise_invalid_num_lines_error(number_of_lines, data.shape[0]) if expected_num_dimensions is not None: - self._raise_error_if_invalid_write_dimensions( - expected_num_dimensions, len(data.shape)) + self._raise_error_if_invalid_write_dimensions(expected_num_dimensions, len(data.shape)) def _raise_error_if_invalid_write_dimensions( - self, num_dimensions_expected, num_dimensions_in_data): + self, num_dimensions_expected, num_dimensions_in_data + ): if num_dimensions_expected != num_dimensions_in_data: raise DaqError( - 'Write cannot be performed because the NumPy array passed ' - 'into this function is not shaped correctly. ' - 'You must pass in a NumPy array of the correct number of ' - 'dimensions based on the write method you use.\n\n' - 'No. of dimensions of NumPy Array provided: {}\n' - 'No. of dimensions of NumPy Array required: {}' - .format(num_dimensions_in_data, num_dimensions_expected), - DAQmxErrors.UNKNOWN, task_name=self._task.name) + "Write cannot be performed because the NumPy array passed " + "into this function is not shaped correctly. " + "You must pass in a NumPy array of the correct number of " + "dimensions based on the write method you use.\n\n" + "No. of dimensions of NumPy Array provided: {}\n" + "No. of dimensions of NumPy Array required: {}".format( + num_dimensions_in_data, num_dimensions_expected + ), + DAQmxErrors.UNKNOWN, + task_name=self._task.name, + ) diff --git a/generated/nidaqmx/stream_writers/_counter_writer.py b/generated/nidaqmx/stream_writers/_counter_writer.py index d005d1c05..2f8b9028a 100644 --- a/generated/nidaqmx/stream_writers/_counter_writer.py +++ b/generated/nidaqmx/stream_writers/_counter_writer.py @@ -1,18 +1,15 @@ from nidaqmx.constants import FillMode - -from nidaqmx.stream_writers._channel_writer_base import ChannelWriterBase, AUTO_START_UNSET +from nidaqmx.stream_writers._channel_writer_base import ( + AUTO_START_UNSET, + ChannelWriterBase, +) class CounterWriter(ChannelWriterBase): - """ - Writes samples to a counter output channel in an NI-DAQmx task. - """ + """Writes samples to a counter output channel in an NI-DAQmx task.""" - def write_many_sample_pulse_frequency( - self, frequencies, duty_cycles, timeout=10.0): - """ - Writes one or more pulse samples in terms of frequency to a - single counter output channel in a task. + def write_many_sample_pulse_frequency(self, frequencies, duty_cycles, timeout=10.0): + """Writes one or more pulse samples in terms of frequency to a single counter output channel in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -43,27 +40,30 @@ def write_many_sample_pulse_frequency( once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote. - """ + """ # noqa: W505 - doc line too long (111 > 100 characters) (auto-generated noqa) self._verify_array(frequencies, False, True) self._verify_array(duty_cycles, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) - return self._interpreter.write_ctr_freq( - self._handle, frequencies.shape[0], auto_start, timeout, - FillMode.GROUP_BY_CHANNEL.value, frequencies, duty_cycles) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False - def write_many_sample_pulse_ticks( - self, high_ticks, low_ticks, timeout=10.0): - """ - Writes one or more pulse samples in terms of ticks to a single - counter output channel in a task. + return self._interpreter.write_ctr_freq( + self._handle, + frequencies.shape[0], + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + frequencies, + duty_cycles, + ) + + def write_many_sample_pulse_ticks(self, high_ticks, low_ticks, timeout=10.0): + """Writes one or more pulse samples in terms of ticks to a single counter output channel in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -94,27 +94,30 @@ def write_many_sample_pulse_ticks( once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote. - """ + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) self._verify_array(high_ticks, False, True) self._verify_array(low_ticks, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) - return self._interpreter.write_ctr_ticks( - self._handle, high_ticks.shape[0], auto_start, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_ticks, low_ticks) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False - def write_many_sample_pulse_time( - self, high_times, low_times, timeout=10.0): - """ - Writes one or more pulse samples in terms of time to a single - counter output channel in a task. + return self._interpreter.write_ctr_ticks( + self._handle, + high_ticks.shape[0], + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_ticks, + low_ticks, + ) + + def write_many_sample_pulse_time(self, high_times, low_times, timeout=10.0): + """Writes one or more pulse samples in terms of time to a single counter output channel in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -145,27 +148,30 @@ def write_many_sample_pulse_time( once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote. - """ + """ # noqa: W505 - doc line too long (106 > 100 characters) (auto-generated noqa) self._verify_array(high_times, False, True) self._verify_array(low_times, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) - return self._interpreter.write_ctr_time( - self._handle, high_times.shape[0], auto_start, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_times, low_times) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False - def write_one_sample_pulse_frequency( - self, frequency, duty_cycle, timeout=10): - """ - Writes a new pulse frequency and duty cycle to a single counter - output channel in a task. + return self._interpreter.write_ctr_time( + self._handle, + high_times.shape[0], + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_times, + low_times, + ) + + def write_one_sample_pulse_frequency(self, frequency, duty_cycle, timeout=10): + """Writes a new pulse frequency and duty cycle to a single counter output channel in a task. Args: frequency (float): Specifies at what frequency to generate @@ -189,17 +195,14 @@ def write_one_sample_pulse_frequency( not write all the submitted samples, it returns an error and the number of samples successfully written. """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + return self._interpreter.write_ctr_freq_scalar( - self._handle, auto_start, timeout, frequency, duty_cycle) + self._handle, auto_start, timeout, frequency, duty_cycle + ) - def write_one_sample_pulse_ticks( - self, high_ticks, low_ticks, timeout=10): - """ - Writes a new pulse high tick count and low tick count to a - single counter output channel in a task. + def write_one_sample_pulse_ticks(self, high_ticks, low_ticks, timeout=10): + """Writes a new pulse high tick count and low tick count to a single counter output channel in a task. Args: high_ticks (float): Specifies the number of ticks the pulse @@ -217,18 +220,15 @@ def write_one_sample_pulse_ticks( once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. - """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - + """ # noqa: W505 - doc line too long (110 > 100 characters) (auto-generated noqa) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + return self._interpreter.write_ctr_ticks_scalar( - self._handle, auto_start, timeout, high_ticks, low_ticks) + self._handle, auto_start, timeout, high_ticks, low_ticks + ) - def write_one_sample_pulse_time( - self, high_time, low_time, timeout=10): - """ - Writes a new pulse high time and low time to a single counter - output channel in a task. + def write_one_sample_pulse_time(self, high_time, low_time, timeout=10): + """Writes a new pulse high time and low time to a single counter output channel in a task. Args: high_time (float): Specifies the amount of time the pulse @@ -247,8 +247,8 @@ def write_one_sample_pulse_time( not write all the submitted samples, it returns an error and the number of samples successfully written. """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + return self._interpreter.write_ctr_time_scalar( - self._handle, auto_start, timeout, high_time, low_time) + self._handle, auto_start, timeout, high_time, low_time + ) diff --git a/generated/nidaqmx/stream_writers/_digital_multi_channel_writer.py b/generated/nidaqmx/stream_writers/_digital_multi_channel_writer.py index 58981a8ef..2875beec1 100644 --- a/generated/nidaqmx/stream_writers/_digital_multi_channel_writer.py +++ b/generated/nidaqmx/stream_writers/_digital_multi_channel_writer.py @@ -1,18 +1,15 @@ from nidaqmx.constants import FillMode - -from nidaqmx.stream_writers._channel_writer_base import ChannelWriterBase, AUTO_START_UNSET +from nidaqmx.stream_writers._channel_writer_base import ( + AUTO_START_UNSET, + ChannelWriterBase, +) class DigitalMultiChannelWriter(ChannelWriterBase): - """ - Writes samples to one or more digital output channels in an NI-DAQmx - task. - """ + """Writes samples to one or more digital output channels in an NI-DAQmx task.""" def write_many_sample_port_byte(self, data, timeout=10.0): - """ - Writes one or more 8-bit unsigned integer samples to one or more - digital output channels in a task. + """Writes one or more 8-bit unsigned integer samples to one or more digital output channels in a task. Use this method for devices with up to 8 lines per port. @@ -44,24 +41,23 @@ def write_many_sample_port_byte(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (110 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_digital_u8( - self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_many_sample_port_uint16(self, data, timeout=10.0): - """ - Writes one or more 16-bit unsigned integer samples to one or - more digital output channels in a task. + """Writes one or more 16-bit unsigned integer samples to one or more digital output channels in a task. Use this method for devices with up to 16 lines per port. @@ -93,24 +89,23 @@ def write_many_sample_port_uint16(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (111 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_digital_u16( - self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_many_sample_port_uint32(self, data, timeout=10.0): - """ - Writes one or more 32-bit unsigned integer samples to one or - more digital output channels in a task. + """Writes one or more 32-bit unsigned integer samples to one or more digital output channels in a task. Use this method for devices with up to 32 lines per port. @@ -142,25 +137,25 @@ def write_many_sample_port_uint32(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (111 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_digital_u32( - self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample_multi_line(self, data, timeout=10): - """ - Writes a single boolean sample to one or more digital output - channels in a task. The channel can contain multiple digital - lines. + """Writes a single boolean sample to one or more digital output channels in a task. + + The channel can contain multiple digital lines. Args: data (numpy.ndarray): Contains a 2D NumPy array of boolean @@ -183,18 +178,17 @@ def write_one_sample_multi_line(self, data, timeout=10): and the number of samples successfully written. """ self._verify_array_digital_lines(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True return self._interpreter.write_digital_lines( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample_one_line(self, data, timeout=10): - """ - Writes a single boolean sample to one or more digital output - channels in a task. The channel can contain only one digital - line. + """Writes a single boolean sample to one or more digital output channels in a task. + + The channel can contain only one digital line. Args: data (numpy.ndarray): Contains a 1D NumPy array of boolean @@ -217,17 +211,15 @@ def write_one_sample_one_line(self, data, timeout=10): and the number of samples successfully written. """ self._verify_array_digital_lines(data, True, False) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True return self._interpreter.write_digital_lines( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample_port_byte(self, data, timeout=10): - """ - Writes a single 8-bit unsigned integer sample to one or more - digital output channels in a task. + """Writes a single 8-bit unsigned integer sample to one or more digital output channels in a task. Use this method for devices with up to 8 lines per port. @@ -250,19 +242,17 @@ def write_one_sample_port_byte(self, data, timeout=10): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. - """ + """ # noqa: W505 - doc line too long (106 > 100 characters) (auto-generated noqa) self._verify_array(data, True, False) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True return self._interpreter.write_digital_u8( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample_port_uint16(self, data, timeout=10): - """ - Writes a single 16-bit unsigned integer sample to one or more - digital output channels in a task. + """Writes a single 16-bit unsigned integer sample to one or more digital output channels in a task. Use this method for devices with up to 16 lines per port. @@ -285,19 +275,17 @@ def write_one_sample_port_uint16(self, data, timeout=10): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. - """ + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) self._verify_array(data, True, False) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True return self._interpreter.write_digital_u16( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample_port_uint32(self, data, timeout=10): - """ - Writes a single 32-bit unsigned integer sample to one or more - digital output channels in a task. + """Writes a single 32-bit unsigned integer sample to one or more digital output channels in a task. Use this method for devices with up to 32 lines per port. @@ -320,11 +308,11 @@ def write_one_sample_port_uint32(self, data, timeout=10): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. - """ + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) self._verify_array(data, True, False) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True return self._interpreter.write_digital_u32( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) diff --git a/generated/nidaqmx/stream_writers/_digital_single_channel_writer.py b/generated/nidaqmx/stream_writers/_digital_single_channel_writer.py index c1c731858..6f5dbb485 100644 --- a/generated/nidaqmx/stream_writers/_digital_single_channel_writer.py +++ b/generated/nidaqmx/stream_writers/_digital_single_channel_writer.py @@ -1,20 +1,17 @@ import numpy from nidaqmx.constants import FillMode - -from nidaqmx.stream_writers._channel_writer_base import ChannelWriterBase, AUTO_START_UNSET +from nidaqmx.stream_writers._channel_writer_base import ( + AUTO_START_UNSET, + ChannelWriterBase, +) class DigitalSingleChannelWriter(ChannelWriterBase): - """ - Writes samples to a single digital output channel in an NI-DAQmx - task. - """ + """Writes samples to a single digital output channel in an NI-DAQmx task.""" def write_many_sample_port_byte(self, data, timeout=10.0): - """ - Writes one or more 8-bit unsigned integer samples to a single - digital output channel in a task. + """Writes one or more 8-bit unsigned integer samples to a single digital output channel in a task. Use this method for devices with up to 8 lines per port. @@ -42,24 +39,23 @@ def write_many_sample_port_byte(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote. - """ + """ # noqa: W505 - doc line too long (106 > 100 characters) (auto-generated noqa) self._verify_array(data, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_digital_u8( - self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_many_sample_port_uint16(self, data, timeout=10.0): - """ - Writes one or more 16-bit unsigned integer samples to a single - digital output channel in a task. + """Writes one or more 16-bit unsigned integer samples to a single digital output channel in a task. Use this method for devices with up to 16 lines per port. @@ -87,24 +83,23 @@ def write_many_sample_port_uint16(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote. - """ + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) self._verify_array(data, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_digital_u16( - self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_many_sample_port_uint32(self, data, timeout=10.0): - """ - Writes one or more 32-bit unsigned integer samples to a single - digital output channel in a task. + """Writes one or more 32-bit unsigned integer samples to a single digital output channel in a task. Use this method for devices with up to 32 lines per port. @@ -132,25 +127,25 @@ def write_many_sample_port_uint32(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote. - """ + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) self._verify_array(data, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_digital_u32( - self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample_multi_line(self, data, timeout=10): - """ - Writes a single boolean sample to a single digital output - channel in a task. The channel can contain multiple digital - lines. + """Writes a single boolean sample to a single digital output channel in a task. + + The channel can contain multiple digital lines. Args: data (numpy.ndarray): Contains a 1D NumPy array of boolean @@ -169,18 +164,17 @@ def write_one_sample_multi_line(self, data, timeout=10): and the number of samples successfully written. """ self._verify_array_digital_lines(data, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True return self._interpreter.write_digital_lines( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample_one_line(self, data, timeout=10): - """ - Writes a single boolean sample to a single digital output - channel in a task. The channel can contain only one digital - line. + """Writes a single boolean sample to a single digital output channel in a task. + + The channel can contain only one digital line. Args: data (int): Specifies the boolean sample to write to the @@ -197,18 +191,16 @@ def write_one_sample_one_line(self, data, timeout=10): not write all the submitted samples, it returns an error and the number of samples successfully written. """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + numpy_array = numpy.asarray([data], dtype=bool) return self._interpreter.write_digital_lines( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, numpy_array) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, numpy_array + ) def write_one_sample_port_byte(self, data, timeout=10): - """ - Writes a single 8-bit unsigned integer sample to a single - digital output channel in a task. + """Writes a single 8-bit unsigned integer sample to a single digital output channel in a task. Use this method for devices with up to 8 lines per port. @@ -226,19 +218,17 @@ def write_one_sample_port_byte(self, data, timeout=10): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. - """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - + """ # noqa: W505 - doc line too long (102 > 100 characters) (auto-generated noqa) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + numpy_array = numpy.asarray([data], dtype=numpy.uint8) return self._interpreter.write_digital_u8( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, numpy_array) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, numpy_array + ) def write_one_sample_port_uint16(self, data, timeout=10): - """ - Writes a single 16-bit unsigned integer sample to a single - digital output channel in a task. + """Writes a single 16-bit unsigned integer sample to a single digital output channel in a task. Use this method for devices with up to 16 lines per port. @@ -256,19 +246,17 @@ def write_one_sample_port_uint16(self, data, timeout=10): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. - """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - + """ # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + numpy_array = numpy.asarray([data], dtype=numpy.uint16) return self._interpreter.write_digital_u16( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, numpy_array) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, numpy_array + ) def write_one_sample_port_uint32(self, data, timeout=10): - """ - Writes a single 32-bit unsigned integer sample to a single - digital output channel in a task. + """Writes a single 32-bit unsigned integer sample to a single digital output channel in a task. Use this method for devices with up to 32 lines per port. @@ -286,9 +274,7 @@ def write_one_sample_port_uint32(self, data, timeout=10): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. - """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - - return self._interpreter.write_digital_scalar_u32( - self._handle, auto_start, timeout, data) + """ # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + + return self._interpreter.write_digital_scalar_u32(self._handle, auto_start, timeout, data) diff --git a/generated/nidaqmx/system/__init__.py b/generated/nidaqmx/system/__init__.py index 6d57599ca..cbcc8f80f 100644 --- a/generated/nidaqmx/system/__init__.py +++ b/generated/nidaqmx/system/__init__.py @@ -1,9 +1,19 @@ -from nidaqmx.system.system import ( - System, AOPowerUpState, CDAQSyncConnection, DOPowerUpState, - DOResistorPowerUpState) +"""NI-DAQmx system classes.""" + from nidaqmx.system.device import Device from nidaqmx.system.physical_channel import PhysicalChannel +from nidaqmx.system.system import ( + AOPowerUpState, + CDAQSyncConnection, + DOPowerUpState, + DOResistorPowerUpState, + System, +) from nidaqmx.system.watchdog import ( - WatchdogTask, AOExpirationState, COExpirationState, DOExpirationState) + AOExpirationState, + COExpirationState, + DOExpirationState, + WatchdogTask, +) -__all__ = ['system', 'device', 'physical_channel', 'storage', 'watchdog'] +__all__ = ["system", "device", "physical_channel", "storage", "watchdog"] diff --git a/generated/nidaqmx/system/_collections/device_collection.py b/generated/nidaqmx/system/_collections/device_collection.py index 01262ee32..e1f13a38f 100644 --- a/generated/nidaqmx/system/_collections/device_collection.py +++ b/generated/nidaqmx/system/_collections/device_collection.py @@ -1,24 +1,24 @@ from collections.abc import Sequence -from nidaqmx.errors import DaqError from nidaqmx.error_codes import DAQmxErrors +from nidaqmx.errors import DaqError from nidaqmx.system.device import Device, _DeviceAlternateConstructor from nidaqmx.utils import unflatten_channel_string class DeviceCollection(Sequence): - """ - Contains the collection of devices for a DAQmx system. - + """Contains the collection of devices for a DAQmx system. + This class defines methods that implements a container object. """ + def __init__(self, interpreter): - """ - Do not construct this object directly; instead, call nidaqmx.system.System.local().devices. - """ + """Do not construct this object directly; instead, call nidaqmx.system.System.local().devices.""" # noqa: W505 - doc line too long (105 > 100 characters) (auto-generated noqa) self._interpreter = interpreter - - def __contains__(self, item): + + def __contains__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, item + ): device_names = self.device_names if isinstance(item, str): @@ -28,14 +28,13 @@ def __contains__(self, item): return item.name in device_names return False - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return True return False def __getitem__(self, index): - """ - Indexes a subset of devices on this device collection. + """Indexes a subset of devices on this device collection. Args: index: The value of the index. The following index types are @@ -48,15 +47,19 @@ def __getitem__(self, index): - int: Index/position of the device in the collection. - slice: Range of the indexes/positions of devices in the collection. + Returns: - List[nidaqmx.system.device.Device]: - + List[nidaqmx.system.device.Device]: + Indicates the subset of devices indexed. """ if isinstance(index, int): return _DeviceAlternateConstructor(self.device_names[index], self._interpreter) elif isinstance(index, slice): - return [_DeviceAlternateConstructor(name, self._interpreter) for name in self.device_names[index]] + return [ + _DeviceAlternateConstructor(name, self._interpreter) + for name in self.device_names[index] + ] elif isinstance(index, str): device_names = unflatten_channel_string(index) if len(device_names) == 1: @@ -64,20 +67,21 @@ def __getitem__(self, index): return [_DeviceAlternateConstructor(name, self._interpreter) for name in device_names] else: raise DaqError( - 'Invalid index type "{}" used to access collection.' - .format(type(index)), DAQmxErrors.UNKNOWN) + 'Invalid index type "{}" used to access collection.'.format(type(index)), + DAQmxErrors.UNKNOWN, + ) - def __iter__(self): + def __iter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) for device_name in self.device_names: yield _DeviceAlternateConstructor(device_name, self._interpreter) - def __len__(self): + def __len__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return len(self.device_names) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __reversed__(self): + def __reversed__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) device_names = self.device_names device_names.reverse() @@ -86,9 +90,6 @@ def __reversed__(self): @property def device_names(self): - """ - List[str]: Indicates the names of all devices on this device - collection. - """ - val = self._interpreter.get_system_info_attribute_string(0x193b) + """List[str]: Indicates the names of all devices on this device collection.""" + val = self._interpreter.get_system_info_attribute_string(0x193B) return unflatten_channel_string(val) diff --git a/generated/nidaqmx/system/_collections/persisted_channel_collection.py b/generated/nidaqmx/system/_collections/persisted_channel_collection.py index d389a5f84..06c0910e3 100644 --- a/generated/nidaqmx/system/_collections/persisted_channel_collection.py +++ b/generated/nidaqmx/system/_collections/persisted_channel_collection.py @@ -1,23 +1,27 @@ from collections.abc import Sequence -from nidaqmx.errors import DaqError from nidaqmx.error_codes import DAQmxErrors -from nidaqmx.system.storage.persisted_channel import PersistedChannel, _PersistedChannelAlternateConstructor +from nidaqmx.errors import DaqError +from nidaqmx.system.storage.persisted_channel import ( + PersistedChannel, + _PersistedChannelAlternateConstructor, +) from nidaqmx.utils import unflatten_channel_string + class PersistedChannelCollection(Sequence): - """ - Contains the collection of global channels for a DAQmx system. - + """Contains the collection of global channels for a DAQmx system. + This class defines methods that implements a container object. """ + def __init__(self, interpreter): - """ - Do not construct this object directly; instead, call nidaqmx.system.System.local().global_channels. - """ + """Do not construct this object directly; instead, call nidaqmx.system.System.local().global_channels.""" # noqa: W505 - doc line too long (113 > 100 characters) (auto-generated noqa) self._interpreter = interpreter - - def __contains__(self, item): + + def __contains__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, item + ): channel_names = self.global_channel_names if isinstance(item, str): @@ -26,15 +30,13 @@ def __contains__(self, item): elif isinstance(item, PersistedChannel): return item._name in channel_names - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return True return False def __getitem__(self, index): - """ - Indexes a subset of global channels on this global channel - collection. + """Indexes a subset of global channels on this global channel collection. Args: index: The value of the index. The following index types @@ -48,37 +50,45 @@ def __getitem__(self, index): collection. - slice: Range of the indexes/positions of global channels in the collection. + Returns: List[nidaqmx.system.storage.persisted_channel.PersistedChannel]: - + Indicates the of global channels indexed. """ if isinstance(index, int): - return _PersistedChannelAlternateConstructor(self.global_channel_names[index], self._interpreter) + return _PersistedChannelAlternateConstructor( + self.global_channel_names[index], self._interpreter + ) elif isinstance(index, slice): - return [_PersistedChannelAlternateConstructor(name, self._interpreter) for name in - self.global_channel_names[index]] + return [ + _PersistedChannelAlternateConstructor(name, self._interpreter) + for name in self.global_channel_names[index] + ] elif isinstance(index, str): names = unflatten_channel_string(index) if len(names) == 1: return _PersistedChannelAlternateConstructor(names[0], self._interpreter) - return [_PersistedChannelAlternateConstructor(name, self._interpreter) for name in names] + return [ + _PersistedChannelAlternateConstructor(name, self._interpreter) for name in names + ] else: raise DaqError( - 'Invalid index type "{}" used to access collection.' - .format(type(index)), DAQmxErrors.UNKNOWN) + 'Invalid index type "{}" used to access collection.'.format(type(index)), + DAQmxErrors.UNKNOWN, + ) - def __iter__(self): + def __iter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) for channel_name in self.global_channel_names: yield _PersistedChannelAlternateConstructor(channel_name, self._interpreter) - def __len__(self): + def __len__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return len(self.global_channel_names) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __reversed__(self): + def __reversed__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) channel_names = self.global_channel_names channel_names.reverse() @@ -87,9 +97,6 @@ def __reversed__(self): @property def global_channel_names(self): - """ - List[str]: The names of all the global channels on this - collection. - """ + """List[str]: The names of all the global channels on this collection.""" val = self._interpreter.get_system_info_attribute_string(0x1265) return unflatten_channel_string(val) diff --git a/generated/nidaqmx/system/_collections/persisted_scale_collection.py b/generated/nidaqmx/system/_collections/persisted_scale_collection.py index bdbcc5adb..dc1785c06 100644 --- a/generated/nidaqmx/system/_collections/persisted_scale_collection.py +++ b/generated/nidaqmx/system/_collections/persisted_scale_collection.py @@ -1,23 +1,27 @@ from collections.abc import Sequence -from nidaqmx.errors import DaqError from nidaqmx.error_codes import DAQmxErrors -from nidaqmx.system.storage.persisted_scale import PersistedScale, _PersistedScaleAlternateConstructor +from nidaqmx.errors import DaqError +from nidaqmx.system.storage.persisted_scale import ( + PersistedScale, + _PersistedScaleAlternateConstructor, +) from nidaqmx.utils import unflatten_channel_string + class PersistedScaleCollection(Sequence): - """ - Contains the collection of custom scales on a DAQmx system. - + """Contains the collection of custom scales on a DAQmx system. + This class defines methods that implements a container object. """ + def __init__(self, interpreter): - """ - Do not construct this object directly; instead, call nidaqmx.system.System.local().scales. - """ + """Do not construct this object directly; instead, call nidaqmx.system.System.local().scales.""" # noqa: W505 - doc line too long (104 > 100 characters) (auto-generated noqa) self._interpreter = interpreter - - def __contains__(self, item): + + def __contains__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, item + ): scale_names = self.scale_names if isinstance(item, str): @@ -26,14 +30,13 @@ def __contains__(self, item): elif isinstance(item, PersistedScale): return item._name in scale_names - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return True return False def __getitem__(self, index): - """ - Indexes a subset of custom scales on this collection. + """Indexes a subset of custom scales on this collection. Args: index: The value of the index. The following index types @@ -47,16 +50,19 @@ def __getitem__(self, index): collection. - slice: Range of the indexes/positions of custom scales in the collection. + Returns: List[nidaqmx.system.storage.persisted_scale.PersistedScale]: - + Indicates the subset of custom scales indexed. """ if isinstance(index, int): return _PersistedScaleAlternateConstructor(self.scale_names[index], self._interpreter) elif isinstance(index, slice): - return [_PersistedScaleAlternateConstructor(name, self._interpreter) for name in - self.scale_names[index]] + return [ + _PersistedScaleAlternateConstructor(name, self._interpreter) + for name in self.scale_names[index] + ] elif isinstance(index, str): names = unflatten_channel_string(index) if len(names) == 1: @@ -64,20 +70,21 @@ def __getitem__(self, index): return [_PersistedScaleAlternateConstructor(name, self._interpreter) for name in names] else: raise DaqError( - 'Invalid index type "{}" used to access collection.' - .format(type(index)), DAQmxErrors.UNKNOWN) + 'Invalid index type "{}" used to access collection.'.format(type(index)), + DAQmxErrors.UNKNOWN, + ) - def __iter__(self): + def __iter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) for scale_name in self.scale_names: yield _PersistedScaleAlternateConstructor(scale_name, self._interpreter) - def __len__(self): + def __len__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return len(self.scale_names) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __reversed__(self): + def __reversed__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) scale_names = self.scale_names scale_names.reverse() @@ -86,9 +93,6 @@ def __reversed__(self): @property def scale_names(self): - """ - List[str]: Indicates the names of all the custom scales on this - collection. - """ + """List[str]: Indicates the names of all the custom scales on this collection.""" val = self._interpreter.get_system_info_attribute_string(0x1266) return unflatten_channel_string(val) diff --git a/generated/nidaqmx/system/_collections/persisted_task_collection.py b/generated/nidaqmx/system/_collections/persisted_task_collection.py index 5d0adea4c..43b1a01e2 100644 --- a/generated/nidaqmx/system/_collections/persisted_task_collection.py +++ b/generated/nidaqmx/system/_collections/persisted_task_collection.py @@ -1,23 +1,27 @@ from collections.abc import Sequence -from nidaqmx.errors import DaqError from nidaqmx.error_codes import DAQmxErrors -from nidaqmx.system.storage.persisted_task import PersistedTask, _PersistedTaskAlternateConstructor +from nidaqmx.errors import DaqError +from nidaqmx.system.storage.persisted_task import ( + PersistedTask, + _PersistedTaskAlternateConstructor, +) from nidaqmx.utils import unflatten_channel_string + class PersistedTaskCollection(Sequence): - """ - Contains the collection of task saved on a DAQmx system. - + """Contains the collection of task saved on a DAQmx system. + This class defines methods that implements a container object. """ + def __init__(self, interpreter): - """ - Do not construct this object directly; instead, call nidaqmx.system.System.local().tasks. - """ + """Do not construct this object directly; instead, call nidaqmx.system.System.local().tasks.""" # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) self._interpreter = interpreter - - def __contains__(self, item): + + def __contains__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, item + ): task_names = self.task_names if isinstance(item, str): @@ -26,14 +30,13 @@ def __contains__(self, item): elif isinstance(item, PersistedTask): return item._name in task_names - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return True return False def __getitem__(self, index): - """ - Indexes a subset of saved tasks on this collection. + """Indexes a subset of saved tasks on this collection. Args: index: The value of the index. The following index types @@ -47,16 +50,19 @@ def __getitem__(self, index): collection. - slice: Range of the indexes/positions of saved tasks in the collection. + Returns: List[nidaqmx.system.storage.persisted_task.PersistedTask]: - + Indicates the subset of saved tasks indexed. """ if isinstance(index, int): return _PersistedTaskAlternateConstructor(self.task_names[index], self._interpreter) elif isinstance(index, slice): - return [_PersistedTaskAlternateConstructor(name, self._interpreter) for name in - self.task_names[index]] + return [ + _PersistedTaskAlternateConstructor(name, self._interpreter) + for name in self.task_names[index] + ] elif isinstance(index, str): names = unflatten_channel_string(index) if len(names) == 1: @@ -64,20 +70,21 @@ def __getitem__(self, index): return [_PersistedTaskAlternateConstructor(name, self._interpreter) for name in names] else: raise DaqError( - 'Invalid index type "{}" used to access collection.' - .format(type(index)), DAQmxErrors.UNKNOWN) + 'Invalid index type "{}" used to access collection.'.format(type(index)), + DAQmxErrors.UNKNOWN, + ) - def __iter__(self): + def __iter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) for task_name in self.task_names: yield _PersistedTaskAlternateConstructor(task_name, self._interpreter) - def __len__(self): + def __len__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return len(self.task_names) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __reversed__(self): + def __reversed__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) task_names = self.task_names task_names.reverse() @@ -86,8 +93,6 @@ def __reversed__(self): @property def task_names(self): - """ - List[str]: Indicates the names of all the tasks on this collection. - """ + """List[str]: Indicates the names of all the tasks on this collection.""" val = self._interpreter.get_system_info_attribute_string(0x1267) return unflatten_channel_string(val) diff --git a/generated/nidaqmx/system/_collections/physical_channel_collection.py b/generated/nidaqmx/system/_collections/physical_channel_collection.py index 7eff2e40e..5248e15c9 100644 --- a/generated/nidaqmx/system/_collections/physical_channel_collection.py +++ b/generated/nidaqmx/system/_collections/physical_channel_collection.py @@ -1,24 +1,28 @@ from collections.abc import Sequence -from nidaqmx.errors import DaqError from nidaqmx.error_codes import DAQmxErrors -from nidaqmx.system.physical_channel import PhysicalChannel, _PhysicalChannelAlternateConstructor -from nidaqmx.utils import unflatten_channel_string, flatten_channel_string +from nidaqmx.errors import DaqError +from nidaqmx.system.physical_channel import ( + PhysicalChannel, + _PhysicalChannelAlternateConstructor, +) +from nidaqmx.utils import flatten_channel_string, unflatten_channel_string + class PhysicalChannelCollection(Sequence): - """ - Contains the collection of physical channels for a DAQmx device. - + """Contains the collection of physical channels for a DAQmx device. + This class defines methods that implements a container object. """ + def __init__(self, device_name, interpreter): - """ - Do not construct this object directly; instead, construct a nidaqmx.system.Device and use the appropriate property, such as device.ai_physical_channels. - """ + """Do not construct this object directly; instead, construct a nidaqmx.system.Device and use the appropriate property, such as device.ai_physical_channels.""" # noqa: W505 - doc line too long (166 > 100 characters) (auto-generated noqa) self._name = device_name self._interpreter = interpreter - def __contains__(self, item): + def __contains__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, item + ): channel_names = self.channel_names if isinstance(item, str): @@ -28,15 +32,13 @@ def __contains__(self, item): return item._name in channel_names return False - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return self._name == other._name return False def __getitem__(self, index): - """ - Indexes a subset of physical channels on this physical channel - collection. + """Indexes a subset of physical channels on this physical channel collection. Args: index: The value of the index. The following index types @@ -51,45 +53,55 @@ def __getitem__(self, index): collection. - slice: Range of the indexes/positions of physical channels in the collection. + Returns: - nidaqmx.system.physical_channel.PhysicalChannel: - + nidaqmx.system.physical_channel.PhysicalChannel: + Indicates the subset of physical channels indexed. """ if isinstance(index, int): - return _PhysicalChannelAlternateConstructor(self.channel_names[index], self._interpreter) + return _PhysicalChannelAlternateConstructor( + self.channel_names[index], self._interpreter + ) elif isinstance(index, slice): - return [_PhysicalChannelAlternateConstructor(channel, self._interpreter) for channel in self.channel_names[index]] + return [ + _PhysicalChannelAlternateConstructor(channel, self._interpreter) + for channel in self.channel_names[index] + ] elif isinstance(index, str): requested_channels = unflatten_channel_string(index) - # Ensure the channel names are fully qualified. If the channel is invalid, the user will get errors from the + # Ensure the channel names are fully qualified. If the channel is invalid, the user will get errors from the # noqa: W505 - doc line too long (120 > 100 characters) (auto-generated noqa) # channel objects on use. channels_to_use = [] for channel in requested_channels: if channel.startswith(f"{self._name}/"): channels_to_use.append(channel) else: - channels_to_use.append(f'{self._name}/{channel}') + channels_to_use.append(f"{self._name}/{channel}") if len(channels_to_use) == 1: return _PhysicalChannelAlternateConstructor(channels_to_use[0], self._interpreter) - return [_PhysicalChannelAlternateConstructor(channel, self._interpreter) for channel in channels_to_use] + return [ + _PhysicalChannelAlternateConstructor(channel, self._interpreter) + for channel in channels_to_use + ] else: raise DaqError( - 'Invalid index type "{}" used to access collection.' - .format(type(index)), DAQmxErrors.UNKNOWN) + 'Invalid index type "{}" used to access collection.'.format(type(index)), + DAQmxErrors.UNKNOWN, + ) - def __iter__(self): + def __iter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) for channel_name in self.channel_names: yield _PhysicalChannelAlternateConstructor(channel_name, self._interpreter) - def __len__(self): + def __len__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return len(self.channel_names) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __reversed__(self): + def __reversed__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) channel_names = self.channel_names channel_names.reverse() @@ -98,125 +110,124 @@ def __reversed__(self): @property def all(self): - """ - nidaqmx.system.physical_channel.PhysicalChannel: Specifies a - physical channel object that represents the entire list of - physical channels on this channel collection. - """ - return _PhysicalChannelAlternateConstructor(flatten_channel_string(self.channel_names), self._interpreter) + """nidaqmx.system.physical_channel.PhysicalChannel: Specifies a physical channel object that represents the entire list of physical channels on this channel collection.""" # noqa: W505 - doc line too long (179 > 100 characters) (auto-generated noqa) + return _PhysicalChannelAlternateConstructor( + flatten_channel_string(self.channel_names), self._interpreter + ) @property def channel_names(self): - """ - List[str]: Specifies the entire list of physical channels in this - collection. - """ + """List[str]: Specifies the entire list of physical channels in this collection.""" raise NotImplementedError() class AIPhysicalChannelCollection(PhysicalChannelCollection): - """ - Contains the collection of analog input physical channels for a - DAQmx device. - + """Contains the collection of analog input physical channels for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): - val = self._interpreter.get_device_attribute_string(self._name, 0x231e) + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): + val = self._interpreter.get_device_attribute_string(self._name, 0x231E) return unflatten_channel_string(val) class AOPhysicalChannelCollection(PhysicalChannelCollection): - """ - Contains the collection of analog output physical channels for a - DAQmx device. - + """Contains the collection of analog output physical channels for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): - val = self._interpreter.get_device_attribute_string(self._name, 0x231f) + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): + val = self._interpreter.get_device_attribute_string(self._name, 0x231F) return unflatten_channel_string(val) class CIPhysicalChannelCollection(PhysicalChannelCollection): - """ - Contains the collection of counter input physical channels for a - DAQmx device. - + """Contains the collection of counter input physical channels for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): val = self._interpreter.get_device_attribute_string(self._name, 0x2324) return unflatten_channel_string(val) class COPhysicalChannelCollection(PhysicalChannelCollection): - """ - Contains the collection of counter output physical channels for a - DAQmx device. - + """Contains the collection of counter output physical channels for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): val = self._interpreter.get_device_attribute_string(self._name, 0x2325) return unflatten_channel_string(val) class DILinesCollection(PhysicalChannelCollection): - """ - Contains the collection of digital input lines for a DAQmx device. - + """Contains the collection of digital input lines for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): val = self._interpreter.get_device_attribute_string(self._name, 0x2320) return unflatten_channel_string(val) class DOLinesCollection(PhysicalChannelCollection): - """ - Contains the collection of digital output lines for a DAQmx device. - + """Contains the collection of digital output lines for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): val = self._interpreter.get_device_attribute_string(self._name, 0x2322) return unflatten_channel_string(val) class DIPortsCollection(PhysicalChannelCollection): - """ - Contains the collection of digital input ports for a DAQmx device. - + """Contains the collection of digital input ports for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): val = self._interpreter.get_device_attribute_string(self._name, 0x2321) return unflatten_channel_string(val) class DOPortsCollection(PhysicalChannelCollection): - """ - Contains the collection of digital output ports for a DAQmx device. - + """Contains the collection of digital output ports for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): val = self._interpreter.get_device_attribute_string(self._name, 0x2323) return unflatten_channel_string(val) diff --git a/generated/nidaqmx/system/_watchdog_modules/expiration_states_collection.py b/generated/nidaqmx/system/_watchdog_modules/expiration_states_collection.py index 5d437ef92..6fee56327 100644 --- a/generated/nidaqmx/system/_watchdog_modules/expiration_states_collection.py +++ b/generated/nidaqmx/system/_watchdog_modules/expiration_states_collection.py @@ -3,41 +3,43 @@ class ExpirationStatesCollection: - """ - Contains the collection of expiration states for a DAQmx Watchdog Task. - + """Contains the collection of expiration states for a DAQmx Watchdog Task. + This class defines methods that implements a container object. """ - def __init__(self, task_handle, interpreter): + + def __init__( # noqa: D107 - Missing docstring in __init__ (auto-generated noqa) + self, task_handle, interpreter + ): self._handle = task_handle self._interpreter = interpreter - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return self._handle == other._handle return False - def __hash__(self): + def __hash__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return self._interpreter.hash_task_handle(self._handle) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) def __getitem__(self, index): - """ - Indexes an expiration state on this collection. + """Indexes an expiration state on this collection. Args: index (str): Name of the physical channel of which the expiration state to retrieve. + Returns: nidaqmx.system._watchdog_modules.expiration_state.ExpirationState: - + The object representing the indexed expiration state. """ if isinstance(index, str): return ExpirationState(self._handle, index, self._interpreter) else: raise DaqError( - 'Invalid index type "{}" used to access expiration states.' - .format(type(index)), -1) + 'Invalid index type "{}" used to access expiration states.'.format(type(index)), -1 + ) diff --git a/generated/nidaqmx/system/storage/__init__.py b/generated/nidaqmx/system/storage/__init__.py index 90e8571ba..eb2a0887a 100644 --- a/generated/nidaqmx/system/storage/__init__.py +++ b/generated/nidaqmx/system/storage/__init__.py @@ -1,5 +1,7 @@ +"""NI-DAQmx storage classes.""" + from nidaqmx.system.storage.persisted_channel import PersistedChannel from nidaqmx.system.storage.persisted_scale import PersistedScale from nidaqmx.system.storage.persisted_task import PersistedTask -__all__ = ['persisted_channel', 'persisted_scale', 'persisted_task'] +__all__ = ["persisted_channel", "persisted_scale", "persisted_task"] diff --git a/generated/nidaqmx/system/storage/persisted_channel.py b/generated/nidaqmx/system/storage/persisted_channel.py index fafa6aede..e0e4227e6 100644 --- a/generated/nidaqmx/system/storage/persisted_channel.py +++ b/generated/nidaqmx/system/storage/persisted_channel.py @@ -1,19 +1,22 @@ +"""NI-DAQmx persisted channel classes.""" + from nidaqmx import utils -__all__ = ['PersistedChannel'] +__all__ = ["PersistedChannel"] class PersistedChannel: - """ - Represents a saved DAQmx global channel. + """Represents a saved DAQmx global channel. Use the DAQmx Persisted Channel properties to query information about programmatically saved global channels. """ - __slots__ = ['_name', '_interpreter', '__weakref__'] + + __slots__ = ["_name", "_interpreter", "__weakref__"] def __init__(self, name, *, grpc_options=None): - """ + """Initialize a new PersistedChannel. + Args: name (str): Specifies the name of the global channel. grpc_options (Optional[:class:`~nidaqmx.GrpcSessionOptions`]): Specifies @@ -22,56 +25,45 @@ def __init__(self, name, *, grpc_options=None): self._name = name self._interpreter = utils._select_interpreter(grpc_options) - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return self._name == other._name return False - def __hash__(self): + def __hash__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return hash(self._name) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __repr__(self): - return f'PersistedChannel(name={self._name})' + def __repr__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + return f"PersistedChannel(name={self._name})" @property def name(self): - """ - str: Indicates the name of the global channel. - """ + """str: Indicates the name of the global channel.""" return self._name @property def author(self): - """ - str: Indicates the author of the global channel. - """ - val = self._interpreter.get_persisted_chan_attribute_string(self._name, 0x22d0) + """str: Indicates the author of the global channel.""" + val = self._interpreter.get_persisted_chan_attribute_string(self._name, 0x22D0) return val @property def allow_interactive_editing(self): - """ - bool: Indicates whether the global channel can be edited in the - DAQ Assistant. - """ - val = self._interpreter.get_persisted_chan_attribute_bool(self._name, 0x22d1) + """bool: Indicates whether the global channel can be edited in the DAQ Assistant.""" + val = self._interpreter.get_persisted_chan_attribute_bool(self._name, 0x22D1) return val @property def allow_interactive_deletion(self): - """ - bool: Indicates whether the global channel can be deleted - through MAX. - """ - val = self._interpreter.get_persisted_chan_attribute_bool(self._name, 0x22d2) + """bool: Indicates whether the global channel can be deleted through MAX.""" + val = self._interpreter.get_persisted_chan_attribute_bool(self._name, 0x22D2) return val def delete(self): - """ - Deletes this global channel from MAX. + """Deletes this global channel from MAX. This function does not remove the global channel from tasks that use it. @@ -80,16 +72,17 @@ def delete(self): class _PersistedChannelAlternateConstructor(PersistedChannel): - """ - Provide an alternate constructor for the PersistedChannel object. + """Provide an alternate constructor for the PersistedChannel object. This is a private API used to instantiate a PersistedChannel with an existing interpreter. """ - # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. + + # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. # noqa: W505 - doc line too long (108 > 100 characters) (auto-generated noqa) __slots__ = () def __init__(self, name, interpreter): - """ + """Initialize a new PersistedChannel with an existing interpreter. + Args: name: Specifies the name of the PersistedChannel. interpreter: Specifies the interpreter instance. @@ -100,4 +93,4 @@ def __init__(self, name, interpreter): # Use meta-programming to change the type of this object to PersistedChannel, # so the user isn't confused when doing introspection. - self.__class__ = PersistedChannel # type: ignore[assignment] \ No newline at end of file + self.__class__ = PersistedChannel # type: ignore[assignment] diff --git a/generated/nidaqmx/system/storage/persisted_scale.py b/generated/nidaqmx/system/storage/persisted_scale.py index 784f94244..c4d340a12 100644 --- a/generated/nidaqmx/system/storage/persisted_scale.py +++ b/generated/nidaqmx/system/storage/persisted_scale.py @@ -1,20 +1,23 @@ +"""NI-DAQmx persisted scale classes.""" + from nidaqmx import utils from nidaqmx.scale import _ScaleAlternateConstructor -__all__ = ['PersistedScale'] +__all__ = ["PersistedScale"] class PersistedScale: - """ - Represents a saved DAQmx custom scale. + """Represents a saved DAQmx custom scale. Use the DAQmx Persisted Scale properties to query information about programmatically saved custom scales. """ - __slots__ = ['_name', '_interpreter', '__weakref__'] + + __slots__ = ["_name", "_interpreter", "__weakref__"] def __init__(self, name, *, grpc_options=None): - """ + """Initialize a new PersistedScale. + Args: name (str): Specifies the name of the saved scale. grpc_options (Optional[:class:`~nidaqmx.GrpcSessionOptions`]): Specifies @@ -23,56 +26,45 @@ def __init__(self, name, *, grpc_options=None): self._name = name self._interpreter = utils._select_interpreter(grpc_options) - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return self._name == other._name return False - def __hash__(self): + def __hash__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return hash(self._name) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __repr__(self): - return f'PersistedScale(name={self._name})' + def __repr__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + return f"PersistedScale(name={self._name})" @property def name(self): - """ - str: Indicates the name of the custom scale. - """ + """str: Indicates the name of the custom scale.""" return self._name @property def author(self): - """ - str: Indicates the author of the custom scale. - """ - val = self._interpreter.get_persisted_scale_attribute_string(self._name, 0x22d4) + """str: Indicates the author of the custom scale.""" + val = self._interpreter.get_persisted_scale_attribute_string(self._name, 0x22D4) return val @property def allow_interactive_editing(self): - """ - bool: Indicates whether the custom scale can be edited in the - DAQ Assistant. - """ - val = self._interpreter.get_persisted_scale_attribute_bool(self._name, 0x22d5) + """bool: Indicates whether the custom scale can be edited in the DAQ Assistant.""" + val = self._interpreter.get_persisted_scale_attribute_bool(self._name, 0x22D5) return val @property def allow_interactive_deletion(self): - """ - bool: Indicates whether the custom scale can be deleted through - MAX. - """ - val = self._interpreter.get_persisted_scale_attribute_bool(self._name, 0x22d6) + """bool: Indicates whether the custom scale can be deleted through MAX.""" + val = self._interpreter.get_persisted_scale_attribute_bool(self._name, 0x22D6) return val def delete(self): - """ - Deletes this custom scale from MAX. + """Deletes this custom scale from MAX. This function does not remove the custom scale from virtual channels that use it. @@ -80,8 +72,7 @@ def delete(self): self._interpreter.delete_saved_scale(self._name) def load(self): - """ - Loads this custom scale. + """Loads this custom scale. Returns: nidaqmx.scale.Scale: Indicates the loaded Scale object. @@ -90,16 +81,17 @@ def load(self): class _PersistedScaleAlternateConstructor(PersistedScale): - """ - Provide an alternate constructor for the PersistedScale object. + """Provide an alternate constructor for the PersistedScale object. This is a private API used to instantiate a PersistedScale with an existing interpreter. """ - # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. + + # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. # noqa: W505 - doc line too long (108 > 100 characters) (auto-generated noqa) __slots__ = () def __init__(self, name, interpreter): - """ + """Initialize a new PersistedScale with an existing interpreter. + Args: name: Specifies the name of the PersistedScale. interpreter: Specifies the interpreter instance. @@ -110,4 +102,4 @@ def __init__(self, name, interpreter): # Use meta-programming to change the type of this object to PersistedScale, # so the user isn't confused when doing introspection. - self.__class__ = PersistedScale # type: ignore[assignment] \ No newline at end of file + self.__class__ = PersistedScale # type: ignore[assignment] diff --git a/generated/nidaqmx/system/storage/persisted_task.py b/generated/nidaqmx/system/storage/persisted_task.py index cf49bbdad..49493666f 100644 --- a/generated/nidaqmx/system/storage/persisted_task.py +++ b/generated/nidaqmx/system/storage/persisted_task.py @@ -1,20 +1,22 @@ -from nidaqmx import task -from nidaqmx import utils +"""NI-DAQmx persisted task classes.""" -__all__ = ['PersistedTask'] +from nidaqmx import task, utils + +__all__ = ["PersistedTask"] class PersistedTask: - """ - Represents a saved DAQmx task. + """Represents a saved DAQmx task. Use the DAQmx Persisted Task properties to query information about programmatically saved tasks. """ - __slots__ = ['_name', '_interpreter', '__weakref__'] + + __slots__ = ["_name", "_interpreter", "__weakref__"] def __init__(self, name, *, grpc_options=None): - """ + """Initialize a new PersistedTask. + Args: name (str): Specifies the name of the saved task. grpc_options (Optional[:class:`~nidaqmx.GrpcSessionOptions`]): Specifies @@ -23,55 +25,45 @@ def __init__(self, name, *, grpc_options=None): self._name = name self._interpreter = utils._select_interpreter(grpc_options) - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return self._name == other._name return False - def __hash__(self): + def __hash__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return hash(self._name) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __repr__(self): - return f'PersistedTask(name={self._name})' + def __repr__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + return f"PersistedTask(name={self._name})" @property def name(self): - """ - str: Indicates the name of the task. - """ + """str: Indicates the name of the task.""" return self._name @property def author(self): - """ - str: Indicates the author of the task. - """ - val = self._interpreter.get_persisted_task_attribute_string(self._name, 0x22cc) + """str: Indicates the author of the task.""" + val = self._interpreter.get_persisted_task_attribute_string(self._name, 0x22CC) return val @property def allow_interactive_editing(self): - """ - bool: Indicates whether the task can be edited in the DAQ - Assistant. - """ - val = self._interpreter.get_persisted_task_attribute_bool(self._name, 0x22cd) + """bool: Indicates whether the task can be edited in the DAQ Assistant.""" + val = self._interpreter.get_persisted_task_attribute_bool(self._name, 0x22CD) return val @property def allow_interactive_deletion(self): - """ - bool: Indicates whether the task can be deleted through MAX. - """ - val = self._interpreter.get_persisted_task_attribute_bool(self._name, 0x22ce) + """bool: Indicates whether the task can be deleted through MAX.""" + val = self._interpreter.get_persisted_task_attribute_bool(self._name, 0x22CE) return val def delete(self): - """ - Deletes this task from MAX. + """Deletes this task from MAX. This function does not clear the copy of the task stored in memory. Use the DAQmx Clear Task function to clear that copy of the task. @@ -79,8 +71,7 @@ def delete(self): self._interpreter.delete_saved_task(self._name) def load(self): - """ - Loads this saved task. + """Loads this saved task. If you use this function to load a task, you must use DAQmx Clear Task to destroy it. @@ -94,16 +85,17 @@ def load(self): class _PersistedTaskAlternateConstructor(PersistedTask): - """ - Provide an alternate constructor for the PersistedTask object. + """Provide an alternate constructor for the PersistedTask object. This is a private API used to instantiate a PersistedTask with an existing interpreter. """ - # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. + + # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. # noqa: W505 - doc line too long (108 > 100 characters) (auto-generated noqa) __slots__ = () def __init__(self, name, interpreter): - """ + """Initialize a new PersistedTask with an existing interpreter. + Args: name: Specifies the name of the PersistedTask. interpreter: Specifies the interpreter instance. diff --git a/generated/nidaqmx/task/__init__.py b/generated/nidaqmx/task/__init__.py index a5a3eef9b..202448c6a 100644 --- a/generated/nidaqmx/task/__init__.py +++ b/generated/nidaqmx/task/__init__.py @@ -1,9 +1,15 @@ -from nidaqmx.task._task import ( - Task, _TaskEventType, _TaskAlternateConstructor -) -from nidaqmx.task._in_stream import InStream -from nidaqmx.task._out_stream import OutStream +"""NI-DAQmx task and related classes.""" + from nidaqmx.task._export_signals import ExportSignals +from nidaqmx.task._in_stream import InStream +from nidaqmx.task._out_stream import OutStream +from nidaqmx.task._task import Task, _TaskAlternateConstructor, _TaskEventType from nidaqmx.task._timing import Timing -__all__ = ['Task', 'InStream', 'OutStream', 'ExportSignals', 'Timing',] \ No newline at end of file +__all__ = [ + "Task", + "InStream", + "OutStream", + "ExportSignals", + "Timing", +] diff --git a/generated/nidaqmx/task/_task.py b/generated/nidaqmx/task/_task.py index 49d954118..4977d25f8 100644 --- a/generated/nidaqmx/task/_task.py +++ b/generated/nidaqmx/task/_task.py @@ -7,37 +7,42 @@ import numpy from nitypes.waveform import AnalogWaveform, DigitalWaveform + from nidaqmx import utils from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature -from nidaqmx.task.channels._channel import Channel +from nidaqmx.constants import ( + READ_ALL_AVAILABLE, + AcquisitionType, + ChannelType, + EveryNSamplesEventType, + FillMode, + ShuntCalSelect, + ShuntCalSource, + ShuntElementLocation, + UsageTypeAI, + UsageTypeCI, + UsageTypeCO, + _Save, +) +from nidaqmx.error_codes import DAQmxErrors +from nidaqmx.errors import DaqError, DaqResourceWarning +from nidaqmx.system.device import _DeviceAlternateConstructor from nidaqmx.task._export_signals import ExportSignals from nidaqmx.task._in_stream import InStream +from nidaqmx.task._out_stream import OutStream from nidaqmx.task._timing import Timing +from nidaqmx.task.channels._channel import Channel +from nidaqmx.task.collections._ai_channel_collection import AIChannelCollection +from nidaqmx.task.collections._ao_channel_collection import AOChannelCollection +from nidaqmx.task.collections._ci_channel_collection import CIChannelCollection +from nidaqmx.task.collections._co_channel_collection import COChannelCollection +from nidaqmx.task.collections._di_channel_collection import DIChannelCollection +from nidaqmx.task.collections._do_channel_collection import DOChannelCollection from nidaqmx.task.triggering._triggers import Triggers -from nidaqmx.task._out_stream import OutStream -from nidaqmx.task.collections._ai_channel_collection import ( - AIChannelCollection) -from nidaqmx.task.collections._ao_channel_collection import ( - AOChannelCollection) -from nidaqmx.task.collections._ci_channel_collection import ( - CIChannelCollection) -from nidaqmx.task.collections._co_channel_collection import ( - COChannelCollection) -from nidaqmx.task.collections._di_channel_collection import ( - DIChannelCollection) -from nidaqmx.task.collections._do_channel_collection import ( - DOChannelCollection) -from nidaqmx.constants import ( - AcquisitionType, ChannelType, FillMode, UsageTypeAI, UsageTypeCI, EveryNSamplesEventType, - READ_ALL_AVAILABLE, UsageTypeCO, _Save, ShuntCalSelect, ShuntCalSource, ShuntElementLocation) -from nidaqmx.error_codes import DAQmxErrors -from nidaqmx.errors import ( - DaqError, DaqResourceWarning) -from nidaqmx.system.device import _DeviceAlternateConstructor from nidaqmx.types import CtrFreq, CtrTick, CtrTime, PowerMeasurement -from nidaqmx.utils import unflatten_channel_string, flatten_channel_string +from nidaqmx.utils import flatten_channel_string, unflatten_channel_string -__all__ = ['Task'] +__all__ = ["Task"] class UnsetNumSamplesSentinel: @@ -56,17 +61,32 @@ class UnsetAutoStartSentinel: class Task: - """ - Represents a DAQmx Task. - """ - __slots__ = ('_handle', '_close_on_exit', '_saved_name', '_grpc_options', '_event_handlers', '_interpreter', - '_ai_channels', '_ao_channels', '_ci_channels', '_co_channels', '_di_channels', '_do_channels', - '_export_signals', '_in_stream', '_timing', '_triggers', '_out_stream', '_event_handler_lock', - '__weakref__') - - def __init__(self, new_task_name='', *, grpc_options=None): - """ - Creates a DAQmx task. + """Represents a DAQmx Task.""" + + __slots__ = ( + "_handle", + "_close_on_exit", + "_saved_name", + "_grpc_options", + "_event_handlers", + "_interpreter", + "_ai_channels", + "_ao_channels", + "_ci_channels", + "_co_channels", + "_di_channels", + "_do_channels", + "_export_signals", + "_in_stream", + "_timing", + "_triggers", + "_out_stream", + "_event_handler_lock", + "__weakref__", + ) + + def __init__(self, new_task_name="", *, grpc_options=None): + """Creates a DAQmx task. Args: new_task_name (Optional[str]): Specifies the name to assign to @@ -81,7 +101,7 @@ def __init__(self, new_task_name='', *, grpc_options=None): grpc_options (Optional[:class:`~nidaqmx.GrpcSessionOptions`]): Specifies the gRPC session options. """ - # Initialize the fields that __del__ accesses so it doesn't crash when __init__ raises an exception. + # Initialize the fields that __del__ accesses so it doesn't crash when __init__ raises an exception. # noqa: W505 - doc line too long (108 > 100 characters) (auto-generated noqa) self._handle = None self._close_on_exit = False self._saved_name = new_task_name # _initialize sets this to the name assigned by DAQmx. @@ -94,188 +114,152 @@ def __init__(self, new_task_name='', *, grpc_options=None): raise DaqError( f'Unsupported session name: "{grpc_options.session_name}". If a session name is specified, it must match the task name.', DAQmxErrors.UNKNOWN, - task_name=new_task_name) + task_name=new_task_name, + ) self._interpreter = utils._select_interpreter(grpc_options) self._handle, self._close_on_exit = self._interpreter.create_task(new_task_name) self._initialize(self._handle, self._interpreter) - def __del__(self): + def __del__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if self._handle is not None and self._close_on_exit and self._grpc_options is None: warnings.warn( 'Task of name "{}" was not explicitly closed before it was ' - 'destructed. Resources on the task device may still be ' - 'reserved.'.format(self._saved_name), - DaqResourceWarning + "destructed. Resources on the task device may still be " + "reserved.".format(self._saved_name), + DaqResourceWarning, ) - elif ( - self._grpc_options is not None - and self._event_handlers - ): + elif self._grpc_options is not None and self._event_handlers: warnings.warn( 'Task of name "{}" was not explicitly closed before it was ' - 'destructed. Event handlers may still be active.'.format(self._saved_name), - DaqResourceWarning + "destructed. Event handlers may still be active.".format(self._saved_name), + DaqResourceWarning, ) - def __enter__(self): + def __enter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return self - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return self._handle == other._handle return False - def __exit__(self, type, value, traceback): + def __exit__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, type, value, traceback + ): if self._close_on_exit: self.close() - def __hash__(self): + def __hash__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return self._interpreter.hash_task_handle(self._handle) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __repr__(self): - return f'Task(name={self._saved_name})' + def __repr__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + return f"Task(name={self._saved_name})" @property def name(self): - """ - str: Indicates the name of the task. - """ + """str: Indicates the name of the task.""" val = self._interpreter.get_task_attribute_string(self._handle, 0x1276) return val @property def channels(self): - """ - :class:`nidaqmx.task.channels.Channel`: Specifies - a channel object that represents the entire list of virtual - channels in this task. - """ + """:class:`nidaqmx.task.channels.Channel`: Specifies a channel object that represents the entire list of virtual channels in this task.""" # noqa: W505 - doc line too long (146 > 100 characters) (auto-generated noqa) return Channel._factory( - self._handle, flatten_channel_string(self.channel_names), self._interpreter) + self._handle, flatten_channel_string(self.channel_names), self._interpreter + ) @property def channel_names(self): - """ - List[str]: Indicates the names of all virtual channels in the task. - """ + """List[str]: Indicates the names of all virtual channels in the task.""" val = self._interpreter.get_task_attribute_string(self._handle, 0x1273) return unflatten_channel_string(val) @property def number_of_channels(self): - """ - int: Indicates the number of virtual channels in the task. - """ + """int: Indicates the number of virtual channels in the task.""" val = self._interpreter.get_task_attribute_uint32(self._handle, 0x2181) return val @property def devices(self): - """ - List[:class:`nidaqmx.system.device.Device`]: Indicates a list - of Device objects representing all the devices in the task. - """ - val = self._interpreter.get_task_attribute_string(self._handle, 0x230e) - return [_DeviceAlternateConstructor(v, self._interpreter) for v in - unflatten_channel_string(val)] + """List[:class:`nidaqmx.system.device.Device`]: Indicates a list of Device objects representing all the devices in the task.""" # noqa: W505 - doc line too long (135 > 100 characters) (auto-generated noqa) + val = self._interpreter.get_task_attribute_string(self._handle, 0x230E) + return [ + _DeviceAlternateConstructor(v, self._interpreter) for v in unflatten_channel_string(val) + ] @property def number_of_devices(self): - """ - int: Indicates the number of devices in the task. - """ - val = self._interpreter.get_task_attribute_uint32(self._handle, 0x29ba) + """int: Indicates the number of devices in the task.""" + val = self._interpreter.get_task_attribute_uint32(self._handle, 0x29BA) return val @property def ai_channels(self) -> AIChannelCollection: - """ - Gets the collection of analog input channels for this task. - """ + """Gets the collection of analog input channels for this task.""" return self._ai_channels @property def ao_channels(self) -> AOChannelCollection: - """ - Gets the collection of analog output channels for this task. - """ + """Gets the collection of analog output channels for this task.""" return self._ao_channels @property def ci_channels(self) -> CIChannelCollection: - """ - Gets the collection of counter input channels for this task. - """ + """Gets the collection of counter input channels for this task.""" return self._ci_channels @property def co_channels(self) -> COChannelCollection: - """ - Gets the collection of counter output channels for this task. - """ + """Gets the collection of counter output channels for this task.""" return self._co_channels @property def di_channels(self) -> DIChannelCollection: - """ - Gets the collection of digital input channels for this task. - """ + """Gets the collection of digital input channels for this task.""" return self._di_channels @property def do_channels(self) -> DOChannelCollection: - """ - Gets the collection of digital output channels for this task. - """ + """Gets the collection of digital output channels for this task.""" return self._do_channels @property def export_signals(self) -> ExportSignals: - """ - Gets the exported signal configurations for the task. - """ + """Gets the exported signal configurations for the task.""" return self._export_signals @property def in_stream(self) -> InStream: - """ - Gets the read configurations for the task. - """ + """Gets the read configurations for the task.""" return self._in_stream @property def out_stream(self) -> OutStream: - """ - Gets the write configurations for the task. - """ + """Gets the write configurations for the task.""" return self._out_stream @property def timing(self) -> Timing: - """ - Gets the timing configurations for the task. - """ + """Gets the timing configurations for the task.""" return self._timing @property def triggers(self) -> Triggers: - """ - Gets the trigger configurations for the task. - """ + """Gets the trigger configurations for the task.""" return self._triggers def _initialize(self, task_handle, interpreter): - """ - Instantiates and populates various attributes used by this task. + """Instantiates and populates various attributes used by this task. Args: task_handle (TaskHandle): Specifies the handle for this task. - """ + """ # noqa: D417 - Missing argument descriptions in the docstring (auto-generated noqa) # Saved name is used in self.close() to throw graceful error on # double closes. self._saved_name = self.name @@ -295,8 +279,7 @@ def _initialize(self, task_handle, interpreter): self._event_handler_lock = threading.Lock() def _calculate_num_samps_per_chan(self, num_samps_per_chan): - """ - Calculates the actual number of samples per channel to read. + """Calculates the actual number of samples per channel to read. This method is necessary because the number of samples per channel can be set to NUM_SAMPLES_UNSET or -1, where each value entails a @@ -312,8 +295,7 @@ def _calculate_num_samps_per_chan(self, num_samps_per_chan): elif num_samps_per_chan == READ_ALL_AVAILABLE: acq_type = self.timing.samp_quant_samp_mode - if (acq_type == AcquisitionType.FINITE and - not self.in_stream.read_all_avail_samp): + if acq_type == AcquisitionType.FINITE and not self.in_stream.read_all_avail_samp: return self.timing.samp_quant_samp_per_chan else: return self.in_stream.avail_samp_per_chan @@ -321,8 +303,7 @@ def _calculate_num_samps_per_chan(self, num_samps_per_chan): return num_samps_per_chan def add_global_channels(self, global_channels): - """ - Adds global virtual channels from MAX to the given task. + """Adds global virtual channels from MAX to the given task. Args: global_channels (List[nidaqmx.system.storage.persisted_channel.PersistedChannel]): @@ -337,8 +318,7 @@ def add_global_channels(self, global_channels): self._interpreter.add_global_chans_to_task(self._handle, channels) def close(self): - """ - Clears the task. + """Clears the task. Before clearing, this method aborts the task, if necessary, and releases any resources the task reserved. You cannot use a task @@ -351,7 +331,9 @@ def close(self): if self._handle is None: warnings.warn( 'Attempted to close NI-DAQmx task of name "{}" but task was ' - 'already closed.'.format(self._saved_name), DaqResourceWarning) + "already closed.".format(self._saved_name), + DaqResourceWarning, + ) return first_exception = None @@ -375,8 +357,7 @@ def close(self): raise first_exception def control(self, action): - """ - Alters the state of a task according to the action you specify. + """Alters the state of a task according to the action you specify. Args: action (nidaqmx.constants.TaskMode): Specifies how to alter @@ -385,9 +366,9 @@ def control(self, action): self._interpreter.task_control(self._handle, action.value) def is_task_done(self): - """ - Queries the status of the task and indicates if it completed - execution. Use this function to ensure that the specified + """Queries the status of the task and indicates if it completed execution. + + Use this function to ensure that the specified operation is complete before you stop the task. Returns: @@ -400,8 +381,7 @@ def is_task_done(self): return is_task_done def perform_bridge_offset_nulling_cal(self, channel="", skip_unsupported_channels=False): - """ - Perform a bridge offset nulling calibration on the channels in the task. + """Perform a bridge offset nulling calibration on the channels in the task. If the task measures both bridge-based sensors and non-bridge-based sensors, use the channels input to specify the names of the channels that measure @@ -417,18 +397,22 @@ def perform_bridge_offset_nulling_cal(self, channel="", skip_unsupported_channel support calibration. If skip unsupported channels is TRUE, this VI calibrates only supported channels. If FALSE, this VI calibrates the channels specified by channels. The default is FALSE. - """ + """ # noqa: D202, W505 - No blank lines allowed after function docstring (auto-generated noqa), doc line too long (102 > 100 characters) (auto-generated noqa) self._interpreter.perform_bridge_offset_nulling_cal_ex( - self._handle, channel, skip_unsupported_channels) + self._handle, channel, skip_unsupported_channels + ) def perform_strain_shunt_cal( - self, channel="", shunt_resistor_value=100000, - shunt_resistor_location=ShuntElementLocation.R3, shunt_resistor_select=ShuntCalSelect.A, - shunt_resistor_source=ShuntCalSource.DEFAULT, skip_unsupported_channels=False): - """ - Perform shunt calibration for the specified channels using a strain - gage sensor. + self, + channel="", + shunt_resistor_value=100000, + shunt_resistor_location=ShuntElementLocation.R3, + shunt_resistor_select=ShuntCalSelect.A, + shunt_resistor_source=ShuntCalSource.DEFAULT, + skip_unsupported_channels=False, + ): + """Perform shunt calibration for the specified channels using a strain gage sensor. Refer to the calibration procedure for your module for detailed calibration instructions. @@ -449,17 +433,26 @@ def perform_strain_shunt_cal( the channels specified by channels. The default is False. """ self._interpreter.perform_strain_shunt_cal_ex( - self._handle, channel, shunt_resistor_value, - shunt_resistor_location.value, shunt_resistor_select.value, - shunt_resistor_source.value, skip_unsupported_channels) + self._handle, + channel, + shunt_resistor_value, + shunt_resistor_location.value, + shunt_resistor_select.value, + shunt_resistor_source.value, + skip_unsupported_channels, + ) def perform_bridge_shunt_cal( - self, channel="", shunt_resistor_value=100000, - shunt_resistor_location=ShuntElementLocation.R3, shunt_resistor_select=ShuntCalSelect.A, - shunt_resistor_source=ShuntCalSource.DEFAULT, bridge_resistance=120, - skip_unsupported_channels=False): - """ - Perform shunt calibration for the specified channels using a bridge sensor. + self, + channel="", + shunt_resistor_value=100000, + shunt_resistor_location=ShuntElementLocation.R3, + shunt_resistor_select=ShuntCalSelect.A, + shunt_resistor_source=ShuntCalSource.DEFAULT, + bridge_resistance=120, + skip_unsupported_channels=False, + ): + """Perform shunt calibration for the specified channels using a bridge sensor. Refer to the calibration procedure for your module for detailed calibration instructions. @@ -483,14 +476,18 @@ def perform_bridge_shunt_cal( the channels specified by channels. The default is False. """ self._interpreter.perform_bridge_shunt_cal_ex( - self._handle, channel, shunt_resistor_value, - shunt_resistor_location.value, shunt_resistor_select.value, - shunt_resistor_source.value, bridge_resistance, - skip_unsupported_channels) + self._handle, + channel, + shunt_resistor_value, + shunt_resistor_location.value, + shunt_resistor_select.value, + shunt_resistor_source.value, + bridge_resistance, + skip_unsupported_channels, + ) def perform_thrmcpl_lead_offset_nulling_cal(self, channel="", skip_unsupported_channels=False): - """ - Perform thermocouple lead offset nulling calibration on the channels in the task. + """Perform thermocouple lead offset nulling calibration on the channels in the task. This is to compensate for offsets introduced by open thermocouple detection. Keep the measured temperature as constant as possible while performing this @@ -506,15 +503,14 @@ def perform_thrmcpl_lead_offset_nulling_cal(self, channel="", skip_unsupported_c support calibration. If skip unsupported channels is TRUE, this VI calibrates only supported channels. If FALSE, this VI calibrates the channels specified by channels. The default is FALSE. - """ + """ # noqa: D202, W505 - No blank lines allowed after function docstring (auto-generated noqa), doc line too long (102 > 100 characters) (auto-generated noqa) self._interpreter.perform_thrmcpl_lead_offset_nulling_cal( - self._handle, channel, skip_unsupported_channels) + self._handle, channel, skip_unsupported_channels + ) - def read(self, number_of_samples_per_channel=NUM_SAMPLES_UNSET, - timeout=10.0): - """ - Reads samples from the task or virtual channels you specify. + def read(self, number_of_samples_per_channel=NUM_SAMPLES_UNSET, timeout=10.0): + """Reads samples from the task or virtual channels you specify. This read method is dynamic, and is capable of inferring an appropriate return type based on these factors: @@ -574,6 +570,7 @@ def read(self, number_of_samples_per_channel=NUM_SAMPLES_UNSET, indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: dynamic: @@ -597,18 +594,16 @@ def read(self, number_of_samples_per_channel=NUM_SAMPLES_UNSET, number_of_channels = len(channels_to_read.channel_names) read_chan_type = channels_to_read.chan_type - num_samples_not_set = (number_of_samples_per_channel is - NUM_SAMPLES_UNSET) + num_samples_not_set = number_of_samples_per_channel is NUM_SAMPLES_UNSET number_of_samples_per_channel = self._calculate_num_samps_per_chan( - number_of_samples_per_channel) + number_of_samples_per_channel + ) # Determine the array shape and size to create if number_of_channels > 1: if not num_samples_not_set: - array_shape: tuple[int, ...] = ( - number_of_channels, number_of_samples_per_channel - ) + array_shape: tuple[int, ...] = (number_of_channels, number_of_samples_per_channel) else: array_shape = (number_of_channels,) else: @@ -622,54 +617,77 @@ def read(self, number_of_samples_per_channel=NUM_SAMPLES_UNSET, else: data: numpy.typing.NDArray = numpy.zeros(array_shape, dtype=numpy.float64) _, samples_read = self._interpreter.read_analog_f64( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) - elif (read_chan_type == ChannelType.DIGITAL_INPUT or - read_chan_type == ChannelType.DIGITAL_OUTPUT): + elif ( + read_chan_type == ChannelType.DIGITAL_INPUT + or read_chan_type == ChannelType.DIGITAL_OUTPUT + ): if self.in_stream.di_num_booleans_per_chan == 1: data = numpy.zeros(array_shape, dtype=bool) _, samples_read, _ = self._interpreter.read_digital_lines( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) else: data = numpy.zeros(array_shape, dtype=numpy.uint32) _, samples_read = self._interpreter.read_digital_u32( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) elif read_chan_type == ChannelType.COUNTER_INPUT: meas_type = channels_to_read.ci_meas_type - if meas_type in [UsageTypeCI.PULSE_FREQ, UsageTypeCI.PULSE_TIME, UsageTypeCI.PULSE_TICKS]: + if meas_type in [ + UsageTypeCI.PULSE_FREQ, + UsageTypeCI.PULSE_TIME, + UsageTypeCI.PULSE_TICKS, + ]: return self._read_ctr_pulse( array_shape, meas_type, number_of_channels, number_of_samples_per_channel, num_samples_not_set, - timeout + timeout, ) else: data = numpy.zeros(array_shape, dtype=numpy.float64) _, samples_read = self._interpreter.read_counter_f64_ex( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) else: raise DaqError( - 'Read failed, because there are no channels in this task from ' - 'which data can be read.', + "Read failed, because there are no channels in this task from " + "which data can be read.", DAQmxErrors.READ_NO_INPUT_CHANS_IN_TASK, - task_name=self.name) + task_name=self.name, + ) if num_samples_not_set and array_shape == (1,): return data.tolist()[0] if samples_read != number_of_samples_per_channel: if number_of_channels > 1: - return data[:,:samples_read].tolist() + return data[:, :samples_read].tolist() else: return data[:samples_read].tolist() @@ -689,8 +707,13 @@ def _read_ctr_pulse( duty_cycles = numpy.zeros(array_shape, dtype=numpy.float64) _, _, samples_read = self._interpreter.read_ctr_freq( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, frequencies, duty_cycles) + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + frequencies, + duty_cycles, + ) data: list[CtrFreq] | list[CtrTick] | list[CtrTime] = [ CtrFreq(freq=f, duty_cycle=d) for f, d in zip(frequencies, duty_cycles) @@ -701,17 +724,27 @@ def _read_ctr_pulse( low_times = numpy.zeros(array_shape, dtype=numpy.float64) _, _, samples_read = self._interpreter.read_ctr_time( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_times, low_times) + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_times, + low_times, + ) data = [CtrTime(high_time=h, low_time=l) for h, l in zip(high_times, low_times)] elif meas_type == UsageTypeCI.PULSE_TICKS: high_ticks = numpy.zeros(array_shape, dtype=numpy.uint32) low_ticks = numpy.zeros(array_shape, dtype=numpy.uint32) - _, _ , samples_read = self._interpreter.read_ctr_ticks( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_ticks, low_ticks) + _, _, samples_read = self._interpreter.read_ctr_ticks( + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_ticks, + low_ticks, + ) data = [CtrTick(high_tick=h, low_tick=l) for h, l in zip(high_ticks, low_ticks)] else: @@ -741,16 +774,18 @@ def _read_power( currents = numpy.zeros(array_shape, dtype=numpy.float64) _, _, samples_read = self._interpreter.read_power_f64( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, voltages, currents) + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + voltages, + currents, + ) if number_of_channels > 1: if number_of_samples_per_channel == 1: # n channel, 1 sample - return [ - PowerMeasurement(voltage=v, current=i) - for v, i in zip(voltages, currents) - ] + return [PowerMeasurement(voltage=v, current=i) for v, i in zip(voltages, currents)] else: # n channel, n samples return [ @@ -766,16 +801,13 @@ def _read_power( return PowerMeasurement(voltage=voltages[0], current=currents[0]) else: # 1 channel, n samples - return [ - PowerMeasurement(voltage=v, current=i) - for v, i in zip(voltages, currents) - ][:samples_read] + return [PowerMeasurement(voltage=v, current=i) for v, i in zip(voltages, currents)][ + :samples_read + ] @requires_feature(WAVEFORM_SUPPORT) - def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads samples from the task or virtual channels you specify, and returns them as waveforms. + def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): + """Reads samples from the task or virtual channels you specify, and returns them as waveforms. This read method is dynamic, and is capable of inferring an appropriate return type based on these factors: @@ -795,7 +827,7 @@ def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, number of samples to read. If this input is not set, it defaults to nidaqmx.constants.READ_ALL_AVAILABLE. - If this input is nidaqmx.constants.READ_ALL_AVAILABLE, + If this input is nidaqmx.constants.READ_ALL_AVAILABLE, NI-DAQmx determines how many samples to read based on if the task acquires samples continuously or acquires a finite number of samples. @@ -821,6 +853,7 @@ def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: dynamic: @@ -838,13 +871,14 @@ def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, >>> data = task.read_waveform() >>> type(data) - """ + """ # noqa: W505 - doc line too long (102 > 100 characters) (auto-generated noqa) channels_to_read = self.in_stream.channels_to_read number_of_channels = len(channels_to_read.channel_names) read_chan_type = channels_to_read.chan_type number_of_samples_per_channel = self._calculate_num_samps_per_chan( - number_of_samples_per_channel) + number_of_samples_per_channel + ) if read_chan_type == ChannelType.ANALOG_INPUT: if number_of_channels == 1: @@ -859,8 +893,7 @@ def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, return analog_waveform else: analog_waveforms = [ - AnalogWaveform(number_of_samples_per_channel) - for _ in range(number_of_channels) + AnalogWaveform(number_of_samples_per_channel) for _ in range(number_of_channels) ] self._interpreter.read_analog_waveforms( self._handle, @@ -871,12 +904,14 @@ def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, ) return analog_waveforms - elif (read_chan_type == ChannelType.DIGITAL_INPUT or - read_chan_type == ChannelType.DIGITAL_OUTPUT): + elif ( + read_chan_type == ChannelType.DIGITAL_INPUT + or read_chan_type == ChannelType.DIGITAL_OUTPUT + ): if number_of_channels == 1: digital_waveform = DigitalWaveform( - number_of_samples_per_channel, - self.in_stream.di_num_booleans_per_chan) + number_of_samples_per_channel, self.in_stream.di_num_booleans_per_chan + ) self._interpreter.read_digital_waveform( self._handle, number_of_samples_per_channel, @@ -897,17 +932,16 @@ def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, else: raise DaqError( - 'Read failed, because there are no channels in this task from ' - 'which data can be read.', + "Read failed, because there are no channels in this task from " + "which data can be read.", DAQmxErrors.READ_NO_INPUT_CHANS_IN_TASK, - task_name=self.name) + task_name=self.name, + ) def register_done_event(self, callback_method): - """ - Registers a callback function to receive an event when a task stops due - to an error or when a finite acquisition task or finite generation task - completes execution. A Done event does not occur when a task is stopped - explicitly, such as by calling DAQmx Stop Task. + """Registers a callback function to receive an event when a task stops due to an error or when a finite acquisition task or finite generation task completes execution. + + A Done event does not occur when a task is stopped explicitly, such as by calling DAQmx Stop Task. Args: callback_method (function): Specifies the function that you want @@ -928,11 +962,13 @@ def register_done_event(self, callback_method): Passing None for this parameter unregisters the event callback function. - """ + """ # noqa: W505 - doc line too long (175 > 100 characters) (auto-generated noqa) if callback_method is not None: # If the event is already registered, the interpreter should raise DaqError with code # DAQmxErrors.DONE_EVENT_ALREADY_REGISTERED. - event_handler = self._interpreter.register_done_event(self._handle, 0, callback_method, None) + event_handler = self._interpreter.register_done_event( + self._handle, 0, callback_method, None + ) with self._event_handler_lock: assert _TaskEventType.DONE not in self._event_handlers, "Event already registered." self._event_handlers[_TaskEventType.DONE] = event_handler @@ -943,12 +979,10 @@ def register_done_event(self, callback_method): if event_handler is not None: event_handler.close() # may raise an exception - def register_every_n_samples_acquired_into_buffer_event( - self, sample_interval, callback_method): - """ - Registers a callback function to receive an event when the specified - number of samples is written from the device to the buffer. This - function only works with devices that support buffered tasks. + def register_every_n_samples_acquired_into_buffer_event(self, sample_interval, callback_method): + """Registers a callback function to receive an event when the specified number of samples is written from the device to the buffer. + + This function only works with devices that support buffered tasks. When you stop a task explicitly any pending events are discarded. For example, if you call DAQmx Stop Task then you do not receive any @@ -976,30 +1010,42 @@ def register_every_n_samples_acquired_into_buffer_event( Passing None for this parameter unregisters the event callback function. - """ + """ # noqa: W505 - doc line too long (139 > 100 characters) (auto-generated noqa) if callback_method is not None: # If the event is already registered, the interpreter should raise DaqError with code # DAQmxErrors.EVERY_N_SAMPS_ACQ_INTO_BUFFER_EVENT_ALREADY_REGISTERED. event_handler = self._interpreter.register_every_n_samples_event( - self._handle, EveryNSamplesEventType.ACQUIRED_INTO_BUFFER.value, - sample_interval, 0, callback_method, None) + self._handle, + EveryNSamplesEventType.ACQUIRED_INTO_BUFFER.value, + sample_interval, + 0, + callback_method, + None, + ) with self._event_handler_lock: - assert _TaskEventType.EVERY_N_SAMPLES_ACQUIRED_INTO_BUFFER not in self._event_handlers, "Event already registered." - self._event_handlers[_TaskEventType.EVERY_N_SAMPLES_ACQUIRED_INTO_BUFFER] = event_handler + assert ( + _TaskEventType.EVERY_N_SAMPLES_ACQUIRED_INTO_BUFFER not in self._event_handlers + ), "Event already registered." + self._event_handlers[_TaskEventType.EVERY_N_SAMPLES_ACQUIRED_INTO_BUFFER] = ( + event_handler + ) else: self._interpreter.unregister_every_n_samples_event( - self._handle, EveryNSamplesEventType.ACQUIRED_INTO_BUFFER.value) + self._handle, EveryNSamplesEventType.ACQUIRED_INTO_BUFFER.value + ) with self._event_handler_lock: - event_handler = self._event_handlers.pop(_TaskEventType.EVERY_N_SAMPLES_ACQUIRED_INTO_BUFFER, None) + event_handler = self._event_handlers.pop( + _TaskEventType.EVERY_N_SAMPLES_ACQUIRED_INTO_BUFFER, None + ) if event_handler is not None: event_handler.close() # may raise an exception def register_every_n_samples_transferred_from_buffer_event( - self, sample_interval, callback_method): - """ - Registers a callback function to receive an event when the specified - number of samples is written from the buffer to the device. This - function only works with devices that support buffered tasks. + self, sample_interval, callback_method + ): + """Registers a callback function to receive an event when the specified number of samples is written from the buffer to the device. + + This function only works with devices that support buffered tasks. When you stop a task explicitly any pending events are discarded. For example, if you call DAQmx Stop Task then you do not receive any @@ -1027,28 +1073,39 @@ def register_every_n_samples_transferred_from_buffer_event( Passing None for this parameter unregisters the event callback function. - """ + """ # noqa: W505 - doc line too long (139 > 100 characters) (auto-generated noqa) if callback_method is not None: # If the event is already registered, the interpreter should raise DaqError with code # DAQmxErrors.EVERY_N_SAMPS_TRANSFERRED_FROM_BUFFER_EVENT_ALREADY_REGISTERED. event_handler = self._interpreter.register_every_n_samples_event( - self._handle, EveryNSamplesEventType.TRANSFERRED_FROM_BUFFER.value, - sample_interval, 0, callback_method, None) + self._handle, + EveryNSamplesEventType.TRANSFERRED_FROM_BUFFER.value, + sample_interval, + 0, + callback_method, + None, + ) with self._event_handler_lock: - assert _TaskEventType.EVERY_N_SAMPLES_TRANSFERRED_FROM_BUFFER not in self._event_handlers, "Event already registered." - self._event_handlers[_TaskEventType.EVERY_N_SAMPLES_TRANSFERRED_FROM_BUFFER] = event_handler + assert ( + _TaskEventType.EVERY_N_SAMPLES_TRANSFERRED_FROM_BUFFER + not in self._event_handlers + ), "Event already registered." + self._event_handlers[_TaskEventType.EVERY_N_SAMPLES_TRANSFERRED_FROM_BUFFER] = ( + event_handler + ) else: self._interpreter.unregister_every_n_samples_event( - self._handle, EveryNSamplesEventType.TRANSFERRED_FROM_BUFFER.value) + self._handle, EveryNSamplesEventType.TRANSFERRED_FROM_BUFFER.value + ) with self._event_handler_lock: - event_handler = self._event_handlers.pop(_TaskEventType.EVERY_N_SAMPLES_TRANSFERRED_FROM_BUFFER, None) + event_handler = self._event_handlers.pop( + _TaskEventType.EVERY_N_SAMPLES_TRANSFERRED_FROM_BUFFER, None + ) if event_handler is not None: event_handler.close() # may raise an exception def register_signal_event(self, signal_type, callback_method): - """ - Registers a callback function to receive an event when the specified - hardware event occurs. + """Registers a callback function to receive an event when the specified hardware event occurs. When you stop a task explicitly any pending events are discarded. For example, if you call DAQmx Stop Task then you do not receive any @@ -1073,14 +1130,17 @@ def register_signal_event(self, signal_type, callback_method): Passing None for this parameter unregisters the event callback function. - """ + """ # noqa: W505 - doc line too long (102 > 100 characters) (auto-generated noqa) if callback_method is not None: # If the event is already registered, the interpreter should raise DaqError with code # DAQmxErrors.SIGNAL_EVENT_ALREADY_REGISTERED. event_handler = self._interpreter.register_signal_event( - self._handle, signal_type.value, 0, callback_method, None) + self._handle, signal_type.value, 0, callback_method, None + ) with self._event_handler_lock: - assert _TaskEventType.SIGNAL not in self._event_handlers, "Event already registered." + assert ( + _TaskEventType.SIGNAL not in self._event_handlers + ), "Event already registered." self._event_handlers[_TaskEventType.SIGNAL] = event_handler else: self._interpreter.unregister_signal_event(self._handle, signal_type.value) @@ -1089,10 +1149,15 @@ def register_signal_event(self, signal_type, callback_method): if event_handler is not None: event_handler.close() # may raise an exception - def save(self, save_as="", author="", overwrite_existing_task=False, - allow_interactive_editing=True, allow_interactive_deletion=True): - """ - Saves this task and any local channels it contains to MAX. + def save( + self, + save_as="", + author="", + overwrite_existing_task=False, + allow_interactive_editing=True, + allow_interactive_deletion=True, + ): + """Saves this task and any local channels it contains to MAX. This function does not save global channels. Use the DAQmx Save Global Channel function to save global channels. @@ -1129,9 +1194,10 @@ def save(self, save_as="", author="", overwrite_existing_task=False, self._interpreter.save_task(self._handle, save_as, author, options) def start(self): - """ - Transitions the task to the running state to begin the measurement - or generation. Using this method is required for some applications and + """Start the task. + + This method transitions the task to the running state to begin the measurement or + generation. Using this method is required for some applications and is optional for others. If you do not use this method, a measurement task starts automatically @@ -1148,8 +1214,9 @@ def start(self): self._interpreter.start_task(self._handle) def stop(self): - """ - Stops the task and returns it to the state the task was in before the + """Stop the task. + + This method stops the task and returns it to the state the task was in before the DAQmx Start Task method ran or the DAQmx Write method ran with the autostart input set to TRUE. @@ -1162,8 +1229,7 @@ def stop(self): self._interpreter.stop_task(self._handle) def wait_for_valid_timestamp(self, timestamp_event, timeout=10.0): - """ - Wait until the specified timestamp has a value. + """Wait until the specified timestamp has a value. Use this method to ensure the timestamp has a valid value to prevent an error when querying a timestamp value. @@ -1179,12 +1245,13 @@ def wait_for_valid_timestamp(self, timestamp_event, timeout=10.0): datetime: The timestamp value of timestamp_event. - """ - return self._interpreter.wait_for_valid_timestamp(self._handle, timestamp_event.value, timeout) + """ # noqa: W505 - doc line too long (118 > 100 characters) (auto-generated noqa) + return self._interpreter.wait_for_valid_timestamp( + self._handle, timestamp_event.value, timeout + ) def wait_until_done(self, timeout=10.0): - """ - Waits for the measurement or generation to complete. + """Waits for the measurement or generation to complete. Use this method to ensure that the specified operation is complete before you stop the task. @@ -1200,38 +1267,36 @@ def wait_until_done(self, timeout=10.0): """ self._interpreter.wait_until_task_done(self._handle, timeout) - def _raise_invalid_num_lines_error( - self, num_lines_expected, num_lines_in_data): + def _raise_invalid_num_lines_error(self, num_lines_expected, num_lines_in_data): raise DaqError( - 'Specified read or write operation failed, because the number ' - 'of lines in the data for a channel does not match the number ' - 'of lines in the channel.\n\n' - 'If you are using boolean data, make sure the array dimension ' - 'for lines in the data matches the number of lines in the ' - 'channel.\n\n' - 'Number of Lines Per Channel in Task: {}\n' - 'Number of Lines Per Channel in Data: {}' - .format(num_lines_expected, num_lines_in_data), + "Specified read or write operation failed, because the number " + "of lines in the data for a channel does not match the number " + "of lines in the channel.\n\n" + "If you are using boolean data, make sure the array dimension " + "for lines in the data matches the number of lines in the " + "channel.\n\n" + "Number of Lines Per Channel in Task: {}\n" + "Number of Lines Per Channel in Data: {}".format(num_lines_expected, num_lines_in_data), DAQmxErrors.NUM_LINES_MISMATCH_IN_READ_OR_WRITE, - task_name=self.name) + task_name=self.name, + ) - def _raise_invalid_write_num_chans_error( - self, number_of_channels, number_of_channels_in_data): + def _raise_invalid_write_num_chans_error(self, number_of_channels, number_of_channels_in_data): raise DaqError( - 'Write cannot be performed, because the number of channels in the ' - 'data does not match the number of channels in the task.\n\n' - 'When writing, supply data for all channels in the task. ' - 'Alternatively, modify the task to contain the same number of ' - 'channels as the data written.\n\n' - 'Number of Channels in Task: {}\n' - 'Number of Channels in Data: {}' - .format(number_of_channels, number_of_channels_in_data), - DAQmxErrors.WRITE_NUM_CHANS_MISMATCH, task_name=self.name) + "Write cannot be performed, because the number of channels in the " + "data does not match the number of channels in the task.\n\n" + "When writing, supply data for all channels in the task. " + "Alternatively, modify the task to contain the same number of " + "channels as the data written.\n\n" + "Number of Channels in Task: {}\n" + "Number of Channels in Data: {}".format(number_of_channels, number_of_channels_in_data), + DAQmxErrors.WRITE_NUM_CHANS_MISMATCH, + task_name=self.name, + ) def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): - """ - Writes samples to the task or virtual channels you specify. + """Writes samples to the task or virtual channels you specify. This write method is dynamic, and is capable of accepting the samples to write in the various forms for most operations: @@ -1290,6 +1355,7 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: @@ -1304,16 +1370,14 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): if number_of_channels == 1: if isinstance(data, list): if isinstance(data[0], list): - self._raise_invalid_write_num_chans_error( - number_of_channels, len(data)) + self._raise_invalid_write_num_chans_error(number_of_channels, len(data)) number_of_samples_per_channel = len(data) element = data[0] elif isinstance(data, numpy.ndarray): if len(data.shape) == 2: - self._raise_invalid_write_num_chans_error( - number_of_channels, data.shape[0]) + self._raise_invalid_write_num_chans_error(number_of_channels, data.shape[0]) number_of_samples_per_channel = len(data) element = data[0] @@ -1321,8 +1385,7 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): elif isinstance(data, AnalogWaveform): WAVEFORM_SUPPORT.raise_if_disabled() if number_of_channels != 1: - self._raise_invalid_write_num_chans_error( - number_of_channels, 1) + self._raise_invalid_write_num_chans_error(number_of_channels, 1) number_of_samples_per_channel = data.sample_count element = data.raw_data[0] @@ -1333,8 +1396,7 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): else: if isinstance(data, list): if len(data) != number_of_channels: - self._raise_invalid_write_num_chans_error( - number_of_channels, len(data)) + self._raise_invalid_write_num_chans_error(number_of_channels, len(data)) if isinstance(data[0], list): number_of_samples_per_channel = len(data[0]) @@ -1345,8 +1407,7 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): elif isinstance(data, numpy.ndarray): if data.shape[0] != number_of_channels: - self._raise_invalid_write_num_chans_error( - number_of_channels, data.shape[0]) + self._raise_invalid_write_num_chans_error(number_of_channels, data.shape[0]) if len(data.shape) == 2: number_of_samples_per_channel = data.shape[1] @@ -1356,8 +1417,7 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): element = data[0] else: - self._raise_invalid_write_num_chans_error( - number_of_channels, 1) + self._raise_invalid_write_num_chans_error(number_of_channels, 1) if auto_start is AUTO_START_UNSET: if number_of_samples_per_channel > 1: @@ -1368,42 +1428,60 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): if write_chan_type == ChannelType.ANALOG_OUTPUT: if isinstance(data, AnalogWaveform): return self._interpreter.write_analog_waveform( - self._handle, data, auto_start, timeout) + self._handle, data, auto_start, timeout + ) else: data = numpy.asarray(data, dtype=numpy.float64) return self._interpreter.write_analog_f64( - self._handle, number_of_samples_per_channel, auto_start, - timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, + number_of_samples_per_channel, + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) elif write_chan_type == ChannelType.DIGITAL_OUTPUT: if self.out_stream.do_num_booleans_per_chan == 1: - if (not isinstance(element, bool) and - not isinstance(element, numpy.bool_)): + if not isinstance(element, bool) and not isinstance(element, numpy.bool_): raise DaqError( - 'Write failed, because this write method only accepts ' - 'boolean samples when there is one digital line per ' - 'channel in a task.\n\n' - 'Requested sample type: {}'.format(type(element)), - DAQmxErrors.UNKNOWN, task_name=self.name) + "Write failed, because this write method only accepts " + "boolean samples when there is one digital line per " + "channel in a task.\n\n" + "Requested sample type: {}".format(type(element)), + DAQmxErrors.UNKNOWN, + task_name=self.name, + ) data = numpy.asarray(data, dtype=bool) return self._interpreter.write_digital_lines( - self._handle, number_of_samples_per_channel, - auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, + number_of_samples_per_channel, + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) else: - if (not isinstance(element, int) and - not isinstance(element, numpy.uint32)): + if not isinstance(element, int) and not isinstance(element, numpy.uint32): raise DaqError( - 'Write failed, because this write method only accepts ' - 'unsigned 32-bit integer samples when there are ' - 'multiple digital lines per channel in a task.\n\n' - 'Requested sample type: {}'.format(type(element)), - DAQmxErrors.UNKNOWN, task_name=self.name) + "Write failed, because this write method only accepts " + "unsigned 32-bit integer samples when there are " + "multiple digital lines per channel in a task.\n\n" + "Requested sample type: {}".format(type(element)), + DAQmxErrors.UNKNOWN, + task_name=self.name, + ) data = numpy.asarray(data, dtype=numpy.uint32) return self._interpreter.write_digital_u32( - self._handle, number_of_samples_per_channel, - auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, + number_of_samples_per_channel, + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) elif write_chan_type == ChannelType.COUNTER_OUTPUT: output_type = channels_to_write.co_output_type @@ -1412,20 +1490,30 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): data = [data] elif not isinstance(data, Iterable): raise DaqError( - 'Write failed, because the provided data type is not supported ' - 'for counter output channels.', - DAQmxErrors.UNKNOWN, task_name=self.name) + "Write failed, because the provided data type is not supported " + "for counter output channels.", + DAQmxErrors.UNKNOWN, + task_name=self.name, + ) if output_type == UsageTypeCO.PULSE_FREQUENCY: if not all(isinstance(sample, CtrFreq) for sample in data): raise TypeError(f"Output type {output_type} requires samples of type CtrFreq.") frequencies = numpy.array([sample.freq for sample in data], dtype=numpy.float64) - duty_cycles = numpy.array([sample.duty_cycle for sample in data], dtype=numpy.float64) + duty_cycles = numpy.array( + [sample.duty_cycle for sample in data], dtype=numpy.float64 + ) return self._interpreter.write_ctr_freq( - self._handle, number_of_samples_per_channel, auto_start, timeout, - FillMode.GROUP_BY_CHANNEL.value, frequencies, duty_cycles) + self._handle, + number_of_samples_per_channel, + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + frequencies, + duty_cycles, + ) elif output_type == UsageTypeCO.PULSE_TIME: if not all(isinstance(sample, CtrTime) for sample in data): @@ -1435,8 +1523,14 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): low_times = numpy.array([sample.low_time for sample in data], dtype=numpy.float64) return self._interpreter.write_ctr_time( - self._handle, number_of_samples_per_channel, auto_start, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_times, low_times) + self._handle, + number_of_samples_per_channel, + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_times, + low_times, + ) elif output_type == UsageTypeCO.PULSE_TICKS: if not all(isinstance(sample, CtrTick) for sample in data): @@ -1446,8 +1540,14 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): low_ticks = numpy.array([sample.low_tick for sample in data], dtype=numpy.uint32) return self._interpreter.write_ctr_ticks( - self._handle, number_of_samples_per_channel, auto_start, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_ticks, low_ticks) + self._handle, + number_of_samples_per_channel, + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_ticks, + low_ticks, + ) else: raise DaqError( @@ -1459,31 +1559,32 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): else: raise DaqError( - 'Write failed, because there are no output channels in this ' - 'task to which data can be written.', + "Write failed, because there are no output channels in this " + "task to which data can be written.", DAQmxErrors.WRITE_NO_OUTPUT_CHANS_IN_TASK, - task_name=self.name) + task_name=self.name, + ) class _TaskAlternateConstructor(Task): - """ - Provide an alternate constructor for the Task object. + """Provide an alternate constructor for the Task object. This is a private API used to instantiate a Task with an existing task handle and interpreter. """ - # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. + + # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. # noqa: W505 - doc line too long (108 > 100 characters) (auto-generated noqa) __slots__ = () def __init__(self, task_handle, interpreter, close_on_exit): - """ + """Initialize a new Task with an existing interpreter. + Args: task_handle: Specifies the task handle from which to create a Task object. interpreter: Specifies the interpreter instance. close_on_exit: Specifies whether the task's context manager closes the task. - """ - # Initialize the fields that __del__ accesses so it doesn't crash when _initialize raises an exception. + # Initialize the fields that __del__ accesses so it doesn't crash when _initialize raises an exception. # noqa: W505 - doc line too long (111 > 100 characters) (auto-generated noqa) self._handle = task_handle self._close_on_exit = close_on_exit self._saved_name = "" # _initialize sets this to the name assigned by DAQmx. @@ -1500,7 +1601,8 @@ def __init__(self, task_handle, interpreter, close_on_exit): class _TaskEventType(Enum): """Internal enum for task event bookkeeping.""" + DONE = 1 EVERY_N_SAMPLES_ACQUIRED_INTO_BUFFER = 2 EVERY_N_SAMPLES_TRANSFERRED_FROM_BUFFER = 3 - SIGNAL = 4 \ No newline at end of file + SIGNAL = 4 diff --git a/generated/nidaqmx/task/channels/__init__.py b/generated/nidaqmx/task/channels/__init__.py index 1427c46d1..c9c0a4a88 100644 --- a/generated/nidaqmx/task/channels/__init__.py +++ b/generated/nidaqmx/task/channels/__init__.py @@ -1,9 +1,19 @@ -from nidaqmx.task.channels._channel import Channel +"""NI-DAQmx channel classes.""" + from nidaqmx.task.channels._ai_channel import AIChannel from nidaqmx.task.channels._ao_channel import AOChannel +from nidaqmx.task.channels._channel import Channel from nidaqmx.task.channels._ci_channel import CIChannel from nidaqmx.task.channels._co_channel import COChannel from nidaqmx.task.channels._di_channel import DIChannel from nidaqmx.task.channels._do_channel import DOChannel -__all__ = ['Channel', 'AIChannel', 'AOChannel', 'CIChannel', 'COChannel', 'DIChannel', 'DOChannel',] \ No newline at end of file +__all__ = [ + "Channel", + "AIChannel", + "AOChannel", + "CIChannel", + "COChannel", + "DIChannel", + "DOChannel", +] diff --git a/generated/nidaqmx/task/collections/__init__.py b/generated/nidaqmx/task/collections/__init__.py index 2c93309e5..09748517e 100644 --- a/generated/nidaqmx/task/collections/__init__.py +++ b/generated/nidaqmx/task/collections/__init__.py @@ -1,9 +1,19 @@ -from nidaqmx.task.collections._channel_collection import ChannelCollection +"""NI-DAQmx channel collection classes.""" + from nidaqmx.task.collections._ai_channel_collection import AIChannelCollection from nidaqmx.task.collections._ao_channel_collection import AOChannelCollection +from nidaqmx.task.collections._channel_collection import ChannelCollection from nidaqmx.task.collections._ci_channel_collection import CIChannelCollection from nidaqmx.task.collections._co_channel_collection import COChannelCollection from nidaqmx.task.collections._di_channel_collection import DIChannelCollection from nidaqmx.task.collections._do_channel_collection import DOChannelCollection -__all__ = ['ChannelCollection', 'AIChannelCollection', 'AOChannelCollection', 'CIChannelCollection', 'COChannelCollection', 'DIChannelCollection', 'DOChannelCollection',] \ No newline at end of file +__all__ = [ + "ChannelCollection", + "AIChannelCollection", + "AOChannelCollection", + "CIChannelCollection", + "COChannelCollection", + "DIChannelCollection", + "DOChannelCollection", +] diff --git a/generated/nidaqmx/task/collections/_channel_collection.py b/generated/nidaqmx/task/collections/_channel_collection.py index e8d4cb0c9..a42200f53 100644 --- a/generated/nidaqmx/task/collections/_channel_collection.py +++ b/generated/nidaqmx/task/collections/_channel_collection.py @@ -1,25 +1,25 @@ from collections.abc import Sequence -from nidaqmx.task.channels._channel import Channel -from nidaqmx.errors import DaqError from nidaqmx.error_codes import DAQmxErrors -from nidaqmx.utils import unflatten_channel_string, flatten_channel_string +from nidaqmx.errors import DaqError +from nidaqmx.task.channels._channel import Channel +from nidaqmx.utils import flatten_channel_string, unflatten_channel_string class ChannelCollection(Sequence): - """ - Contains the collection of channels for a DAQmx Task. - + """Contains the collection of channels for a DAQmx Task. + This class defines methods that implements a container object. """ + def __init__(self, task_handle, interpreter): - """ - Do not construct this object directly; instead, construct a nidaqmx.Task and use the appropriate property, such as task.ai_channels. - """ + """Do not construct this object directly; instead, construct a nidaqmx.Task and use the appropriate property, such as task.ai_channels.""" # noqa: W505 - doc line too long (146 > 100 characters) (auto-generated noqa) self._handle = task_handle self._interpreter = interpreter - def __contains__(self, item): + def __contains__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, item + ): channel_names = self.channel_names if isinstance(item, str): @@ -29,14 +29,13 @@ def __contains__(self, item): return all([item in channel_names for item in items]) - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return self._handle == other._handle return False def __getitem__(self, index): - """ - Indexes a subset of virtual channels on this channel collection. + """Indexes a subset of virtual channels on this channel collection. Args: index: The value of the index. The following index types are @@ -49,9 +48,10 @@ def __getitem__(self, index): - int: Index/position of the virtual channel in the collection. - slice: Range of the indexes/positions of virtual channels in the collection. + Returns: - nidaqmx.task.channels.Channel: - + nidaqmx.task.channels.Channel: + Indicates a channel object representing the subset of virtual channels indexed. """ @@ -63,30 +63,33 @@ def __getitem__(self, index): channel_names = index else: raise DaqError( - 'Invalid index type "{}" used to access channels.' - .format(type(index)), DAQmxErrors.UNKNOWN) + 'Invalid index type "{}" used to access channels.'.format(type(index)), + DAQmxErrors.UNKNOWN, + ) if channel_names: return Channel._factory(self._handle, channel_names, self._interpreter) else: raise DaqError( - 'You cannot specify an empty index when indexing channels.\n' - 'Index used: {}'.format(index), DAQmxErrors.UNKNOWN) + "You cannot specify an empty index when indexing channels.\n" + "Index used: {}".format(index), + DAQmxErrors.UNKNOWN, + ) - def __hash__(self): + def __hash__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return self._interpreter.hash_task_handle(self._handle) - def __iter__(self): + def __iter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) for channel_name in self.channel_names: yield Channel._factory(self._handle, channel_name, self._interpreter) - def __len__(self): + def __len__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return len(self.channel_names) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __reversed__(self): + def __reversed__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) channel_names = self.channel_names channel_names.reverse() @@ -95,19 +98,12 @@ def __reversed__(self): @property def all(self): - """ - :class:`nidaqmx.task.channels.Channel`: - Specifies a channel object that represents the entire list of - virtual channels on this channel collection. - """ + """:class:`nidaqmx.task.channels.Channel`: Specifies a channel object that represents the entire list of virtual channels on this channel collection.""" # noqa: W505 - doc line too long (160 > 100 characters) (auto-generated noqa) # Passing a blank string means all channels. - return Channel._factory(self._handle, '', self._interpreter) + return Channel._factory(self._handle, "", self._interpreter) @property def channel_names(self): - """ - List[str]: Specifies the entire list of virtual channels on this - channel collection. - """ + """List[str]: Specifies the entire list of virtual channels on this channel collection.""" val = self._interpreter.get_task_attribute_string(self._handle, 0x1273) return unflatten_channel_string(val) diff --git a/generated/nidaqmx/task/triggering/__init__.py b/generated/nidaqmx/task/triggering/__init__.py index b1d4de025..e4359185d 100644 --- a/generated/nidaqmx/task/triggering/__init__.py +++ b/generated/nidaqmx/task/triggering/__init__.py @@ -1,8 +1,17 @@ -from nidaqmx.task.triggering._triggers import Triggers +"""NI-DAQmx task triggering classes.""" + from nidaqmx.task.triggering._arm_start_trigger import ArmStartTrigger from nidaqmx.task.triggering._handshake_trigger import HandshakeTrigger from nidaqmx.task.triggering._pause_trigger import PauseTrigger from nidaqmx.task.triggering._reference_trigger import ReferenceTrigger from nidaqmx.task.triggering._start_trigger import StartTrigger +from nidaqmx.task.triggering._triggers import Triggers -__all__ = ['Triggers', 'ArmStartTrigger', 'HandshakeTrigger', 'PauseTrigger', 'ReferenceTrigger', 'StartTrigger'] \ No newline at end of file +__all__ = [ + "Triggers", + "ArmStartTrigger", + "HandshakeTrigger", + "PauseTrigger", + "ReferenceTrigger", + "StartTrigger", +] diff --git a/generated/nidaqmx/types.py b/generated/nidaqmx/types.py index 12955c5ff..42a67e2f9 100644 --- a/generated/nidaqmx/types.py +++ b/generated/nidaqmx/types.py @@ -1,62 +1,63 @@ +"""NI-DAQmx data types.""" + import collections import typing # region Task Counter IO namedtuples -CtrFreq = collections.namedtuple( - 'CtrFreq', ['freq', 'duty_cycle']) +CtrFreq = collections.namedtuple("CtrFreq", ["freq", "duty_cycle"]) -CtrTick = collections.namedtuple( - 'CtrTick', ['high_tick', 'low_tick']) +CtrTick = collections.namedtuple("CtrTick", ["high_tick", "low_tick"]) -CtrTime = collections.namedtuple( - 'CtrTime', ['high_time', 'low_time']) +CtrTime = collections.namedtuple("CtrTime", ["high_time", "low_time"]) # endregion # region Power IO namedtuples -PowerMeasurement = collections.namedtuple( - 'PowerMeasurement', ['voltage', 'current']) +PowerMeasurement = collections.namedtuple("PowerMeasurement", ["voltage", "current"]) # endregion # region Watchdog namedtuples AOExpirationState = collections.namedtuple( - 'AOExpirationState', - ['physical_channel', 'expiration_state', 'output_type']) + "AOExpirationState", ["physical_channel", "expiration_state", "output_type"] +) COExpirationState = collections.namedtuple( - 'COExpirationState', ['physical_channel', 'expiration_state']) + "COExpirationState", ["physical_channel", "expiration_state"] +) DOExpirationState = collections.namedtuple( - 'DOExpirationState', ['physical_channel', 'expiration_state']) + "DOExpirationState", ["physical_channel", "expiration_state"] +) # endregion # region Power Up States namedtuples AOPowerUpState = collections.namedtuple( - 'AOPowerUpState', ['physical_channel', 'power_up_state', 'channel_type']) + "AOPowerUpState", ["physical_channel", "power_up_state", "channel_type"] +) -DOPowerUpState = collections.namedtuple( - 'DOPowerUpState', ['physical_channel', 'power_up_state']) +DOPowerUpState = collections.namedtuple("DOPowerUpState", ["physical_channel", "power_up_state"]) DOResistorPowerUpState = collections.namedtuple( - 'DOResistorPowerUpState', ['physical_channel', 'power_up_state']) + "DOResistorPowerUpState", ["physical_channel", "power_up_state"] +) # endregion # region System namedtuples -CDAQSyncConnection = collections.namedtuple( - 'CDAQSyncConnection', ['output_port', 'input_port']) +CDAQSyncConnection = collections.namedtuple("CDAQSyncConnection", ["output_port", "input_port"]) # endregion # region ID Pin namedtuples + class IDPinContents(typing.NamedTuple): """IDPinContents represent the contents of the memory connected to the ID pin.""" @@ -66,4 +67,5 @@ class IDPinContents(typing.NamedTuple): format_code: int """The format code of the binary data.""" + # endregion diff --git a/generated/nidaqmx/utils.py b/generated/nidaqmx/utils.py index 72de56a1a..3eb25f7b1 100644 --- a/generated/nidaqmx/utils.py +++ b/generated/nidaqmx/utils.py @@ -1,13 +1,13 @@ +"""NI-DAQmx utility functions.""" + from __future__ import annotations import re from dataclasses import dataclass -from typing import List, Optional +from nidaqmx._base_interpreter import BaseInterpreter from nidaqmx.errors import DaqError from nidaqmx.grpc_session_options import GrpcSessionOptions -from nidaqmx._base_interpreter import BaseInterpreter - # Method logic adapted from # //Measurements/Infrastructure/dmxf/trunk/2.5/source/nimuck/parseUtilities.cpp @@ -18,7 +18,8 @@ "every colon (':') in the input string. Or, if a name is specified after " "the colon, it must be identical to the name specified immediately before " "the colon. Colons are not allowed within the names of the individual " - "objects.") + "objects." +) @dataclass @@ -40,8 +41,7 @@ def to_flattened_name(self) -> str: def flatten_channel_string(channel_names: list[str]) -> str: - """ - Converts a list of channel names to a comma-delimited list of names. + """Converts a list of channel names to a comma-delimited list of names. You can use this method to convert a list of physical or virtual channel names to a single string prior to using the DAQmx Create Channel methods or @@ -56,6 +56,7 @@ def flatten_channel_string(channel_names: list[str]) -> str: Args: channel_names: The list of physical or virtual channel names. + Returns: The resulting comma-delimited list of physical or virtual channel names. """ @@ -67,7 +68,7 @@ def flatten_channel_string(channel_names: list[str]) -> str: flattened_channel_list = [] previous = _ChannelInfo() for channel_name in unflattened_channel_names: - m = re.search('(.*[^0-9])?([0-9]+)$', channel_name) + m = re.search("(.*[^0-9])?([0-9]+)$", channel_name) if not m: # If the channel name doesn't end in a valid number, just use the # channel name as-is. @@ -81,10 +82,15 @@ def flatten_channel_string(channel_names: list[str]) -> str: current_index = int(current_index_str) if current_base_name == previous.base_name and ( - (current_index == previous.end_index + 1 and - previous.end_index >= previous.start_index) or - (current_index == previous.end_index - 1 and - previous.end_index <= previous.start_index)): + ( + current_index == previous.end_index + 1 + and previous.end_index >= previous.start_index + ) + or ( + current_index == previous.end_index - 1 + and previous.end_index <= previous.start_index + ) + ): # If the current channel name has the same base name as the # previous and it's end index differs by 1, change the end # index value. It gets flattened later. @@ -96,11 +102,11 @@ def flatten_channel_string(channel_names: list[str]) -> str: # get flattened with the previous channel. flattened_channel_list.append(previous.to_flattened_name()) previous = _ChannelInfo( - current_base_name, - current_index, - current_index_str, - current_index, - current_index_str + current_base_name, + current_index, + current_index_str, + current_index, + current_index_str, ) # Convert the final channel dictionary to a flattened string @@ -108,12 +114,11 @@ def flatten_channel_string(channel_names: list[str]) -> str: # Remove empty strings in list, convert to comma-delimited string, then trim # whitespace. - return ','.join([_f for _f in flattened_channel_list if _f]).strip() + return ",".join([_f for _f in flattened_channel_list if _f]).strip() + - def unflatten_channel_string(channel_names: str) -> list[str]: - """ - Converts a comma-delimited list of channel names to a list of names. + """Converts a comma-delimited list of channel names to a list of names. You can use this method to convert a comma-delimited list or range of physical or virtual channels into a list of physical or virtual channel @@ -128,36 +133,33 @@ def unflatten_channel_string(channel_names: str) -> list[str]: Args: channel_names: The list or range of physical or virtual channels. - + Returns: - The list of physical or virtual channel names. - + The list of physical or virtual channel names. + Each element of the list contains a single channel. """ channel_list_to_return = [] - channel_list = [c for c in channel_names.strip().split(',') if c] + channel_list = [c for c in channel_names.strip().split(",") if c] for channel in channel_list: channel = channel.strip() - colon_index = channel.find(':') + colon_index = channel.find(":") if colon_index == -1: channel_list_to_return.append(channel) else: before = channel[:colon_index] - after = channel[colon_index+1:] + after = channel[colon_index + 1 :] - m_before = re.match('(.*?)([0-9]+)$', before) - m_after = re.match('(.*?)([0-9]+)$', after) + m_before = re.match("(.*?)([0-9]+)$", before) + m_after = re.match("(.*?)([0-9]+)$", after) if not m_before or not m_after: - raise DaqError(_invalid_range_syntax_message, - error_code=-200498) + raise DaqError(_invalid_range_syntax_message, error_code=-200498) - if m_after.group(1) and ( - m_before.group(1).lower() != m_after.group(1).lower()): - raise DaqError(_invalid_range_syntax_message, - error_code=-200498) + if m_after.group(1) and (m_before.group(1).lower() != m_after.group(1).lower()): + raise DaqError(_invalid_range_syntax_message, error_code=-200498) num_before_str = m_before.group(2) num_before = int(num_before_str) @@ -168,7 +170,7 @@ def unflatten_channel_string(channel_names: str) -> list[str]: # If there are any leading 0s in the first number, we want to ensure # match that width. This is established precedence in the DAQmx # algorithm. - if num_before > 0 and len(num_before_str.lstrip('0')) < len(num_before_str): + if num_before > 0 and len(num_before_str.lstrip("0")) < len(num_before_str): num_min_width = len(num_before_str) num_max = max([num_before, num_after]) @@ -176,8 +178,7 @@ def unflatten_channel_string(channel_names: str) -> list[str]: number_of_channels = (num_max - num_min) + 1 if number_of_channels >= 15000: - raise DaqError(_invalid_range_syntax_message, - error_code=-200498) + raise DaqError(_invalid_range_syntax_message, error_code=-200498) colon_expanded_channel = [] for i in range(number_of_channels): @@ -199,15 +200,16 @@ def unflatten_channel_string(channel_names: str) -> list[str]: def _select_interpreter( - grpc_options: GrpcSessionOptions | None = None, - interpreter: BaseInterpreter | None = None + grpc_options: GrpcSessionOptions | None = None, interpreter: BaseInterpreter | None = None ) -> BaseInterpreter: if interpreter: return interpreter else: if grpc_options: from nidaqmx._grpc_interpreter import GrpcStubInterpreter + return GrpcStubInterpreter(grpc_options) else: from nidaqmx._library_interpreter import LibraryInterpreter + return LibraryInterpreter() diff --git a/pyproject.toml b/pyproject.toml index 64a092cca..765848f5e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -116,10 +116,10 @@ nidaqmx = 'nidaqmx.__main__:main' [tool.black] line-length = 100 -extend_exclude = ".tox/|docs/|generated/|src/codegen/metadata/|src/codegen/templates/|src/handwritten/" +extend_exclude = ".tox/|docs/|generated/|src/codegen/metadata/|src/codegen/templates/" [tool.ni-python-styleguide] -extend_exclude = ".tox,docs,generated,src/codegen/metadata,src/codegen/templates,src/handwritten" +extend_exclude = ".tox,docs,generated,src/codegen/metadata,src/codegen/templates" [tool.pytest.ini_options] addopts = "--doctest-modules --strict-markers" diff --git a/src/handwritten/__init__.py b/src/handwritten/__init__.py index ec8ff6ed7..455cd5aee 100644 --- a/src/handwritten/__init__.py +++ b/src/handwritten/__init__.py @@ -1,5 +1,13 @@ -from nidaqmx.errors import DaqError, DaqReadError, DaqWriteError, DaqWarning, DaqResourceWarning -from nidaqmx.grpc_session_options import * +"""The NI-DAQmx API for Python.""" + +from nidaqmx.errors import ( + DaqError, + DaqReadError, + DaqResourceWarning, + DaqWarning, + DaqWriteError, +) +from nidaqmx.grpc_session_options import * # noqa: F403 - 'from nidaqmx.grpc_session_options import *' used; unable to detect undefined names (auto-generated noqa) from nidaqmx.scale import Scale from nidaqmx.task import Task from nidaqmx.types import CtrFreq, CtrTick, CtrTime @@ -11,7 +19,13 @@ __version__ = version(__name__) -__all__ = ["errors", "scale", "stream_readers", "stream_writers", "task"] +__all__ = [ # noqa: F405 - 'errors' may be undefined, or defined from star imports: nidaqmx.grpc_session_options (auto-generated noqa) + "errors", + "scale", + "stream_readers", + "stream_writers", + "task", +] # Do not add a null logging handler. If the application has not configured logging, the # default behavior is to log warnings and errors to stderr. diff --git a/src/handwritten/__main__.py b/src/handwritten/__main__.py index e0baada58..5bf245291 100644 --- a/src/handwritten/__main__.py +++ b/src/handwritten/__main__.py @@ -1,7 +1,8 @@ +"""'nidaqmx' command line utility.""" + from __future__ import annotations import logging -from typing import Optional import click @@ -16,12 +17,14 @@ count=True, help="Enable verbose logging. Repeat to increase verbosity.", ) -def main(verbosity: int) -> None: +def main( # noqa: D103 - Missing docstring in public function (auto-generated noqa) + verbosity: int, +) -> None: _configure_logging(verbosity) @main.command() -def installdriver(): +def installdriver(): # noqa: D103 - Missing docstring in public function (auto-generated noqa) _install_daqmx.installdriver() diff --git a/src/handwritten/_bitfield_utils.py b/src/handwritten/_bitfield_utils.py index eb04a4bcc..64494f82f 100644 --- a/src/handwritten/_bitfield_utils.py +++ b/src/handwritten/_bitfield_utils.py @@ -1,41 +1,38 @@ -def enum_bitfield_to_list(bitfield_value, bitfield_enum_type, - actual_enum_type): - """ - Converts a bitfield value to a list of enums. +def enum_bitfield_to_list(bitfield_value, bitfield_enum_type, actual_enum_type): + """Converts a bitfield value to a list of enums. Args: bitfield_value (int): Specifies the value of the bitfield. bitfield_enum_type (enum.Enum): Specifies the bitfield enum type from which to mask and extract the enum values. actual_enum_type (enum.Enum): Specifies the actual enum type. + Returns: List[enum.Enum]: Indicates the converted list of enums. """ supported_values = [] for bitfield_mask in bitfield_enum_type: if bitfield_value & bitfield_mask.value: - enum_value = next( - e for e in actual_enum_type if e.name == bitfield_mask.name) + enum_value = next(e for e in actual_enum_type if e.name == bitfield_mask.name) supported_values.append(enum_value) return supported_values def enum_list_to_bitfield(enum_list, bitfield_enum_type): - """ - Converts a list of enums to a bitfield value. + """Converts a list of enums to a bitfield value. Args: enum_list (List[enum.Enum]): Specifies the list of enums. bitfield_enum_type (enum.Enum): Specifies the bitfield enum type from which to mask and extract the enum values. + Returns: int: Indicates the value of the bitfield. """ bitfield_value = 0 for enum_value in enum_list: - bitfield_mask = next( - b for b in bitfield_enum_type if b.name == enum_value.name) + bitfield_mask = next(b for b in bitfield_enum_type if b.name == enum_value.name) bitfield_value |= bitfield_mask.value - return bitfield_value \ No newline at end of file + return bitfield_value diff --git a/src/handwritten/_dotenvpath.py b/src/handwritten/_dotenvpath.py index af092820d..19cad5a2d 100644 --- a/src/handwritten/_dotenvpath.py +++ b/src/handwritten/_dotenvpath.py @@ -70,4 +70,4 @@ def _get_package_path() -> Path: """Get the path of this package.""" module = sys.modules[__package__] assert module.__file__ and module.__file__.endswith("__init__.py") - return Path(module.__file__).parent \ No newline at end of file + return Path(module.__file__).parent diff --git a/src/handwritten/_feature_toggles.py b/src/handwritten/_feature_toggles.py index 20505ff59..9484031a6 100644 --- a/src/handwritten/_feature_toggles.py +++ b/src/handwritten/_feature_toggles.py @@ -4,9 +4,11 @@ import functools import sys -from decouple import AutoConfig, Undefined, undefined from enum import Enum from typing import TYPE_CHECKING, Callable, TypeVar + +from decouple import AutoConfig, Undefined, undefined + from nidaqmx._dotenvpath import get_dotenv_search_path from nidaqmx.errors import FeatureNotSupportedError @@ -36,6 +38,7 @@ def _config( cast: Callable[[str], _T] | Undefined = undefined, ) -> _T: ... + # Based on the recipe at https://docs.python.org/3/howto/enum.html class _OrderedEnum(Enum): def __ge__(self, other: Self) -> bool: @@ -156,4 +159,4 @@ def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T: # Define feature toggle constants here: # -------------------------------------- -WAVEFORM_SUPPORT = FeatureToggle("WAVEFORM_SUPPORT", CodeReadiness.INCOMPLETE) \ No newline at end of file +WAVEFORM_SUPPORT = FeatureToggle("WAVEFORM_SUPPORT", CodeReadiness.INCOMPLETE) diff --git a/src/handwritten/_grpc_time.py b/src/handwritten/_grpc_time.py index 77a818d43..9d56047d5 100644 --- a/src/handwritten/_grpc_time.py +++ b/src/handwritten/_grpc_time.py @@ -1,14 +1,11 @@ from __future__ import annotations -from datetime import timezone -from datetime import datetime as std_datetime -from datetime import tzinfo as dt_tzinfo -from hightime import datetime as ht_datetime -from hightime import timedelta as ht_timedelta -from typing import Optional, Union -from nidaqmx._time import _convert_to_desired_timezone +from datetime import datetime as std_datetime, timezone, tzinfo as dt_tzinfo from google.protobuf.timestamp_pb2 import Timestamp as GrpcTimestamp +from hightime import datetime as ht_datetime, timedelta as ht_timedelta + +from nidaqmx._time import _convert_to_desired_timezone # 66 years, 17 leap days = 24107 days = 2082844800 seconds _BIAS_FROM_1970_EPOCH = 2082844800 @@ -22,7 +19,10 @@ _EPOCH_1970 = ht_datetime(1970, 1, 1, tzinfo=timezone.utc) -def convert_time_to_timestamp(dt: std_datetime | ht_datetime, ts: GrpcTimestamp | None = None) -> GrpcTimestamp: + +def convert_time_to_timestamp( # noqa: D103 - Missing docstring in public function (auto-generated noqa) + dt: std_datetime | ht_datetime, ts: GrpcTimestamp | None = None +) -> GrpcTimestamp: seconds_since_1970 = 0 if ts is None: @@ -44,10 +44,13 @@ def convert_time_to_timestamp(dt: std_datetime | ht_datetime, ts: GrpcTimestamp ts.FromNanoseconds(seconds_since_1970 * _NS_PER_S + nanos) return ts -def convert_timestamp_to_time(ts: GrpcTimestamp, tzinfo: dt_tzinfo | None = None) -> ht_datetime: + +def convert_timestamp_to_time( # noqa: D103 - Missing docstring in public function (auto-generated noqa) + ts: GrpcTimestamp, tzinfo: dt_tzinfo | None = None +) -> ht_datetime: total_nanos = ts.ToNanoseconds() seconds, nanos = divmod(total_nanos, _NS_PER_S) # Convert the nanoseconds to yoctoseconds. total_yoctoseconds = int(round(_YS_PER_NS * nanos)) - dt = _EPOCH_1970 + ht_timedelta(seconds = seconds) + ht_timedelta(yoctoseconds=total_yoctoseconds) + dt = _EPOCH_1970 + ht_timedelta(seconds=seconds) + ht_timedelta(yoctoseconds=total_yoctoseconds) return _convert_to_desired_timezone(dt, tzinfo) diff --git a/src/handwritten/_install_daqmx.py b/src/handwritten/_install_daqmx.py index d63971ec1..97ca0bc76 100644 --- a/src/handwritten/_install_daqmx.py +++ b/src/handwritten/_install_daqmx.py @@ -1,24 +1,20 @@ from __future__ import annotations import contextlib -import errno import importlib.resources as pkg_resources import json import logging import os -import pathlib import re -import shutil import subprocess # nosec: B404 import sys import tempfile -import traceback -import requests import zipfile -from typing import Generator, List, Optional, Tuple +from typing import Generator from urllib.parse import urlparse import click +import requests if sys.platform.startswith("win"): import winreg @@ -37,8 +33,7 @@ def _parse_version(version: str) -> tuple[int, ...]: - """ - Split the version string into a tuple of integers. + """Split the version string into a tuple of integers. >>> _parse_version("23.8.0") (23, 8, 0) @@ -57,10 +52,7 @@ def _parse_version(version: str) -> tuple[int, ...]: def _get_daqmx_installed_version() -> str | None: - """ - Check for existing installation of NI-DAQmx. - - """ + """Check for existing installation of NI-DAQmx.""" if sys.platform.startswith("win"): try: _logger.debug("Reading the registry entries to get installed DAQmx version") @@ -101,7 +93,9 @@ def _get_daqmx_installed_version() -> str | None: commands_info = LINUX_COMMANDS[distribution] query_command = commands_info.get_daqmx_version # Run the package query command defined by _linux_installation_commands.py. - query_output = subprocess.run(query_command, stdout=subprocess.PIPE, text=True).stdout # nosec: B603 + query_output = subprocess.run( + query_command, stdout=subprocess.PIPE, text=True + ).stdout # nosec: B603 if distribution == "ubuntu": version_match = re.search(r"ii\s+ni-daqmx\s+(\d+\.\d+\.\d+)", query_output) @@ -127,13 +121,8 @@ def _get_daqmx_installed_version() -> str | None: # Creating a temp file that we then close and yield - this is used to allow subprocesses to access @contextlib.contextmanager -def _multi_access_temp_file( - *, suffix: str = ".exe", delete: bool = True -) -> Generator[str]: - """ - Context manager for creating a temporary file. - - """ +def _multi_access_temp_file(*, suffix: str = ".exe", delete: bool = True) -> Generator[str]: + """Context manager for creating a temporary file.""" try: temp_file = tempfile.NamedTemporaryFile(suffix=suffix, delete=False, mode="w") temp_file.close() @@ -161,8 +150,7 @@ def _multi_access_temp_file( def _load_data( json_data: str, platform: str ) -> tuple[str | None, str | None, str | None, list[str] | None]: - """ - Load data from JSON string and extract Windows metadata. + """Load data from JSON string and extract Windows metadata. >>> json_data = '{"Windows": [{"Location": "path/to/windows/driver", "Version": "24.0", "Release": "2024Q1", "supportedOS": ["Windows 11"]}], "Linux": []}' >>> _load_data(json_data, "Windows") @@ -188,7 +176,7 @@ def _load_data( Traceback (most recent call last): click.exceptions.ClickException: Unsupported os 'macOS' - """ + """ # noqa: W505 - doc line too long (159 > 100 characters) (auto-generated noqa) try: if platform == "Windows": metadata = json.loads(json_data).get("Windows", []) @@ -214,10 +202,7 @@ def _load_data( def _get_driver_details( platform: str, ) -> tuple[str | None, str | None, str | None, list[str] | None]: - """ - Parse the JSON data and retrieve the download link and version information. - - """ + """Parse the JSON data and retrieve the download link and version information.""" try: with pkg_resources.open_text(__package__, METADATA_FILE) as json_file: _logger.debug("Opening the metadata file %s.", METADATA_FILE) @@ -234,17 +219,14 @@ def _get_driver_details( def _install_daqmx_driver_windows_core(download_url: str) -> None: - """ - Download and launch NI-DAQmx Driver installation in an interactive mode - - """ + """Download and launch NI-DAQmx Driver installation in an interactive mode.""" _validate_download_url(download_url) try: with _multi_access_temp_file() as temp_file: _logger.info("Downloading Driver to %s", temp_file) response = requests.get(download_url, timeout=_NETWORK_TIMEOUT_IN_SECONDS) response.raise_for_status() - with open(temp_file, 'wb') as f: + with open(temp_file, "wb") as f: f.write(response.content) _logger.info("Installing NI-DAQmx") # Run the installer that we just downloaded from https://download.ni.com. @@ -263,10 +245,7 @@ def _install_daqmx_driver_windows_core(download_url: str) -> None: def _install_daqmx_driver_linux_core(download_url: str, release: str) -> None: - """ - Download NI Linux Device Drivers and install NI-DAQmx on Linux OS - - """ + """Download NI Linux Device Drivers and install NI-DAQmx on Linux OS.""" if sys.platform.startswith("linux"): _validate_download_url(download_url) try: @@ -274,7 +253,7 @@ def _install_daqmx_driver_linux_core(download_url: str, release: str) -> None: _logger.info("Downloading Driver to %s", temp_file) response = requests.get(download_url, timeout=_NETWORK_TIMEOUT_IN_SECONDS) response.raise_for_status() - with open(temp_file, 'wb') as f: + with open(temp_file, "wb") as f: f.write(response.content) with tempfile.TemporaryDirectory() as temp_folder: @@ -330,10 +309,7 @@ def _validate_download_url(download_url: str) -> None: def _ask_user_confirmation(user_message: str) -> bool: - """ - Prompt for user confirmation - - """ + """Prompt for user confirmation.""" while True: response = input(user_message + " (yes/no): ").strip().lower() if response in ["yes", "y"]: @@ -349,10 +325,7 @@ def _upgrade_daqmx_user_confirmation( latest_version: str, release: str, ) -> bool: - """ - Confirm with the user and return the user response. - - """ + """Confirm with the user and return the user response.""" _logger.debug("Entering _upgrade_daqmx_user_confirmation") installed_parts = _parse_version(installed_version) latest_parts = _parse_version(latest_version) @@ -371,10 +344,7 @@ def _fresh_install_daqmx_user_confirmation( latest_version: str, release: str, ) -> bool: - """ - Confirm with the user and return the user response. - - """ + """Confirm with the user and return the user response.""" _logger.debug("Entering _fresh_install_daqmx_user_confirmation") return _ask_user_confirmation( f"Latest NI-DAQmx version available is {latest_version} ({release}). Do you want to install?" @@ -382,10 +352,7 @@ def _fresh_install_daqmx_user_confirmation( def _is_distribution_supported() -> None: - """ - Raises an exception if the linux distribution and its version are not supported. - - """ + """Raises an exception if the linux distribution and its version are not supported.""" if sys.platform.startswith("linux"): dist_name = distro.id() dist_version = distro.version() @@ -409,10 +376,7 @@ def _is_distribution_supported() -> None: def _install_daqmx_driver(): - """ - Install the NI-DAQmx driver. - - """ + """Install the NI-DAQmx driver.""" if sys.platform.startswith("win"): _logger.info("Windows platform detected") platform = "Windows" @@ -443,9 +407,7 @@ def _install_daqmx_driver(): installed_version, latest_version, release ) else: - user_response = _fresh_install_daqmx_user_confirmation( - latest_version, release - ) + user_response = _fresh_install_daqmx_user_confirmation(latest_version, release) if user_response: if platform == "Linux": @@ -455,10 +417,7 @@ def _install_daqmx_driver(): def installdriver() -> None: - """ - Download and launch NI-DAQmx Driver installation in an interactive mode. - - """ + """Download and launch NI-DAQmx Driver installation in an interactive mode.""" try: _install_daqmx_driver() except click.ClickException: diff --git a/src/handwritten/_lib.py b/src/handwritten/_lib.py index b68489678..8fccba52b 100644 --- a/src/handwritten/_lib.py +++ b/src/handwritten/_lib.py @@ -1,35 +1,45 @@ from __future__ import annotations -from ctypes.util import find_library import ctypes -from numpy.ctypeslib import ndpointer -import platform +import locale import sys import threading -import locale +from ctypes.util import find_library +from typing import TYPE_CHECKING, cast + from decouple import config -from typing import cast, TYPE_CHECKING +from numpy.ctypeslib import ndpointer -from nidaqmx.errors import DaqNotFoundError, DaqNotSupportedError, DaqFunctionNotSupportedError +from nidaqmx.errors import ( + DaqFunctionNotSupportedError, + DaqNotFoundError, + DaqNotSupportedError, +) if TYPE_CHECKING: from typing_extensions import TypeAlias -_DAQ_NOT_FOUND_MESSAGE = "Could not find an installation of NI-DAQmx. Please ensure that NI-DAQmx " \ - "is installed on this machine or contact National Instruments for support." +_DAQ_NOT_FOUND_MESSAGE = ( + "Could not find an installation of NI-DAQmx. Please ensure that NI-DAQmx " + "is installed on this machine or contact National Instruments for support." +) -_DAQ_NOT_SUPPORTED_MESSAGE = "NI-DAQmx Python is not supported on this platform: {0}. Please " \ - "direct any questions or feedback to National Instruments." +_DAQ_NOT_SUPPORTED_MESSAGE = ( + "NI-DAQmx Python is not supported on this platform: {0}. Please " + "direct any questions or feedback to National Instruments." +) -_FUNCTION_NOT_SUPPORTED_MESSAGE = "The NI-DAQmx function \"{0}\" is not supported in this version " \ - "of NI-DAQmx. Visit ni.com/downloads to upgrade." +_FUNCTION_NOT_SUPPORTED_MESSAGE = ( + 'The NI-DAQmx function "{0}" is not supported in this version ' + "of NI-DAQmx. Visit ni.com/downloads to upgrade." +) -class c_bool32(ctypes.c_uint): - """ - Specifies a custom ctypes data type to represent 32-bit booleans. - """ +class c_bool32( # noqa: N801 - class name 'c_bool32' should use CapWords convention (auto-generated noqa) + ctypes.c_uint +): + """Specifies a custom ctypes data type to represent 32-bit booleans.""" # typeshed specifies that _SimpleCData[_T].value is an instance variable with type _T, so # accessing it with the descriptor protocol via its class results in "error: Access to generic @@ -47,12 +57,12 @@ def _setter(self, val): class CtypesByteString: - """ - Custom argtype that automatically converts unicode strings to encoding - used by the DAQmx C API DLL in Python 3. - """ + """Custom argtype that automatically converts unicode strings to encoding used by the C API.""" + @classmethod - def from_param(cls, param): + def from_param( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + cls, param + ): if isinstance(param, str): param = param.encode(lib_importer.encoding) return ctypes.c_char_p(param) @@ -62,9 +72,7 @@ def from_param(cls, param): def wrapped_ndpointer(*args, **kwargs): - """ - Specifies an ndpointer type that wraps numpy.ctypeslib.ndpointer and - allows a value of None to be passed to an argument of that type. + """Wraps numpy.ctypeslib.ndpointer in order to allow passing None. Taken from http://stackoverflow.com/questions/32120178 """ @@ -75,28 +83,29 @@ def from_param(cls, obj): return obj return base.from_param(obj) - return type(base.__name__, (base,), - {'from_param': classmethod(from_param)}) + return type(base.__name__, (base,), {"from_param": classmethod(from_param)}) class DaqFunctionImporter: - """ - Wraps the function getter function of a ctypes library. + """Wraps the function getter function of a ctypes library. Allows the NI-DAQmx Python API to fail elegantly if a function is not supported in the current version of the API. """ def __init__(self, library): + """Initialize a new DaqFunctionImporter.""" self._library = library self._lib_lock = threading.Lock() - def __getattr__(self, function): + def __getattr__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, function + ): try: cfunc = getattr(self._library, function) - if not hasattr(cfunc, 'arglock'): + if not hasattr(cfunc, "arglock"): with self._lib_lock: - if not hasattr(cfunc, 'arglock'): + if not hasattr(cfunc, "arglock"): cfunc.arglock = threading.Lock() return cfunc except AttributeError: @@ -121,19 +130,16 @@ def __getattr__(self, function): def get_encoding_from_locale() -> str: - """ - Gets the current locale encoding handling cases where it is unset. - """ + """Gets the current locale encoding handling cases where it is unset.""" _, encoding = locale.getlocale() - return encoding or 'ascii' + return encoding or "ascii" class DaqLibImporter: - """ - Encapsulates NI-DAQmx library importing and handle type parsing logic. - """ + """Encapsulates NI-DAQmx library importing and handle type parsing logic.""" def __init__(self): + """Initialize a new DaqLibImporter.""" self._windll = None self._cdll = None self._cal_handle = None @@ -141,35 +147,37 @@ def __init__(self): self._encoding = None @property - def windll(self): + def windll(self): # noqa: D102 - Missing docstring in public method (auto-generated noqa) if self._windll is None: self._import_lib() return self._windll @property - def cdll(self): + def cdll(self): # noqa: D102 - Missing docstring in public method (auto-generated noqa) if self._cdll is None: self._import_lib() return self._cdll @property - def task_handle(self) -> type: + def task_handle( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ) -> type: return TaskHandle @property - def cal_handle(self) -> type: + def cal_handle( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ) -> type: return CalHandle - + @property - def encoding(self): + def encoding(self): # noqa: D102 - Missing docstring in public method (auto-generated noqa) if self._encoding is None: self._import_lib() return self._encoding def _import_lib(self): - """ - Determines the location of and loads the NI-DAQmx CAI DLL. - """ + """Determines the location of and loads the NI-DAQmx CAI DLL.""" self._windll = None self._cdll = None self._encoding = None @@ -178,42 +186,44 @@ def _import_lib(self): cdll = None encoding = None - if sys.platform.startswith('win'): + if sys.platform.startswith("win"): def _load_lib(libname: str): windll = ctypes.windll.LoadLibrary(libname) cdll = ctypes.cdll.LoadLibrary(libname) - return windll, cdll - + return windll, cdll + # Feature Toggle to load nicaiu.dll or nicai_utf8.dll # The Feature Toggle can be set in the .env file - nidaqmx_c_library = config('NIDAQMX_C_LIBRARY', default=None) - + nidaqmx_c_library = config("NIDAQMX_C_LIBRARY", default=None) + if nidaqmx_c_library is not None: - try: - if nidaqmx_c_library=="nicaiu": + try: + if nidaqmx_c_library == "nicaiu": windll, cdll = _load_lib("nicaiu") encoding = get_encoding_from_locale() - elif nidaqmx_c_library=="nicai_utf8": + elif nidaqmx_c_library == "nicai_utf8": windll, cdll = _load_lib("nicai_utf8") - encoding = 'utf-8' + encoding = "utf-8" else: - raise ValueError(f"Unsupported NIDAQMX_C_LIBRARY value: {nidaqmx_c_library}") + raise ValueError( + f"Unsupported NIDAQMX_C_LIBRARY value: {nidaqmx_c_library}" + ) except OSError as e: - raise DaqNotFoundError(_DAQ_NOT_FOUND_MESSAGE) from e + raise DaqNotFoundError(_DAQ_NOT_FOUND_MESSAGE) from e else: try: windll, cdll = _load_lib("nicai_utf8") - encoding = 'utf-8' + encoding = "utf-8" except OSError: # Fallback to nicaiu.dll if nicai_utf8.dll cannot be loaded try: windll, cdll = _load_lib("nicaiu") encoding = get_encoding_from_locale() except OSError as e: - raise DaqNotFoundError(_DAQ_NOT_FOUND_MESSAGE) from e - elif sys.platform.startswith('linux'): - library_path = find_library('nidaqmx') + raise DaqNotFoundError(_DAQ_NOT_FOUND_MESSAGE) from e + elif sys.platform.startswith("linux"): + library_path = find_library("nidaqmx") if library_path is not None: cdll = ctypes.cdll.LoadLibrary(library_path) windll = cdll diff --git a/src/handwritten/_lib_time.py b/src/handwritten/_lib_time.py index 69444a3fb..8af8ebb38 100644 --- a/src/handwritten/_lib_time.py +++ b/src/handwritten/_lib_time.py @@ -2,16 +2,17 @@ import ctypes import functools -from datetime import timezone -from datetime import datetime as std_datetime -from datetime import tzinfo as dt_tzinfo -from hightime import datetime as ht_datetime -from hightime import timedelta as ht_timedelta -from typing import Optional, Union +from datetime import datetime as std_datetime, timezone, tzinfo as dt_tzinfo + +from hightime import datetime as ht_datetime, timedelta as ht_timedelta + from nidaqmx._time import _convert_to_desired_timezone + @functools.total_ordering -class AbsoluteTime(ctypes.Structure): +class AbsoluteTime( # noqa: D101 - Missing docstring in public class (auto-generated noqa) + ctypes.Structure +): # Please visit ni.com/info and enter the Info Code NI_BTF for detailed information. # The summary is: # * lsb - positive fractions (2^-64) of a second @@ -33,9 +34,10 @@ class AbsoluteTime(ctypes.Structure): _EPOCH_1904 = ht_datetime(1904, 1, 1, tzinfo=timezone.utc) - @classmethod - def from_datetime(cls, dt: std_datetime | ht_datetime) -> AbsoluteTime: + def from_datetime( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + cls, dt: std_datetime | ht_datetime + ) -> AbsoluteTime: seconds_since_1904 = 0 # Convert the subseconds. @@ -49,27 +51,37 @@ def from_datetime(cls, dt: std_datetime | ht_datetime) -> AbsoluteTime: ) else: seconds_since_1904 = int((dt - AbsoluteTime._EPOCH_1904).total_seconds()) - lsb = int( - round(AbsoluteTime._NUM_SUBSECONDS * dt.microsecond / AbsoluteTime._US_PER_S) - ) + lsb = int(round(AbsoluteTime._NUM_SUBSECONDS * dt.microsecond / AbsoluteTime._US_PER_S)) return AbsoluteTime(lsb=lsb, msb=seconds_since_1904) - def to_datetime(self, tzinfo: dt_tzinfo | None = None) -> ht_datetime: + def to_datetime( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, tzinfo: dt_tzinfo | None = None + ) -> ht_datetime: total_yoctoseconds = int( round(AbsoluteTime._YS_PER_S * self.lsb / AbsoluteTime._NUM_SUBSECONDS) ) - dt = AbsoluteTime._EPOCH_1904 + ht_timedelta(seconds=self.msb) + ht_timedelta(yoctoseconds=total_yoctoseconds) - return _convert_to_desired_timezone(dt,tzinfo) + dt = ( + AbsoluteTime._EPOCH_1904 + + ht_timedelta(seconds=self.msb) + + ht_timedelta(yoctoseconds=total_yoctoseconds) + ) + return _convert_to_desired_timezone(dt, tzinfo) - def __str__(self) -> str: + def __str__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, + ) -> str: return f"AbsoluteTime(lsb=0x{self.lsb:x}, msb=0x{self.msb:x})" - def __eq__(self, other) -> bool: + def __eq__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, other + ) -> bool: return self.msb == other.msb and self.lsb == other.lsb - def __lt__(self, other) -> bool: + def __lt__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, other + ) -> bool: if self.msb == other.msb: return self.lsb < other.lsb else: - return self.msb < other.msb \ No newline at end of file + return self.msb < other.msb diff --git a/src/handwritten/_linux_installation_commands.py b/src/handwritten/_linux_installation_commands.py index 8e26cd743..cacd90176 100644 --- a/src/handwritten/_linux_installation_commands.py +++ b/src/handwritten/_linux_installation_commands.py @@ -1,7 +1,8 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Callable, Dict, List, Tuple +from typing import Callable + def _get_version_ubuntu(dist_version: str) -> str: return dist_version.replace(".", "") @@ -57,8 +58,9 @@ def _get_version_rhel(dist_version: str) -> str: _DEBIAN_DAQMX_VERSION_COMMAND = ["dpkg", "-l", "ni-daqmx"] _RPM_DAQMX_VERSION_COMMAND = ["rpm", "-q", "ni-daqmx"] + @dataclass -class DistroInfo: +class DistroInfo: # noqa: D101 - Missing docstring in public class (auto-generated noqa) get_distro_version: Callable[[str], str] get_daqmx_version: list[str] install_commands: list[list[str]] @@ -77,10 +79,7 @@ class DistroInfo: def get_linux_installation_commands( _directory_to_extract_to: str, dist_name: str, dist_version: str, _release_string: str ) -> list[list[str]]: - """ - Get the installation commands for Linux based on the distribution. - - """ + """Get the installation commands for Linux based on the distribution.""" if dist_name not in LINUX_COMMANDS: raise ValueError(f"Unsupported distribution '{dist_name}'") diff --git a/src/handwritten/_time.py b/src/handwritten/_time.py index 06edadd50..0acdf7f12 100644 --- a/src/handwritten/_time.py +++ b/src/handwritten/_time.py @@ -1,15 +1,16 @@ from __future__ import annotations -from tzlocal import get_localzone -from datetime import timezone -from datetime import tzinfo as dt_tzinfo -from datetime import datetime as std_datetime -from hightime import datetime as ht_datetime -from typing import Optional, Union +from datetime import datetime as std_datetime, timezone, tzinfo as dt_tzinfo from zoneinfo import ZoneInfo +from hightime import datetime as ht_datetime +from tzlocal import get_localzone + + # theoretically the same as astimezone(), but with support for dates before 1970 -def _convert_to_desired_timezone(expected_time_utc: std_datetime | ht_datetime, tzinfo: dt_tzinfo | None = None) -> std_datetime | ht_datetime: +def _convert_to_desired_timezone( + expected_time_utc: std_datetime | ht_datetime, tzinfo: dt_tzinfo | None = None +) -> std_datetime | ht_datetime: # if timezone matches, no need to do conversion if expected_time_utc.tzinfo is tzinfo: return expected_time_utc @@ -22,9 +23,9 @@ def _convert_to_desired_timezone(expected_time_utc: std_datetime | ht_datetime, if isinstance(tzinfo, ZoneInfo): localized_time = expected_time_utc.replace(tzinfo=tzinfo) desired_expected_time = tzinfo.fromutc(localized_time) - return(desired_expected_time) + return desired_expected_time - # if the tzinfo passed in is a timedelta function, then we don't need to consider daylight savings + # if the tzinfo passed in is a timedelta function, then we don't need to consider daylight savings # noqa: W505 - doc line too long (102 > 100 characters) (auto-generated noqa) elif tzinfo.utcoffset(None) is not None: current_time_utc = ht_datetime.now(timezone.utc) desired_timezone_offset = current_time_utc.astimezone(tz=tzinfo).utcoffset() diff --git a/src/handwritten/errors.py b/src/handwritten/errors.py index 3dec1c60d..03c779acf 100644 --- a/src/handwritten/errors.py +++ b/src/handwritten/errors.py @@ -1,50 +1,48 @@ +"""NI-DAQmx error classes.""" + import warnings + import deprecation from nidaqmx.error_codes import DAQmxErrors, DAQmxWarnings -__all__ = ['DaqError', 'DaqReadError', 'DaqWriteError', 'DaqWarning', 'DaqResourceWarning'] +__all__ = ["DaqError", "DaqReadError", "DaqWriteError", "DaqWarning", "DaqResourceWarning"] class Error(Exception): - """ - Base error class for module. - """ + """Base error class for module.""" + pass class DaqNotFoundError(Error): - """ - Error raised when NI-DAQmx driver is not installed. - """ + """Error raised when NI-DAQmx driver is not installed.""" + pass class DaqNotSupportedError(Error): - """ - Error raised when DAQmx is not supported on this platform. - """ + """Error raised when DAQmx is not supported on this platform.""" + pass class DaqFunctionNotSupportedError(Error): - """ - Error raised when a specific function isn't supported by the installed - version of the NI-DAQmx driver. - """ + """Error raised when a specific function isn't supported by the installed NI-DAQmx driver.""" + pass class DaqError(Error): - """ - Error raised by any DAQmx method. - """ - def __init__(self, message, error_code, task_name=''): - """ + """Error raised by any DAQmx method.""" + + def __init__(self, message, error_code, task_name=""): + """Initialize a new DaqError. + Args: message (string): Specifies the error message. error_code (int): Specifies the NI-DAQmx error code. - """ + """ # noqa: D417 - Missing argument descriptions in the docstring (auto-generated noqa) self._error_code = int(error_code) try: @@ -54,93 +52,80 @@ def __init__(self, message, error_code, task_name=''): # If message is empty, we try to put at least some information in it if not message: - message = f'Description could not be found for the status code.\n\nStatus Code: {self._error_code}' + message = f"Description could not be found for the status code.\n\nStatus Code: {self._error_code}" if task_name: - message = f'{message}\n\nTask Name: {task_name}' - - # We do not know where the error description came from, so we add the status code if it is not already in the message + message = f"{message}\n\nTask Name: {task_name}" + + # We do not know where the error description came from, so we add the status code if it is not already in the message # noqa: W505 - doc line too long (125 > 100 characters) (auto-generated noqa) if str(self._error_code) not in message: - message = f'{message}\n\nStatus Code: {self._error_code}' + message = f"{message}\n\nStatus Code: {self._error_code}" super().__init__(message) @property def error_code(self): - """ - int: Specifies the NI-DAQmx error code. - """ + """int: Specifies the NI-DAQmx error code.""" return self._error_code @property def error_type(self): - """ - :class:`nidaqmx.error_codes.DAQmxErrors`: Specifies the NI-DAQmx - error type. - """ + """:class:`nidaqmx.error_codes.DAQmxErrors`: Specifies the NI-DAQmx error type.""" return self._error_type class DaqReadError(DaqError): - """ - Error raised by DAQmx write method that includes the amount of data that was - read. - """ - def __init__(self, message, error_code, samps_per_chan_read, task_name=''): - """ + """Error raised by DAQmx write method that includes the amount of data that was read.""" + + def __init__(self, message, error_code, samps_per_chan_read, task_name=""): + """Initialize a new DaqReadError. + Args: message (string): Specifies the error message. error_code (int): Specifies the NI-DAQmx error code. - """ + """ # noqa: D417 - Missing argument descriptions in the docstring (auto-generated noqa) super().__init__(message, error_code, task_name) self._samps_per_chan_read = samps_per_chan_read @property def samps_per_chan_read(self): - """ - int: Indicates the number of samples successfully read. - """ + """int: Indicates the number of samples successfully read.""" return self._samps_per_chan_read class DaqWriteError(DaqError): - """ - Error raised by DAQmx write method that includes the amount of data that was - written. - """ - def __init__(self, message, error_code, samps_per_chan_written, task_name=''): - """ + """Error raised by DAQmx write method that includes the amount of data that was written.""" + + def __init__(self, message, error_code, samps_per_chan_written, task_name=""): + """Initialize a new DaqWriteError. + Args: message (string): Specifies the error message. error_code (int): Specifies the NI-DAQmx error code. samps_per_chan_written (int): Specifies the number of samples written. - """ + """ # noqa: D417 - Missing argument descriptions in the docstring (auto-generated noqa) super().__init__(message, error_code, task_name) self._samps_per_chan_written = samps_per_chan_written @property def samps_per_chan_written(self): - """ - int: Indicates the number of samples successfully written. - """ + """int: Indicates the number of samples successfully written.""" return self._samps_per_chan_written - class DaqWarning(Warning): - """ - Warning raised by any NI-DAQmx method. - """ + """Warning raised by any NI-DAQmx method.""" + def __init__(self, message, error_code): - """ + """Initialize a new DaqWarning. + Args: message (string): Specifies the warning message. error_code (int): Specifies the NI-DAQmx error code. """ - super().__init__( - f'\nWarning {error_code} occurred.\n\n{message}') + super().__init__(f"\nWarning {error_code} occurred.\n\n{message}") self._error_code = int(error_code) @@ -151,51 +136,64 @@ def __init__(self, message, error_code): @property def error_code(self): - """ - int: Specifies the NI-DAQmx error code. - """ + """int: Specifies the NI-DAQmx error code.""" return self._error_code @property def error_type(self): - """ - :class:`nidaqmx.error_codes.DAQmxWarnings`: Specifies the NI-DAQmx - error type. - """ + """:class:`nidaqmx.error_codes.DAQmxWarnings`: Specifies the NI-DAQmx error type.""" return self._error_type + class DaqResourceWarning(ResourceWarning): + """Warning about DAQ resource usage, such as a leaking an NI-DAQmx task.""" + pass + warnings.filterwarnings("always", category=DaqWarning) warnings.filterwarnings("always", category=DaqResourceWarning) -@deprecation.deprecated(deprecated_in="0.8.0", details="This function will be removed in a future update.") + +@deprecation.deprecated( + deprecated_in="0.8.0", details="This function will be removed in a future update." +) def check_for_error(error_code, samps_per_chan_written=None, samps_per_chan_read=None): from nidaqmx._library_interpreter import LibraryInterpreter - return LibraryInterpreter().check_for_error(error_code, samps_per_chan_written, samps_per_chan_read) + + return LibraryInterpreter().check_for_error( + error_code, samps_per_chan_written, samps_per_chan_read + ) -@deprecation.deprecated(deprecated_in="0.8.0", details="This function will be removed in a future update.") +@deprecation.deprecated( + deprecated_in="0.8.0", details="This function will be removed in a future update." +) def is_string_buffer_too_small(error_code): import nidaqmx._library_interpreter + return nidaqmx._library_interpreter.is_string_buffer_too_small(error_code) -@deprecation.deprecated(deprecated_in="0.8.0", details="This function will be removed in a future update.") +@deprecation.deprecated( + deprecated_in="0.8.0", details="This function will be removed in a future update." +) def is_array_buffer_too_small(error_code): import nidaqmx._library_interpreter + return nidaqmx._library_interpreter.is_array_buffer_too_small(error_code) class RpcError(Error): - '''An error specific to sessions to the NI gRPC Device Server''' + """An error specific to sessions to the NI gRPC Device Server.""" def __init__(self, rpc_code, description): + """Initialize a new RpcError.""" self.rpc_code = rpc_code self.description = description try: import grpc + rpc_error = str(grpc.StatusCode(self.rpc_code)) except Exception: rpc_error = str(self.rpc_code) @@ -203,4 +201,4 @@ def __init__(self, rpc_code, description): class FeatureNotSupportedError(Exception): - """The feature is not supported at the current code readiness level.""" \ No newline at end of file + """The feature is not supported at the current code readiness level.""" diff --git a/src/handwritten/grpc_session_options.py b/src/handwritten/grpc_session_options.py index 16191fa13..fdabdc3b3 100644 --- a/src/handwritten/grpc_session_options.py +++ b/src/handwritten/grpc_session_options.py @@ -1,4 +1,7 @@ +"""NI-DAQmx gRPC session options.""" + from __future__ import annotations + from enum import IntEnum from typing import TYPE_CHECKING @@ -7,42 +10,44 @@ # This constant specifies the gRPC package and service used by this API. -# Customers can pass this value to the MeasurementLink discovery service to resolve the server instance that provides this interface. -GRPC_SERVICE_INTERFACE_NAME = 'nidaqmx_grpc.NiDAQmx' +# Customers can pass this value to the MeasurementLink discovery service to resolve the server instance that provides this interface. # noqa: W505 - doc line too long (133 > 100 characters) (auto-generated noqa) +GRPC_SERVICE_INTERFACE_NAME = "nidaqmx_grpc.NiDAQmx" # This constant specifies the API license key required by the NI gRPC Device Server that comes with # MeasurementLink 2023 Q1. -MEASUREMENTLINK_23Q1_NIDAQMX_PYTHON_API_KEY = '147D9BA7-BE75-4B29-8591-BA4A737AA8CF' +MEASUREMENTLINK_23Q1_NIDAQMX_PYTHON_API_KEY = "147D9BA7-BE75-4B29-8591-BA4A737AA8CF" class SessionInitializationBehavior(IntEnum): + """Specifies how to initialize sessions on the server.""" + AUTO = 0 - r''' + r""" The NI gRPC Device Server will attach to an existing session with the specified name if it exists, otherwise the server will initialize a new session. Note: When using the Session as a context manager and the context exits, the behavior depends on what happened when the constructor was called. If it resulted in a new session being initialized on the NI gRPC Device Server, then it will automatically close the server session. If it instead attached to an existing session, then it will detach from the server session and leave it open. - ''' + """ # noqa: W505 - doc line too long (123 > 100 characters) (auto-generated noqa) INITIALIZE_SERVER_SESSION = 1 - r''' + r""" Require the NI gRPC Device Server to initialize a new session with the specified name. Note: When using the Session as a context manager and the context exits, it will automatically close the server session. - ''' + """ # noqa: W505 - doc line too long (102 > 100 characters) (auto-generated noqa) ATTACH_TO_SERVER_SESSION = 2 - r''' + r""" Require the NI gRPC Device Server to attach to an existing session with the specified name. Note: When using the Session as a context manager and the context exits, it will detach from the server session and leave it open. - ''' + """ # noqa: W505 - doc line too long (109 > 100 characters) (auto-generated noqa) class GrpcSessionOptions: - '''Collection of options that specifies session behaviors related to gRPC.''' + """Collection of options that specifies session behaviors related to gRPC.""" def __init__( self, @@ -50,10 +55,10 @@ def __init__( session_name: str, *, api_key=MEASUREMENTLINK_23Q1_NIDAQMX_PYTHON_API_KEY, - initialization_behavior=SessionInitializationBehavior.AUTO + initialization_behavior=SessionInitializationBehavior.AUTO, ): - r'''Collection of options that specifies session behaviors related to gRPC. - Creates and returns an object you can pass to a Session constructor. + """Initialize a new GrpcSessionOptions. + Args: grpc_channel (grpc.Channel): Specifies the channel to the NI gRPC Device Server. session_name (str): User-specified name that identifies the driver session on the NI gRPC Device @@ -65,7 +70,7 @@ def __init__( initialization_behavior (enum): Specifies whether it is acceptable to initialize a new session or attach to an existing one, or if only one of the behaviors is desired. The driver session exists on the NI gRPC Device Server. - ''' + """ # noqa: W505 - doc line too long (108 > 100 characters) (auto-generated noqa) self.grpc_channel = grpc_channel self.session_name = session_name self.api_key = api_key diff --git a/src/handwritten/stream_readers/__init__.py b/src/handwritten/stream_readers/__init__.py index bd1beccb5..bfd21e0a0 100644 --- a/src/handwritten/stream_readers/__init__.py +++ b/src/handwritten/stream_readers/__init__.py @@ -1,5 +1,4 @@ -""" -NI-DAQmx stream readers. +"""NI-DAQmx stream readers. This package provides classes for reading samples from NI-DAQmx tasks. """ @@ -7,27 +6,32 @@ from __future__ import annotations from nidaqmx import DaqError - -from nidaqmx.stream_readers._analog_single_channel_reader import AnalogSingleChannelReader from nidaqmx.stream_readers._analog_multi_channel_reader import AnalogMultiChannelReader +from nidaqmx.stream_readers._analog_single_channel_reader import ( + AnalogSingleChannelReader, +) from nidaqmx.stream_readers._analog_unscaled_reader import AnalogUnscaledReader from nidaqmx.stream_readers._counter_reader import CounterReader -from nidaqmx.stream_readers._digital_single_channel_reader import DigitalSingleChannelReader -from nidaqmx.stream_readers._digital_multi_channel_reader import DigitalMultiChannelReader +from nidaqmx.stream_readers._digital_multi_channel_reader import ( + DigitalMultiChannelReader, +) +from nidaqmx.stream_readers._digital_single_channel_reader import ( + DigitalSingleChannelReader, +) from nidaqmx.stream_readers._power_readers import ( - PowerSingleChannelReader, - PowerMultiChannelReader, PowerBinaryReader, + PowerMultiChannelReader, + PowerSingleChannelReader, ) __all__ = [ - 'AnalogSingleChannelReader', - 'AnalogMultiChannelReader', - 'AnalogUnscaledReader', - 'CounterReader', - 'DigitalSingleChannelReader', - 'DigitalMultiChannelReader', - 'PowerSingleChannelReader', - 'PowerMultiChannelReader', - 'PowerBinaryReader', + "AnalogSingleChannelReader", + "AnalogMultiChannelReader", + "AnalogUnscaledReader", + "CounterReader", + "DigitalSingleChannelReader", + "DigitalMultiChannelReader", + "PowerSingleChannelReader", + "PowerMultiChannelReader", + "PowerBinaryReader", ] diff --git a/src/handwritten/stream_readers/_analog_multi_channel_reader.py b/src/handwritten/stream_readers/_analog_multi_channel_reader.py index 323b7a273..b75aba567 100644 --- a/src/handwritten/stream_readers/_analog_multi_channel_reader.py +++ b/src/handwritten/stream_readers/_analog_multi_channel_reader.py @@ -1,28 +1,22 @@ from __future__ import annotations import numpy -from nidaqmx import DaqError +from nitypes.waveform import AnalogWaveform +from nidaqmx import DaqError from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature -from nidaqmx.constants import FillMode, READ_ALL_AVAILABLE, ReallocationPolicy +from nidaqmx.constants import READ_ALL_AVAILABLE, FillMode, ReallocationPolicy from nidaqmx.error_codes import DAQmxErrors -from nitypes.waveform import AnalogWaveform - from nidaqmx.stream_readers._channel_reader_base import ChannelReaderBase class AnalogMultiChannelReader(ChannelReaderBase): - """ - Reads samples from one or more analog input channels in an NI-DAQmx - task. - """ + """Reads samples from one or more analog input channels in an NI-DAQmx task.""" def read_many_sample( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more floating-point samples from one or more analog - input channels in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more floating-point samples from one or more analog input channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -83,29 +77,32 @@ def read_many_sample( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (101 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) _, samps_per_chan_read = self._interpreter.read_analog_f64( - self._handle, number_of_samples_per_channel, - timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_one_sample(self, data, timeout=10): - """ - Reads a single floating-point sample from one or more analog - input channels in a task. + """Reads a single floating-point sample from one or more analog input channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -136,7 +133,9 @@ def read_one_sample(self, data, timeout=10): """ self._verify_array(data, 1, True, False) - self._interpreter.read_analog_f64(self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._interpreter.read_analog_f64( + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) @requires_feature(WAVEFORM_SUPPORT) def read_waveforms( @@ -146,9 +145,7 @@ def read_waveforms( reallocation_policy: ReallocationPolicy = ReallocationPolicy.TO_GROW, timeout: int = 10, ) -> int: - """ - Reads one or more floating-point samples from one or more analog - input channels into a list of waveforms. + """Reads one or more floating-point samples from one or more analog input channels into a list of waveforms. This read method optionally accepts a preallocated list of waveforms to hold the samples requested, which can be advantageous for performance and @@ -161,7 +158,7 @@ def read_waveforms( Args: waveforms (list[AnalogWaveform]): Specifies a list of AnalogWaveform objects to use for reading samples into. - The list must contain one waveform for each channel in the task. + The list must contain one waveform for each channel in the task. number_of_samples_per_channel (Optional[int]): Specifies the number of samples to read. @@ -194,35 +191,40 @@ def read_waveforms( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ + """ # noqa: W505 - doc line too long (116 > 100 characters) (auto-generated noqa) number_of_channels = self._in_stream.num_chans - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) if len(waveforms) != number_of_channels: raise DaqError( - f'The number of waveforms provided ({len(waveforms)}) does not match ' - f'the number of channels in the task ({number_of_channels}). Please provide ' - 'one waveform for each channel.', - DAQmxErrors.MISMATCHED_INPUT_ARRAY_SIZES, task_name=self._task.name) - + f"The number of waveforms provided ({len(waveforms)}) does not match " + f"the number of channels in the task ({number_of_channels}). Please provide " + "one waveform for each channel.", + DAQmxErrors.MISMATCHED_INPUT_ARRAY_SIZES, + task_name=self._task.name, + ) + for i, waveform in enumerate(waveforms): if waveform.start_index + number_of_samples_per_channel > waveform.capacity: if reallocation_policy == ReallocationPolicy.TO_GROW: waveform.capacity = waveform.start_index + number_of_samples_per_channel else: raise DaqError( - f'The waveform at index {i} does not have enough space ({waveform.capacity - waveform.start_index}) to hold ' - f'the requested number of samples ({number_of_samples_per_channel}). Please provide larger ' - 'waveforms or adjust the number of samples requested.', - DAQmxErrors.READ_BUFFER_TOO_SMALL, task_name=self._task.name) + f"The waveform at index {i} does not have enough space ({waveform.capacity - waveform.start_index}) to hold " + f"the requested number of samples ({number_of_samples_per_channel}). Please provide larger " + "waveforms or adjust the number of samples requested.", + DAQmxErrors.READ_BUFFER_TOO_SMALL, + task_name=self._task.name, + ) return self._interpreter.read_analog_waveforms( self._handle, diff --git a/src/handwritten/stream_readers/_analog_single_channel_reader.py b/src/handwritten/stream_readers/_analog_single_channel_reader.py index 0a8db41f5..5d67b0c6c 100644 --- a/src/handwritten/stream_readers/_analog_single_channel_reader.py +++ b/src/handwritten/stream_readers/_analog_single_channel_reader.py @@ -1,27 +1,22 @@ from __future__ import annotations import numpy -from nidaqmx import DaqError +from nitypes.waveform import AnalogWaveform +from nidaqmx import DaqError from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature -from nidaqmx.constants import FillMode, READ_ALL_AVAILABLE, ReallocationPolicy +from nidaqmx.constants import READ_ALL_AVAILABLE, FillMode, ReallocationPolicy from nidaqmx.error_codes import DAQmxErrors -from nitypes.waveform import AnalogWaveform - from nidaqmx.stream_readers._channel_reader_base import ChannelReaderBase class AnalogSingleChannelReader(ChannelReaderBase): - """ - Reads samples from an analog input channel in an NI-DAQmx task. - """ + """Reads samples from an analog input channel in an NI-DAQmx task.""" def read_many_sample( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more floating-point samples from a single analog - input channel in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more floating-point samples from a single analog input channel in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -69,6 +64,7 @@ def read_many_sample( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: @@ -76,22 +72,24 @@ def read_many_sample( NI-DAQmx returns a single value because this value is the same for all channels. """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, False, True) _, samps_per_chan_read = self._interpreter.read_analog_f64( - self._handle, number_of_samples_per_channel, - timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_one_sample(self, timeout=10): - """ - Reads a single floating-point sample from a single analog input - channel in a task. + """Reads a single floating-point sample from a single analog input channel in a task. Args: timeout (Optional[float]): Specifies the amount of time in @@ -103,6 +101,7 @@ def read_one_sample(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: float: @@ -112,15 +111,13 @@ def read_one_sample(self, timeout=10): @requires_feature(WAVEFORM_SUPPORT) def read_waveform( - self, + self, waveform: AnalogWaveform[numpy.float64], - number_of_samples_per_channel: int = READ_ALL_AVAILABLE, + number_of_samples_per_channel: int = READ_ALL_AVAILABLE, reallocation_policy: ReallocationPolicy = ReallocationPolicy.TO_GROW, - timeout: int = 10, + timeout: int = 10, ) -> int: - """ - Reads one or more floating-point samples from a single analog - input channel into a waveform. + """Reads one or more floating-point samples from a single analog input channel into a waveform. This read method optionally accepts a preallocated waveform to hold the samples requested, which can be advantageous for performance and @@ -165,24 +162,27 @@ def read_waveform( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) if waveform.start_index + number_of_samples_per_channel > waveform.capacity: if reallocation_policy == ReallocationPolicy.TO_GROW: waveform.capacity = waveform.start_index + number_of_samples_per_channel else: raise DaqError( - f'The provided waveform does not have enough space ({waveform.capacity - waveform.start_index}) to hold ' - f'the requested number of samples ({number_of_samples_per_channel}). Please provide a larger ' - 'waveform or adjust the number of samples requested.', - DAQmxErrors.READ_BUFFER_TOO_SMALL, task_name=self._task.name) + f"The provided waveform does not have enough space ({waveform.capacity - waveform.start_index}) to hold " + f"the requested number of samples ({number_of_samples_per_channel}). Please provide a larger " + "waveform or adjust the number of samples requested.", + DAQmxErrors.READ_BUFFER_TOO_SMALL, + task_name=self._task.name, + ) return self._interpreter.read_analog_waveform( self._handle, diff --git a/src/handwritten/stream_readers/_analog_unscaled_reader.py b/src/handwritten/stream_readers/_analog_unscaled_reader.py index db4a220d4..21aa028f6 100644 --- a/src/handwritten/stream_readers/_analog_unscaled_reader.py +++ b/src/handwritten/stream_readers/_analog_unscaled_reader.py @@ -1,22 +1,14 @@ from __future__ import annotations -from nidaqmx.constants import FillMode, READ_ALL_AVAILABLE - +from nidaqmx.constants import READ_ALL_AVAILABLE, FillMode from nidaqmx.stream_readers._channel_reader_base import ChannelReaderBase class AnalogUnscaledReader(ChannelReaderBase): - """ - Reads unscaled samples from one or more analog input channels in an - NI-DAQmx task. - """ - - def read_int16( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more unscaled 16-bit integer samples from one or - more analog input channels in a task. + """Reads unscaled samples from one or more analog input channels in an NI-DAQmx task.""" + + def read_int16(self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): + """Reads one or more unscaled 16-bit integer samples from one or more analog input channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -77,31 +69,32 @@ def read_int16( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (110 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) _, samps_per_chan_read = self._interpreter.read_binary_i16( - self._handle, number_of_samples_per_channel, - timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read - def read_int32( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more unscaled 32-bit integer samples from one or - more analog input channels in a task. + def read_int32(self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): + """Reads one or more unscaled 32-bit integer samples from one or more analog input channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -162,31 +155,32 @@ def read_int32( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (110 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) _, samps_per_chan_read = self._interpreter.read_binary_i32( - self._handle, number_of_samples_per_channel, - timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read - def read_uint16( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more unscaled 16-bit unsigned integer samples from - one or more analog input channels in a task. + def read_uint16(self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): + """Reads one or more unscaled 16-bit unsigned integer samples from one or more analog input channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -247,31 +241,32 @@ def read_uint16( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (119 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) _, samps_per_chan_read = self._interpreter.read_binary_u16( - self._handle, number_of_samples_per_channel, - timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read - def read_uint32( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more unscaled unsigned 32-bit integer samples from - one or more analog input channels in a task. + def read_uint32(self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): + """Reads one or more unscaled unsigned 32-bit integer samples from one or more analog input channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -332,21 +327,26 @@ def read_uint32( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (119 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) - _, samps_per_chan_read = self._interpreter.read_binary_u32( - self._handle, number_of_samples_per_channel, - timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + _, samps_per_chan_read = self._interpreter.read_binary_u32( + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read diff --git a/src/handwritten/stream_readers/_channel_reader_base.py b/src/handwritten/stream_readers/_channel_reader_base.py index af7a2db02..ba0300bbb 100644 --- a/src/handwritten/stream_readers/_channel_reader_base.py +++ b/src/handwritten/stream_readers/_channel_reader_base.py @@ -1,16 +1,15 @@ from __future__ import annotations from nidaqmx import DaqError - from nidaqmx.error_codes import DAQmxErrors + class ChannelReaderBase: - """ - Defines base class for all NI-DAQmx stream readers. - """ + """Defines base class for all NI-DAQmx stream readers.""" def __init__(self, task_in_stream): - """ + """Initialize a new ChannelReaderBase. + Args: task_in_stream: Specifies the input stream associated with an NI-DAQmx task from which to read samples. @@ -24,13 +23,12 @@ def __init__(self, task_in_stream): @property def verify_array_shape(self): - """ - bool: Indicates whether the size and shape of the user-defined - NumPy arrays passed to read methods are verified. Defaults - to True when this object is instantiated. + """bool: Specifies whether to verify the shape of NumPy arrays. - Setting this property to True may marginally adversely - impact the performance of read methods. + Defaults to True when this object is instantiated. + + Setting this property to True may marginally adversely + impact the performance of read methods. """ return self._verify_array_shape @@ -38,9 +36,9 @@ def verify_array_shape(self): def verify_array_shape(self, val): self._verify_array_shape = val - def _verify_array(self, data, number_of_samples_per_channel, - is_many_chan, is_many_samp): - """ + def _verify_array(self, data, number_of_samples_per_channel, is_many_chan, is_many_samp): + """Verify the shape of a NumPy array. + Verifies that the shape of the specified NumPy array can be used to read multiple samples from the current task which contains one or more channels, if the "verify_array_shape" property is @@ -64,8 +62,7 @@ def _verify_array(self, data, number_of_samples_per_channel, array_shape: tuple[int, ...] | None = None if is_many_chan: if is_many_samp: - array_shape = (number_of_channels, - number_of_samples_per_channel) + array_shape = (number_of_channels, number_of_samples_per_channel) else: array_shape = (number_of_channels,) else: @@ -74,19 +71,20 @@ def _verify_array(self, data, number_of_samples_per_channel, if array_shape is not None and data.shape != array_shape: raise DaqError( - 'Read cannot be performed because the NumPy array passed into ' - 'this function is not shaped correctly. You must pass in a ' - 'NumPy array of the correct shape based on the number of ' - 'channels in task and the number of samples per channel ' - 'requested.\n\n' - 'Shape of NumPy Array provided: {}\n' - 'Shape of NumPy Array required: {}' - .format(data.shape, array_shape), - DAQmxErrors.UNKNOWN, task_name=self._task.name) - - def _verify_array_digital_lines( - self, data, is_many_chan, is_many_line): - """ + "Read cannot be performed because the NumPy array passed into " + "this function is not shaped correctly. You must pass in a " + "NumPy array of the correct shape based on the number of " + "channels in task and the number of samples per channel " + "requested.\n\n" + "Shape of NumPy Array provided: {}\n" + "Shape of NumPy Array required: {}".format(data.shape, array_shape), + DAQmxErrors.UNKNOWN, + task_name=self._task.name, + ) + + def _verify_array_digital_lines(self, data, is_many_chan, is_many_line): + """Verify the shape of a NumPy array of digital lines. + Verifies that the shape of the specified NumPy array can be used to read samples from the current task which contains one or more channels that have one or more digital lines per channel, if the @@ -118,12 +116,13 @@ def _verify_array_digital_lines( if array_shape is not None and data.shape != array_shape: raise DaqError( - 'Read cannot be performed because the NumPy array passed into ' - 'this function is not shaped correctly. You must pass in a ' - 'NumPy array of the correct shape based on the number of ' - 'channels in task and the number of digital lines per ' - 'channel.\n\n' - 'Shape of NumPy Array provided: {}\n' - 'Shape of NumPy Array required: {}' - .format(data.shape, array_shape), - DAQmxErrors.UNKNOWN, task_name=self._task.name) + "Read cannot be performed because the NumPy array passed into " + "this function is not shaped correctly. You must pass in a " + "NumPy array of the correct shape based on the number of " + "channels in task and the number of digital lines per " + "channel.\n\n" + "Shape of NumPy Array provided: {}\n" + "Shape of NumPy Array required: {}".format(data.shape, array_shape), + DAQmxErrors.UNKNOWN, + task_name=self._task.name, + ) diff --git a/src/handwritten/stream_readers/_counter_reader.py b/src/handwritten/stream_readers/_counter_reader.py index f810dc640..67ef1911b 100644 --- a/src/handwritten/stream_readers/_counter_reader.py +++ b/src/handwritten/stream_readers/_counter_reader.py @@ -1,22 +1,17 @@ from __future__ import annotations -from nidaqmx.constants import FillMode, READ_ALL_AVAILABLE -from nidaqmx.types import CtrFreq, CtrTick, CtrTime - +from nidaqmx.constants import READ_ALL_AVAILABLE, FillMode from nidaqmx.stream_readers._channel_reader_base import ChannelReaderBase +from nidaqmx.types import CtrFreq, CtrTick, CtrTime class CounterReader(ChannelReaderBase): - """ - Reads samples from a counter input channel in an NI-DAQmx task. - """ + """Reads samples from a counter input channel in an NI-DAQmx task.""" def read_many_sample_double( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more floating-point samples from a single counter - input channel in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more floating-point samples from a single counter input channel in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -64,6 +59,7 @@ def read_many_sample_double( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: @@ -71,24 +67,30 @@ def read_many_sample_double( NI-DAQmx returns a single value because this value is the same for all channels. """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, False, True) _, samps_per_chan_read = self._interpreter.read_counter_f64_ex( - self._handle,number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_many_sample_pulse_frequency( - self, frequencies, duty_cycles, - number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): - """ - Reads one or more pulse samples in terms of frequency from a - single counter input channel in a task. + self, + frequencies, + duty_cycles, + number_of_samples_per_channel=READ_ALL_AVAILABLE, + timeout=10.0, + ): + """Reads one or more pulse samples in terms of frequency from a single counter input channel in a task. This read method accepts preallocated NumPy arrays to hold the samples requested, which can be advantageous for performance and @@ -144,34 +146,36 @@ def read_many_sample_pulse_frequency( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (111 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) - self._verify_array( - frequencies, number_of_samples_per_channel, False, True) - self._verify_array( - duty_cycles, number_of_samples_per_channel, False, True) + self._verify_array(frequencies, number_of_samples_per_channel, False, True) + self._verify_array(duty_cycles, number_of_samples_per_channel, False, True) _, _, samps_per_chan_read = self._interpreter.read_ctr_freq( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, frequencies, duty_cycles) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + frequencies, + duty_cycles, + ) + return samps_per_chan_read def read_many_sample_pulse_ticks( - self, high_ticks, low_ticks, - number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): - """ - Reads one or more pulse samples in terms of ticks from a single - counter input channel in a task. + self, high_ticks, low_ticks, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more pulse samples in terms of ticks from a single counter input channel in a task. This read method accepts preallocated NumPy arrays to hold the samples requested, which can be advantageous for performance and @@ -227,34 +231,36 @@ def read_many_sample_pulse_ticks( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) - self._verify_array( - high_ticks, number_of_samples_per_channel, False, True) - self._verify_array( - low_ticks, number_of_samples_per_channel, False, True) + self._verify_array(high_ticks, number_of_samples_per_channel, False, True) + self._verify_array(low_ticks, number_of_samples_per_channel, False, True) _, _, samps_per_chan_read = self._interpreter.read_ctr_ticks( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_ticks, low_ticks) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_ticks, + low_ticks, + ) + return samps_per_chan_read def read_many_sample_pulse_time( - self, high_times, low_times, - number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): - """ - Reads one or more pulse samples in terms of time from a single - counter input channel in a task. + self, high_times, low_times, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more pulse samples in terms of time from a single counter input channel in a task. This read method accepts preallocated NumPy arrays to hold the samples requested, which can be advantageous for performance and @@ -310,34 +316,36 @@ def read_many_sample_pulse_time( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (106 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) - self._verify_array( - high_times, number_of_samples_per_channel, False, True) - self._verify_array( - low_times, number_of_samples_per_channel, False, True) + self._verify_array(high_times, number_of_samples_per_channel, False, True) + self._verify_array(low_times, number_of_samples_per_channel, False, True) _, _, samps_per_chan_read = self._interpreter.read_ctr_time( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_times, low_times) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_times, + low_times, + ) + return samps_per_chan_read def read_many_sample_uint32( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more 32-bit unsigned integer samples from a single - counter input channel in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more 32-bit unsigned integer samples from a single counter input channel in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -385,29 +393,32 @@ def read_many_sample_uint32( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, False, True) _, samps_per_chan_read = self._interpreter.read_counter_u32_ex( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_one_sample_double(self, timeout=10): - """ - Reads a single floating-point sample from a single counter input - channel in a task. + """Reads a single floating-point sample from a single counter input channel in a task. Args: timeout (Optional[float]): Specifies the amount of time in @@ -419,6 +430,7 @@ def read_one_sample_double(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: float: Indicates a single floating-point sample from the task. @@ -426,9 +438,7 @@ def read_one_sample_double(self, timeout=10): return self._interpreter.read_counter_scalar_f64(self._handle, timeout) def read_one_sample_pulse_frequency(self, timeout=10): - """ - Reads a pulse sample in terms of frequency from a single counter - input channel in a task. + """Reads a pulse sample in terms of frequency from a single counter input channel in a task. Args: timeout (Optional[float]): Specifies the amount of time in @@ -440,6 +450,7 @@ def read_one_sample_pulse_frequency(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: nidaqmx.types.CtrFreq: @@ -450,9 +461,7 @@ def read_one_sample_pulse_frequency(self, timeout=10): return CtrFreq(freq, duty_cycle) def read_one_sample_pulse_ticks(self, timeout=10): - """ - Reads a pulse sample in terms of ticks from a single counter - input channel in a task. + """Reads a pulse sample in terms of ticks from a single counter input channel in a task. Args: timeout (Optional[float]): Specifies the amount of time in @@ -464,6 +473,7 @@ def read_one_sample_pulse_ticks(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: nidaqmx.types.CtrTick: @@ -474,9 +484,7 @@ def read_one_sample_pulse_ticks(self, timeout=10): return CtrTick(high_ticks, low_ticks) def read_one_sample_pulse_time(self, timeout=10): - """ - Reads a pulse sample in terms of time from a single counter - input channel in a task. + """Reads a pulse sample in terms of time from a single counter input channel in a task. Args: timeout (Optional[float]): Specifies the amount of time in @@ -488,6 +496,7 @@ def read_one_sample_pulse_time(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: nidaqmx.types.CtrTime: @@ -498,9 +507,7 @@ def read_one_sample_pulse_time(self, timeout=10): return CtrTime(high_time, low_time) def read_one_sample_uint32(self, timeout=10): - """ - Reads a single 32-bit unsigned integer sample from a single - counter input channel in a task. + """Reads a single 32-bit unsigned integer sample from a single counter input channel in a task. Args: timeout (Optional[float]): Specifies the amount of time in @@ -512,10 +519,11 @@ def read_one_sample_uint32(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates a single 32-bit unsigned integer sample from the task. - """ + """ # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) return self._interpreter.read_counter_scalar_u32(self._handle, timeout) diff --git a/src/handwritten/stream_readers/_digital_multi_channel_reader.py b/src/handwritten/stream_readers/_digital_multi_channel_reader.py index 68ae512d9..22c8ebd90 100644 --- a/src/handwritten/stream_readers/_digital_multi_channel_reader.py +++ b/src/handwritten/stream_readers/_digital_multi_channel_reader.py @@ -1,28 +1,22 @@ from __future__ import annotations import numpy -from nidaqmx import DaqError +from nitypes.waveform import DigitalWaveform +from nidaqmx import DaqError from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature -from nidaqmx.constants import FillMode, READ_ALL_AVAILABLE, ReallocationPolicy +from nidaqmx.constants import READ_ALL_AVAILABLE, FillMode, ReallocationPolicy from nidaqmx.error_codes import DAQmxErrors -from nitypes.waveform import DigitalWaveform - from nidaqmx.stream_readers._channel_reader_base import ChannelReaderBase class DigitalMultiChannelReader(ChannelReaderBase): - """ - Reads samples from one or more digital input channels in an NI-DAQmx - task. - """ + """Reads samples from one or more digital input channels in an NI-DAQmx task.""" def read_many_sample_port_byte( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more 8-bit unsigned integer samples from one or - more digital input channel in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more 8-bit unsigned integer samples from one or more digital input channel in a task. Use this method for devices with up to 8 lines per port. @@ -85,31 +79,34 @@ def read_many_sample_port_byte( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (109 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) _, samps_per_chan_read = self._interpreter.read_digital_u8( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_many_sample_port_uint16( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more 16-bit unsigned integer samples from one or - more digital input channels in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more 16-bit unsigned integer samples from one or more digital input channels in a task. Use this method for devices with up to 16 lines per port. @@ -172,30 +169,34 @@ def read_many_sample_port_uint16( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (111 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) _, samps_per_chan_read = self._interpreter.read_digital_u16( - self._handle, number_of_samples_per_channel, timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_many_sample_port_uint32( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more 32-bit unsigned integer samples from one or - more digital input channels in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more 32-bit unsigned integer samples from one or more digital input channels in a task. Use this method for devices with up to 32 lines per port. @@ -258,29 +259,34 @@ def read_many_sample_port_uint32( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (111 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, True, True) _, samps_per_chan_read = self._interpreter.read_digital_u32( - self._handle, number_of_samples_per_channel, timeout, FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_one_sample_multi_line(self, data, timeout=10): - """ - Reads a single boolean sample from one or more digital input - channels in a task. The channels can contain multiple digital - lines. + """Reads a single boolean sample from one or more digital input channels in a task. + + The channels can contain multiple digital lines. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -324,14 +330,14 @@ def read_one_sample_multi_line(self, data, timeout=10): """ self._verify_array_digital_lines(data, True, True) - _, samps_per_chan_read, num_bytes_per_samp= self._interpreter.read_digital_lines( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + _, samps_per_chan_read, num_bytes_per_samp = self._interpreter.read_digital_lines( + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def read_one_sample_one_line(self, data, timeout=10): - """ - Reads a single boolean sample from one or more digital input - channels in a task. The channel can contain only one digital - line. + """Reads a single boolean sample from one or more digital input channels in a task. + + The channel can contain only one digital line. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -361,13 +367,12 @@ def read_one_sample_one_line(self, data, timeout=10): """ self._verify_array_digital_lines(data, True, False) - _, samps_per_chan_read, num_bytes_per_samp= self._interpreter.read_digital_lines( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + _, samps_per_chan_read, num_bytes_per_samp = self._interpreter.read_digital_lines( + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def read_one_sample_port_byte(self, data, timeout=10): - """ - Reads a single 8-bit unsigned integer sample from one or more - digital input channels in a task. + """Reads a single 8-bit unsigned integer sample from one or more digital input channels in a task. Use this method for devices with up to 8 lines per port. @@ -397,16 +402,15 @@ def read_one_sample_port_byte(self, data, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. - """ + """ # noqa: W505 - doc line too long (106 > 100 characters) (auto-generated noqa) self._verify_array(data, 1, True, False) self._interpreter.read_digital_u8( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def read_one_sample_port_uint16(self, data, timeout=10): - """ - Reads a single 16-bit unsigned integer sample from one or more - digital input channels in a task. + """Reads a single 16-bit unsigned integer sample from one or more digital input channels in a task. Use this method for devices with up to 16 lines per port. @@ -436,16 +440,15 @@ def read_one_sample_port_uint16(self, data, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. - """ + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) self._verify_array(data, 1, True, False) self._interpreter.read_digital_u16( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def read_one_sample_port_uint32(self, data, timeout=10): - """ - Reads a single 32-bit unsigned integer sample from one or more - digital input channels in a task. + """Reads a single 32-bit unsigned integer sample from one or more digital input channels in a task. Use this method for devices with up to 32 lines per port. @@ -475,13 +478,13 @@ def read_one_sample_port_uint32(self, data, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. - """ + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) self._verify_array(data, 1, True, False) self._interpreter.read_digital_u32( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) - - + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) + @requires_feature(WAVEFORM_SUPPORT) def read_waveforms( self, @@ -490,15 +493,13 @@ def read_waveforms( reallocation_policy: ReallocationPolicy = ReallocationPolicy.TO_GROW, timeout: int = 10, ) -> list[DigitalWaveform[numpy.uint8]]: - """ - Reads one or more samples from one or more digital - input channels into a list of waveforms. + """Reads one or more samples from one or more digital input channels into a list of waveforms. - Args: + Args: waveforms (list[DigitalWaveform]): Specifies an existing list of DigitalWaveform objects to use for reading samples into. The list must contain one waveform - for each channel in the task. + for each channel in the task. number_of_samples_per_channel (Optional[int]): Specifies the number of samples to read. @@ -530,25 +531,28 @@ def read_waveforms( nidaqmx.constants.WAIT_INFINITELY, the method waits indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error - if it is unable to. + if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ + """ # noqa: W505 - doc line too long (102 > 100 characters) (auto-generated noqa) number_of_channels = self._in_stream.num_chans - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) if len(waveforms) != number_of_channels: raise DaqError( - f'The number of waveforms provided ({len(waveforms)}) does not match ' - f'the number of channels in the task ({number_of_channels}). Please provide ' - 'one waveform for each channel.', - DAQmxErrors.MISMATCHED_INPUT_ARRAY_SIZES, task_name=self._task.name) + f"The number of waveforms provided ({len(waveforms)}) does not match " + f"the number of channels in the task ({number_of_channels}). Please provide " + "one waveform for each channel.", + DAQmxErrors.MISMATCHED_INPUT_ARRAY_SIZES, + task_name=self._task.name, + ) for i, waveform in enumerate(waveforms): if waveform.start_index + number_of_samples_per_channel > waveform.capacity: @@ -556,10 +560,12 @@ def read_waveforms( waveform.capacity = waveform.start_index + number_of_samples_per_channel else: raise DaqError( - f'The waveform at index {i} does not have enough space ({waveform.capacity - waveform.start_index}) to hold ' - f'the requested number of samples ({number_of_samples_per_channel}). Please provide larger ' - 'waveforms or adjust the number of samples requested.', - DAQmxErrors.READ_BUFFER_TOO_SMALL, task_name=self._task.name) + f"The waveform at index {i} does not have enough space ({waveform.capacity - waveform.start_index}) to hold " + f"the requested number of samples ({number_of_samples_per_channel}). Please provide larger " + "waveforms or adjust the number of samples requested.", + DAQmxErrors.READ_BUFFER_TOO_SMALL, + task_name=self._task.name, + ) waveforms = self._interpreter.read_digital_waveforms( self._handle, diff --git a/src/handwritten/stream_readers/_digital_single_channel_reader.py b/src/handwritten/stream_readers/_digital_single_channel_reader.py index 79f2d96fb..12e5fd085 100644 --- a/src/handwritten/stream_readers/_digital_single_channel_reader.py +++ b/src/handwritten/stream_readers/_digital_single_channel_reader.py @@ -1,27 +1,22 @@ from __future__ import annotations import numpy -from nidaqmx import DaqError +from nitypes.waveform import DigitalWaveform +from nidaqmx import DaqError from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature -from nidaqmx.constants import FillMode, READ_ALL_AVAILABLE, ReallocationPolicy +from nidaqmx.constants import READ_ALL_AVAILABLE, FillMode, ReallocationPolicy from nidaqmx.error_codes import DAQmxErrors -from nitypes.waveform import DigitalWaveform - from nidaqmx.stream_readers._channel_reader_base import ChannelReaderBase class DigitalSingleChannelReader(ChannelReaderBase): - """ - Reads samples from a digital input channel in an NI-DAQmx task. - """ + """Reads samples from a digital input channel in an NI-DAQmx task.""" def read_many_sample_port_byte( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more 8-bit unsigned integer samples from a single - digital input channel in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more 8-bit unsigned integer samples from a single digital input channel in a task. Use this method for devices with up to 8 lines per port. @@ -71,31 +66,34 @@ def read_many_sample_port_byte( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (106 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, False, True) _, samps_per_chan_read = self._interpreter.read_digital_u8( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_many_sample_port_uint16( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more 16-bit unsigned integer samples from a single - digital input channel in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more 16-bit unsigned integer samples from a single digital input channel in a task. Use this method for devices with up to 16 lines per port. @@ -145,31 +143,34 @@ def read_many_sample_port_uint16( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, False, True) _, samps_per_chan_read = self._interpreter.read_digital_u16( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_many_sample_port_uint32( - self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more 32-bit unsigned integer samples from a single - digital input channel in a task. + self, data, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0 + ): + """Reads one or more 32-bit unsigned integer samples from a single digital input channel in a task. Use this method for devices with up to 32 lines per port. @@ -219,30 +220,34 @@ def read_many_sample_port_uint32( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(data, number_of_samples_per_channel, False, True) _, samps_per_chan_read = self._interpreter.read_digital_u32( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) + return samps_per_chan_read def read_one_sample_multi_line(self, data, timeout=10): - """ - Reads a single boolean sample from a single digital input - channel in a task. The channel can contain multiple digital - lines. + """Reads a single boolean sample from a single digital input channel in a task. + + The channel can contain multiple digital lines. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -273,13 +278,13 @@ def read_one_sample_multi_line(self, data, timeout=10): self._verify_array_digital_lines(data, False, True) _, samps_per_chan_read, num_bytes_per_samp = self._interpreter.read_digital_lines( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def read_one_sample_one_line(self, timeout=10): - """ - Reads a single boolean sample from a single digital input - channel in a task. The channel can contain only one digital - line. + """Reads a single boolean sample from a single digital input channel in a task. + + The channel can contain only one digital line. Args: timeout (Optional[float]): Specifies the amount of time in @@ -291,21 +296,21 @@ def read_one_sample_one_line(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: bool: Indicates a single boolean sample from the task. """ data = numpy.zeros(1, dtype=bool) - _, samps_per_chan_read, num_bytes_per_samp= self._interpreter.read_digital_lines( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + _, samps_per_chan_read, num_bytes_per_samp = self._interpreter.read_digital_lines( + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) return bool(data[0]) def read_one_sample_port_byte(self, timeout=10): - """ - Reads a single 8-bit unsigned integer sample from a single - digital input channel in a task. + """Reads a single 8-bit unsigned integer sample from a single digital input channel in a task. Use this method for devices with up to 8 lines per port. @@ -319,22 +324,22 @@ def read_one_sample_port_byte(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates a single 8-bit unsigned integer sample from the task. - """ + """ # noqa: W505 - doc line too long (102 > 100 characters) (auto-generated noqa) data = numpy.zeros(1, dtype=numpy.uint8) _, samps_per_chan_read = self._interpreter.read_digital_u8( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) return int(data[0]) def read_one_sample_port_uint16(self, timeout=10): - """ - Reads a single 16-bit unsigned integer sample from a single - digital input channel in a task. + """Reads a single 16-bit unsigned integer sample from a single digital input channel in a task. Use this method for devices with up to 16 lines per port. @@ -348,22 +353,22 @@ def read_one_sample_port_uint16(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates a single 16-bit unsigned integer sample from the task. - """ + """ # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) data = numpy.zeros(1, dtype=numpy.uint16) _, samps_per_read_chan = self._interpreter.read_digital_u16( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) return int(data[0]) def read_one_sample_port_uint32(self, timeout=10): - """ - Reads a single 32-bit unsigned integer sample from a single - digital input channel in a task. + """Reads a single 32-bit unsigned integer sample from a single digital input channel in a task. Use this method for devices with up to 32 lines per port. @@ -377,12 +382,13 @@ def read_one_sample_port_uint32(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates a single 32-bit unsigned integer sample from the task. - """ + """ # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) return self._interpreter.read_digital_scalar_u32(self._handle, timeout) @requires_feature(WAVEFORM_SUPPORT) @@ -393,14 +399,12 @@ def read_waveform( reallocation_policy: ReallocationPolicy = ReallocationPolicy.TO_GROW, timeout: float = 10.0, ) -> int: - """ - Reads one or more digital samples from a single digital input - channel into a waveform. + """Reads one or more digital samples from a single digital input channel into a waveform. Args: waveform (DigitalWaveform[numpy.uint8]): Specifies a preallocated DigitalWaveform object to hold the samples - requested. + requested. number_of_samples_per_channel (Optional[int]): Specifies the number of samples to read. @@ -433,6 +437,7 @@ def read_waveform( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: @@ -440,24 +445,26 @@ def read_waveform( NI-DAQmx returns a single value because this value is the same for all channels. """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) - + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) + if waveform.start_index + number_of_samples_per_channel > waveform.capacity: if reallocation_policy == ReallocationPolicy.TO_GROW: waveform.capacity = waveform.start_index + number_of_samples_per_channel else: raise DaqError( - f'The waveform does not have enough space ({waveform.capacity - waveform.start_index}) to hold ' - f'the requested number of samples ({number_of_samples_per_channel}). Please ' - 'provide a larger waveform or adjust the number of samples requested.', - DAQmxErrors.READ_BUFFER_TOO_SMALL, task_name=self._task.name) - + f"The waveform does not have enough space ({waveform.capacity - waveform.start_index}) to hold " + f"the requested number of samples ({number_of_samples_per_channel}). Please " + "provide a larger waveform or adjust the number of samples requested.", + DAQmxErrors.READ_BUFFER_TOO_SMALL, + task_name=self._task.name, + ) + return self._interpreter.read_digital_waveform( - self._handle, - number_of_samples_per_channel, - timeout, - waveform, - self._in_stream.waveform_attribute_mode + self._handle, + number_of_samples_per_channel, + timeout, + waveform, + self._in_stream.waveform_attribute_mode, ) diff --git a/src/handwritten/stream_readers/_power_readers.py b/src/handwritten/stream_readers/_power_readers.py index cbb37cc08..a1c6b4324 100644 --- a/src/handwritten/stream_readers/_power_readers.py +++ b/src/handwritten/stream_readers/_power_readers.py @@ -1,22 +1,21 @@ from __future__ import annotations -from nidaqmx.constants import FillMode, READ_ALL_AVAILABLE -from nidaqmx.types import PowerMeasurement - +from nidaqmx.constants import READ_ALL_AVAILABLE, FillMode from nidaqmx.stream_readers._channel_reader_base import ChannelReaderBase +from nidaqmx.types import PowerMeasurement class PowerSingleChannelReader(ChannelReaderBase): - """ - Reads samples from an analog input power channel in an NI-DAQmx task. - """ + """Reads samples from an analog input power channel in an NI-DAQmx task.""" def read_many_sample( - self, voltage_data, current_data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more floating-point power samples from a single analog - input power channel in a task. + self, + voltage_data, + current_data, + number_of_samples_per_channel=READ_ALL_AVAILABLE, + timeout=10.0, + ): + """Reads one or more floating-point power samples from a single analog input power channel in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -72,30 +71,34 @@ def read_many_sample( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (109 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(voltage_data, number_of_samples_per_channel, False, True) self._verify_array(current_data, number_of_samples_per_channel, False, True) _, _, samps_per_chan_read = self._interpreter.read_power_f64( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, voltage_data, current_data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + voltage_data, + current_data, + ) + return samps_per_chan_read def read_one_sample(self, timeout=10): - """ - Reads a single floating-point power sample from a single analog input - power channel in a task. + """Reads a single floating-point power sample from a single analog input power channel in a task. Args: timeout (Optional[float]): Specifies the amount of time in @@ -107,27 +110,27 @@ def read_one_sample(self, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: float: Indicates a single floating-point power sample from the task. - """ + """ # noqa: W505 - doc line too long (105 > 100 characters) (auto-generated noqa) voltage, current = self._interpreter.read_power_scalar_f64(self._handle, timeout) return PowerMeasurement(voltage=voltage, current=current) class PowerMultiChannelReader(ChannelReaderBase): - """ - Reads samples from one or more analog input power channels in an NI-DAQmx - task. - """ + """Reads samples from one or more analog input power channels in an NI-DAQmx task.""" def read_many_sample( - self, voltage_data, current_data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more floating-point power samples from one or more analog - input power channels in a task. + self, + voltage_data, + current_data, + number_of_samples_per_channel=READ_ALL_AVAILABLE, + timeout=10.0, + ): + """Reads one or more floating-point power samples from one or more analog input power channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -209,30 +212,34 @@ def read_many_sample( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (113 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(voltage_data, number_of_samples_per_channel, True, True) self._verify_array(current_data, number_of_samples_per_channel, True, True) _, _, samps_per_chan_read = self._interpreter.read_power_f64( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, voltage_data, current_data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + voltage_data, + current_data, + ) + return samps_per_chan_read def read_one_sample(self, voltage_data, current_data, timeout=10): - """ - Reads a single floating-point power sample from one or more analog - input channels in a task. + """Reads a single floating-point power sample from one or more analog input channels in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -268,27 +275,26 @@ def read_one_sample(self, voltage_data, current_data, timeout=10): indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. - """ + """ # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) self._verify_array(voltage_data, 1, True, False) self._verify_array(current_data, 1, True, False) self._interpreter.read_power_f64( - self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, - voltage_data, current_data) + self._handle, 1, timeout, FillMode.GROUP_BY_CHANNEL.value, voltage_data, current_data + ) class PowerBinaryReader(ChannelReaderBase): - """ - Reads binary samples from one or more analog input power channels in an - NI-DAQmx task. - """ + """Reads binary samples from one or more analog input power channels in an NI-DAQmx task.""" def read_many_sample( - self, voltage_data, current_data, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads one or more binary int16 samples from one or more analog - input power channel in a task. + self, + voltage_data, + current_data, + number_of_samples_per_channel=READ_ALL_AVAILABLE, + timeout=10.0, + ): + """Reads one or more binary int16 samples from one or more analog input power channel in a task. This read method accepts a preallocated NumPy array to hold the samples requested, which can be advantageous for performance and @@ -364,22 +370,28 @@ def read_many_sample( indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: int: Indicates the number of samples acquired by each channel. NI-DAQmx returns a single value because this value is the same for all channels. - """ - number_of_samples_per_channel = ( - self._task._calculate_num_samps_per_chan( - number_of_samples_per_channel)) + """ # noqa: W505 - doc line too long (104 > 100 characters) (auto-generated noqa) + number_of_samples_per_channel = self._task._calculate_num_samps_per_chan( + number_of_samples_per_channel + ) self._verify_array(voltage_data, number_of_samples_per_channel, True, True) self._verify_array(current_data, number_of_samples_per_channel, True, True) _, _, samps_per_chan_read = self._interpreter.read_power_binary_i16( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, voltage_data, current_data) - + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + voltage_data, + current_data, + ) + return samps_per_chan_read diff --git a/src/handwritten/stream_writers/__init__.py b/src/handwritten/stream_writers/__init__.py index eb2520747..aeba78e41 100644 --- a/src/handwritten/stream_writers/__init__.py +++ b/src/handwritten/stream_writers/__init__.py @@ -1,25 +1,34 @@ -""" -NI-DAQmx stream writers. +"""NI-DAQmx stream writers. This package provides classes for writing samples to NI-DAQmx tasks. """ from __future__ import annotations -from nidaqmx.stream_writers._analog_single_channel_writer import AnalogSingleChannelWriter from nidaqmx.stream_writers._analog_multi_channel_writer import AnalogMultiChannelWriter +from nidaqmx.stream_writers._analog_single_channel_writer import ( + AnalogSingleChannelWriter, +) from nidaqmx.stream_writers._analog_unscaled_writer import AnalogUnscaledWriter +from nidaqmx.stream_writers._channel_writer_base import ( + AUTO_START_UNSET, + UnsetAutoStartSentinel, +) from nidaqmx.stream_writers._counter_writer import CounterWriter -from nidaqmx.stream_writers._digital_single_channel_writer import DigitalSingleChannelWriter -from nidaqmx.stream_writers._digital_multi_channel_writer import DigitalMultiChannelWriter -from nidaqmx.stream_writers._channel_writer_base import UnsetAutoStartSentinel, AUTO_START_UNSET +from nidaqmx.stream_writers._digital_multi_channel_writer import ( + DigitalMultiChannelWriter, +) +from nidaqmx.stream_writers._digital_single_channel_writer import ( + DigitalSingleChannelWriter, +) __all__ = [ - 'AnalogSingleChannelWriter', - 'AnalogMultiChannelWriter', - 'AnalogUnscaledWriter', - 'CounterWriter', - 'DigitalSingleChannelWriter', - 'DigitalMultiChannelWriter', - 'UnsetAutoStartSentinel', - 'AUTO_START_UNSET'] + "AnalogSingleChannelWriter", + "AnalogMultiChannelWriter", + "AnalogUnscaledWriter", + "CounterWriter", + "DigitalSingleChannelWriter", + "DigitalMultiChannelWriter", + "UnsetAutoStartSentinel", + "AUTO_START_UNSET", +] diff --git a/src/handwritten/stream_writers/_analog_multi_channel_writer.py b/src/handwritten/stream_writers/_analog_multi_channel_writer.py index aa2213e4b..ba1d64e5a 100644 --- a/src/handwritten/stream_writers/_analog_multi_channel_writer.py +++ b/src/handwritten/stream_writers/_analog_multi_channel_writer.py @@ -1,18 +1,15 @@ from nidaqmx.constants import FillMode - -from nidaqmx.stream_writers._channel_writer_base import ChannelWriterBase, AUTO_START_UNSET +from nidaqmx.stream_writers._channel_writer_base import ( + AUTO_START_UNSET, + ChannelWriterBase, +) class AnalogMultiChannelWriter(ChannelWriterBase): - """ - Writes samples to one or more analog output channels in an NI-DAQmx - task. - """ + """Writes samples to one or more analog output channels in an NI-DAQmx task.""" def write_many_sample(self, data, timeout=10.0): - """ - Writes one or more floating-point samples to one or more analog - output channels in a task. + """Writes one or more floating-point samples to one or more analog output channels in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -42,24 +39,23 @@ def write_many_sample(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (101 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_analog_f64( - self._handle, data.shape[1], auto_start, timeout,FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample(self, data, timeout=10): - """ - Writes a single floating-point sample to one or more analog - output channels in a task. + """Writes a single floating-point sample to one or more analog output channels in a task. Args: data (numpy.ndarray): Contains a 1D NumPy array of @@ -82,9 +78,9 @@ def write_one_sample(self, data, timeout=10): and the number of samples successfully written. """ self._verify_array(data, True, False) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True return self._interpreter.write_analog_f64( - self._handle, 1, auto_start, timeout,FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) diff --git a/src/handwritten/stream_writers/_analog_single_channel_writer.py b/src/handwritten/stream_writers/_analog_single_channel_writer.py index ddaf08048..01f9d52bd 100644 --- a/src/handwritten/stream_writers/_analog_single_channel_writer.py +++ b/src/handwritten/stream_writers/_analog_single_channel_writer.py @@ -1,24 +1,22 @@ from __future__ import annotations -import numpy from typing import Any -from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature -from nidaqmx.constants import FillMode from nitypes.waveform import AnalogWaveform -from nidaqmx.stream_writers._channel_writer_base import ChannelWriterBase, AUTO_START_UNSET +from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature +from nidaqmx.constants import FillMode +from nidaqmx.stream_writers._channel_writer_base import ( + AUTO_START_UNSET, + ChannelWriterBase, +) class AnalogSingleChannelWriter(ChannelWriterBase): - """ - Writes samples to an analog output channel in an NI-DAQmx task. - """ + """Writes samples to an analog output channel in an NI-DAQmx task.""" def write_many_sample(self, data, timeout=10.0): - """ - Writes one or more floating-point samples to a single analog - output channel in a task. + """Writes one or more floating-point samples to a single analog output channel in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -44,6 +42,7 @@ def write_many_sample(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: @@ -51,17 +50,15 @@ def write_many_sample(self, data, timeout=10.0): successfully wrote. """ self._verify_array(data, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_analog_f64( - self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample(self, data, timeout=10): - """ - Writes a single floating-point sample to a single analog output - channel in a task. + """Writes a single floating-point sample to a single analog output channel in a task. Args: data (float): Specifies the floating-point sample to write @@ -81,20 +78,13 @@ def write_one_sample(self, data, timeout=10): not write all the submitted samples, it returns an error and the number of samples successfully written. """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - - return self._interpreter.write_analog_scalar_f64( - self._handle, auto_start, timeout, data) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + + return self._interpreter.write_analog_scalar_f64(self._handle, auto_start, timeout, data) @requires_feature(WAVEFORM_SUPPORT) - def write_waveform( - self, - waveform: AnalogWaveform[Any], - timeout: float = 10.0 - ) -> int: - """ - Writes a waveform to a single analog output channel in a task. + def write_waveform(self, waveform: AnalogWaveform[Any], timeout: float = 10.0) -> int: + """Writes a waveform to a single analog output channel in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -119,13 +109,11 @@ def write_waveform( once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote. """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False - return self._interpreter.write_analog_waveform( - self._handle, waveform, auto_start, timeout) - \ No newline at end of file + return self._interpreter.write_analog_waveform(self._handle, waveform, auto_start, timeout) diff --git a/src/handwritten/stream_writers/_analog_unscaled_writer.py b/src/handwritten/stream_writers/_analog_unscaled_writer.py index cc23eac3f..c1762e570 100644 --- a/src/handwritten/stream_writers/_analog_unscaled_writer.py +++ b/src/handwritten/stream_writers/_analog_unscaled_writer.py @@ -1,18 +1,15 @@ from nidaqmx.constants import FillMode - -from nidaqmx.stream_writers._channel_writer_base import ChannelWriterBase, AUTO_START_UNSET +from nidaqmx.stream_writers._channel_writer_base import ( + AUTO_START_UNSET, + ChannelWriterBase, +) class AnalogUnscaledWriter(ChannelWriterBase): - """ - Writes unscaled samples to one or more analog output channels in - an NI-DAQmx task. - """ + """Writes unscaled samples to one or more analog output channels in an NI-DAQmx task.""" def write_int16(self, data, timeout=10.0): - """ - Writes one or more unscaled 16-bit integer samples to one or - more analog output channels in a task. + """Writes one or more unscaled 16-bit integer samples to one or more analog output channels in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -40,24 +37,23 @@ def write_int16(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (110 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_binary_i16( - self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_int32(self, data, timeout=10.0): - """ - Writes one or more unscaled 32-bit integer samples to one or - more analog output channels in a task. + """Writes one or more unscaled 32-bit integer samples to one or more analog output channels in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -85,24 +81,23 @@ def write_int32(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (110 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_binary_i32( - self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_uint16(self, data, timeout=10.0): - """ - Writes one or more unscaled 16-bit unsigned integer samples to - one or more analog output channels in a task. + """Writes one or more unscaled 16-bit unsigned integer samples to one or more analog output channels in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -130,24 +125,23 @@ def write_uint16(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (119 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_binary_u16( - self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_uint32(self, data, timeout=10.0): - """ - Writes one or more unscaled 32-bit unsigned integer samples to - one or more analog output channels in a task. + """Writes one or more unscaled 32-bit unsigned integer samples to one or more analog output channels in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -175,16 +169,17 @@ def write_uint32(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (119 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_binary_u32( - self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) diff --git a/src/handwritten/stream_writers/_channel_writer_base.py b/src/handwritten/stream_writers/_channel_writer_base.py index 965736e5d..f631a220c 100644 --- a/src/handwritten/stream_writers/_channel_writer_base.py +++ b/src/handwritten/stream_writers/_channel_writer_base.py @@ -4,32 +4,33 @@ class UnsetAutoStartSentinel: """Sentinel class for unset auto_start parameter.""" - - def __init__(self): - raise RuntimeError("Cannot instantiate UnsetAutoStartSentinel. Use AUTO_START_UNSET instead.") + + def __init__(self): # noqa: D107 - Missing docstring in __init__ (auto-generated noqa) + raise RuntimeError( + "Cannot instantiate UnsetAutoStartSentinel. Use AUTO_START_UNSET instead." + ) AUTO_START_UNSET = object.__new__(UnsetAutoStartSentinel) class ChannelWriterBase: - """ - Defines base class for all NI-DAQmx stream writers. - """ + """Defines base class for all NI-DAQmx stream writers.""" def __init__(self, task_out_stream, auto_start=AUTO_START_UNSET): - """ + """Initialize a new ChannelWriterBase. + Args: task_out_stream: Specifies the output stream associated with an NI-DAQmx task which to write samples. auto_start (Optional[bool]): Specifies if the write method automatically starts the task if you did not explicitly start it with the DAQmx Start Task method. - - If you do not specify a value for this parameter, + + If you do not specify a value for this parameter, NI-DAQmx determines its value based on the type of write method used. If you use a one sample write method, the - value is True; conversely, if you use a many sample + value is True; conversely, if you use a many sample write method, the value is False. """ self._out_stream = task_out_stream @@ -42,16 +43,13 @@ def __init__(self, task_out_stream, auto_start=AUTO_START_UNSET): @property def auto_start(self): - """ - bool: Specifies if the write method automatically starts the - task if you did not explicitly start it with the DAQmx Start - Task method. - - If you do not specify a value for this parameter, NI-DAQmx - determines its value based on the type of write method used. - If you use a one sample write method, its value is True; - conversely, if you use a many sample write method, its value - is False. + """bool: Specifies whether the write method automatically starts the task, if needed. + + If you do not specify a value for this parameter, NI-DAQmx + determines its value based on the type of write method used. + If you use a one sample write method, its value is True; + conversely, if you use a many sample write method, its value + is False. """ return self._auto_start @@ -65,13 +63,12 @@ def auto_start(self): @property def verify_array_shape(self): - """ - bool: Indicates whether the size and shape of the user-defined - NumPy arrays passed to read methods are verified. Defaults - to True when this object is instantiated. + """bool: Specifies whether to verify the shape of NumPy arrays. + + Defaults to True when this object is instantiated. - Setting this property to True may marginally adversely - impact the performance of read methods. + Setting this property to True may marginally adversely + impact the performance of read methods. """ return self._verify_array_shape @@ -80,7 +77,8 @@ def verify_array_shape(self, val): self._verify_array_shape = val def _verify_array(self, data, is_many_chan, is_many_samp): - """ + """Verifies the shape of a NumPy array. + Verifies that the shape of the specified NumPy array can be used with the specified write method type, if the "verify_array_shape" property is set to True. @@ -106,19 +104,17 @@ def _verify_array(self, data, is_many_chan, is_many_samp): expected_num_dimensions = 1 if data.shape[0] != number_of_channels: - self._task._raise_invalid_write_num_chans_error( - number_of_channels, data.shape[0]) + self._task._raise_invalid_write_num_chans_error(number_of_channels, data.shape[0]) else: if is_many_samp: expected_num_dimensions = 1 if expected_num_dimensions is not None: - self._raise_error_if_invalid_write_dimensions( - expected_num_dimensions, len(data.shape)) + self._raise_error_if_invalid_write_dimensions(expected_num_dimensions, len(data.shape)) + + def _verify_array_digital_lines(self, data, is_many_chan, is_many_line): + """Verify the shape of a NumPy array of digital lines. - def _verify_array_digital_lines( - self, data, is_many_chan, is_many_line): - """ Verifies that the shape of the specified NumPy array can be used to read samples from the current task which contains one or more channels that have one or more digital lines per channel, if the @@ -141,36 +137,36 @@ def _verify_array_digital_lines( expected_num_dimensions = None if is_many_chan: if data.shape[0] != number_of_channels: - self._task._raise_invalid_write_num_chans_error( - number_of_channels, data.shape[0]) + self._task._raise_invalid_write_num_chans_error(number_of_channels, data.shape[0]) if is_many_line: expected_num_dimensions = 2 if data.shape[1] != number_of_lines: - self._task._raise_invalid_num_lines_error( - number_of_lines, data.shape[1]) + self._task._raise_invalid_num_lines_error(number_of_lines, data.shape[1]) else: expected_num_dimensions = 1 else: if is_many_line: expected_num_dimensions = 1 if data.shape[0] != number_of_lines: - self._task._raise_invalid_num_lines_error( - number_of_lines, data.shape[0]) + self._task._raise_invalid_num_lines_error(number_of_lines, data.shape[0]) if expected_num_dimensions is not None: - self._raise_error_if_invalid_write_dimensions( - expected_num_dimensions, len(data.shape)) + self._raise_error_if_invalid_write_dimensions(expected_num_dimensions, len(data.shape)) def _raise_error_if_invalid_write_dimensions( - self, num_dimensions_expected, num_dimensions_in_data): + self, num_dimensions_expected, num_dimensions_in_data + ): if num_dimensions_expected != num_dimensions_in_data: raise DaqError( - 'Write cannot be performed because the NumPy array passed ' - 'into this function is not shaped correctly. ' - 'You must pass in a NumPy array of the correct number of ' - 'dimensions based on the write method you use.\n\n' - 'No. of dimensions of NumPy Array provided: {}\n' - 'No. of dimensions of NumPy Array required: {}' - .format(num_dimensions_in_data, num_dimensions_expected), - DAQmxErrors.UNKNOWN, task_name=self._task.name) + "Write cannot be performed because the NumPy array passed " + "into this function is not shaped correctly. " + "You must pass in a NumPy array of the correct number of " + "dimensions based on the write method you use.\n\n" + "No. of dimensions of NumPy Array provided: {}\n" + "No. of dimensions of NumPy Array required: {}".format( + num_dimensions_in_data, num_dimensions_expected + ), + DAQmxErrors.UNKNOWN, + task_name=self._task.name, + ) diff --git a/src/handwritten/stream_writers/_counter_writer.py b/src/handwritten/stream_writers/_counter_writer.py index d005d1c05..2f8b9028a 100644 --- a/src/handwritten/stream_writers/_counter_writer.py +++ b/src/handwritten/stream_writers/_counter_writer.py @@ -1,18 +1,15 @@ from nidaqmx.constants import FillMode - -from nidaqmx.stream_writers._channel_writer_base import ChannelWriterBase, AUTO_START_UNSET +from nidaqmx.stream_writers._channel_writer_base import ( + AUTO_START_UNSET, + ChannelWriterBase, +) class CounterWriter(ChannelWriterBase): - """ - Writes samples to a counter output channel in an NI-DAQmx task. - """ + """Writes samples to a counter output channel in an NI-DAQmx task.""" - def write_many_sample_pulse_frequency( - self, frequencies, duty_cycles, timeout=10.0): - """ - Writes one or more pulse samples in terms of frequency to a - single counter output channel in a task. + def write_many_sample_pulse_frequency(self, frequencies, duty_cycles, timeout=10.0): + """Writes one or more pulse samples in terms of frequency to a single counter output channel in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -43,27 +40,30 @@ def write_many_sample_pulse_frequency( once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote. - """ + """ # noqa: W505 - doc line too long (111 > 100 characters) (auto-generated noqa) self._verify_array(frequencies, False, True) self._verify_array(duty_cycles, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) - return self._interpreter.write_ctr_freq( - self._handle, frequencies.shape[0], auto_start, timeout, - FillMode.GROUP_BY_CHANNEL.value, frequencies, duty_cycles) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False - def write_many_sample_pulse_ticks( - self, high_ticks, low_ticks, timeout=10.0): - """ - Writes one or more pulse samples in terms of ticks to a single - counter output channel in a task. + return self._interpreter.write_ctr_freq( + self._handle, + frequencies.shape[0], + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + frequencies, + duty_cycles, + ) + + def write_many_sample_pulse_ticks(self, high_ticks, low_ticks, timeout=10.0): + """Writes one or more pulse samples in terms of ticks to a single counter output channel in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -94,27 +94,30 @@ def write_many_sample_pulse_ticks( once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote. - """ + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) self._verify_array(high_ticks, False, True) self._verify_array(low_ticks, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) - return self._interpreter.write_ctr_ticks( - self._handle, high_ticks.shape[0], auto_start, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_ticks, low_ticks) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False - def write_many_sample_pulse_time( - self, high_times, low_times, timeout=10.0): - """ - Writes one or more pulse samples in terms of time to a single - counter output channel in a task. + return self._interpreter.write_ctr_ticks( + self._handle, + high_ticks.shape[0], + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_ticks, + low_ticks, + ) + + def write_many_sample_pulse_time(self, high_times, low_times, timeout=10.0): + """Writes one or more pulse samples in terms of time to a single counter output channel in a task. If the task uses on-demand timing, this method returns only after the device generates all samples. On-demand is the default @@ -145,27 +148,30 @@ def write_many_sample_pulse_time( once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote. - """ + """ # noqa: W505 - doc line too long (106 > 100 characters) (auto-generated noqa) self._verify_array(high_times, False, True) self._verify_array(low_times, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) - return self._interpreter.write_ctr_time( - self._handle, high_times.shape[0], auto_start, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_times, low_times) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False - def write_one_sample_pulse_frequency( - self, frequency, duty_cycle, timeout=10): - """ - Writes a new pulse frequency and duty cycle to a single counter - output channel in a task. + return self._interpreter.write_ctr_time( + self._handle, + high_times.shape[0], + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_times, + low_times, + ) + + def write_one_sample_pulse_frequency(self, frequency, duty_cycle, timeout=10): + """Writes a new pulse frequency and duty cycle to a single counter output channel in a task. Args: frequency (float): Specifies at what frequency to generate @@ -189,17 +195,14 @@ def write_one_sample_pulse_frequency( not write all the submitted samples, it returns an error and the number of samples successfully written. """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + return self._interpreter.write_ctr_freq_scalar( - self._handle, auto_start, timeout, frequency, duty_cycle) + self._handle, auto_start, timeout, frequency, duty_cycle + ) - def write_one_sample_pulse_ticks( - self, high_ticks, low_ticks, timeout=10): - """ - Writes a new pulse high tick count and low tick count to a - single counter output channel in a task. + def write_one_sample_pulse_ticks(self, high_ticks, low_ticks, timeout=10): + """Writes a new pulse high tick count and low tick count to a single counter output channel in a task. Args: high_ticks (float): Specifies the number of ticks the pulse @@ -217,18 +220,15 @@ def write_one_sample_pulse_ticks( once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. - """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - + """ # noqa: W505 - doc line too long (110 > 100 characters) (auto-generated noqa) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + return self._interpreter.write_ctr_ticks_scalar( - self._handle, auto_start, timeout, high_ticks, low_ticks) + self._handle, auto_start, timeout, high_ticks, low_ticks + ) - def write_one_sample_pulse_time( - self, high_time, low_time, timeout=10): - """ - Writes a new pulse high time and low time to a single counter - output channel in a task. + def write_one_sample_pulse_time(self, high_time, low_time, timeout=10): + """Writes a new pulse high time and low time to a single counter output channel in a task. Args: high_time (float): Specifies the amount of time the pulse @@ -247,8 +247,8 @@ def write_one_sample_pulse_time( not write all the submitted samples, it returns an error and the number of samples successfully written. """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + return self._interpreter.write_ctr_time_scalar( - self._handle, auto_start, timeout, high_time, low_time) + self._handle, auto_start, timeout, high_time, low_time + ) diff --git a/src/handwritten/stream_writers/_digital_multi_channel_writer.py b/src/handwritten/stream_writers/_digital_multi_channel_writer.py index 58981a8ef..2875beec1 100644 --- a/src/handwritten/stream_writers/_digital_multi_channel_writer.py +++ b/src/handwritten/stream_writers/_digital_multi_channel_writer.py @@ -1,18 +1,15 @@ from nidaqmx.constants import FillMode - -from nidaqmx.stream_writers._channel_writer_base import ChannelWriterBase, AUTO_START_UNSET +from nidaqmx.stream_writers._channel_writer_base import ( + AUTO_START_UNSET, + ChannelWriterBase, +) class DigitalMultiChannelWriter(ChannelWriterBase): - """ - Writes samples to one or more digital output channels in an NI-DAQmx - task. - """ + """Writes samples to one or more digital output channels in an NI-DAQmx task.""" def write_many_sample_port_byte(self, data, timeout=10.0): - """ - Writes one or more 8-bit unsigned integer samples to one or more - digital output channels in a task. + """Writes one or more 8-bit unsigned integer samples to one or more digital output channels in a task. Use this method for devices with up to 8 lines per port. @@ -44,24 +41,23 @@ def write_many_sample_port_byte(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (110 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_digital_u8( - self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_many_sample_port_uint16(self, data, timeout=10.0): - """ - Writes one or more 16-bit unsigned integer samples to one or - more digital output channels in a task. + """Writes one or more 16-bit unsigned integer samples to one or more digital output channels in a task. Use this method for devices with up to 16 lines per port. @@ -93,24 +89,23 @@ def write_many_sample_port_uint16(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (111 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_digital_u16( - self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_many_sample_port_uint32(self, data, timeout=10.0): - """ - Writes one or more 32-bit unsigned integer samples to one or - more digital output channels in a task. + """Writes one or more 32-bit unsigned integer samples to one or more digital output channels in a task. Use this method for devices with up to 32 lines per port. @@ -142,25 +137,25 @@ def write_many_sample_port_uint32(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote to each channel in the task. - """ + """ # noqa: W505 - doc line too long (111 > 100 characters) (auto-generated noqa) self._verify_array(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_digital_u32( - self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[1], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample_multi_line(self, data, timeout=10): - """ - Writes a single boolean sample to one or more digital output - channels in a task. The channel can contain multiple digital - lines. + """Writes a single boolean sample to one or more digital output channels in a task. + + The channel can contain multiple digital lines. Args: data (numpy.ndarray): Contains a 2D NumPy array of boolean @@ -183,18 +178,17 @@ def write_one_sample_multi_line(self, data, timeout=10): and the number of samples successfully written. """ self._verify_array_digital_lines(data, True, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True return self._interpreter.write_digital_lines( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample_one_line(self, data, timeout=10): - """ - Writes a single boolean sample to one or more digital output - channels in a task. The channel can contain only one digital - line. + """Writes a single boolean sample to one or more digital output channels in a task. + + The channel can contain only one digital line. Args: data (numpy.ndarray): Contains a 1D NumPy array of boolean @@ -217,17 +211,15 @@ def write_one_sample_one_line(self, data, timeout=10): and the number of samples successfully written. """ self._verify_array_digital_lines(data, True, False) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True return self._interpreter.write_digital_lines( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample_port_byte(self, data, timeout=10): - """ - Writes a single 8-bit unsigned integer sample to one or more - digital output channels in a task. + """Writes a single 8-bit unsigned integer sample to one or more digital output channels in a task. Use this method for devices with up to 8 lines per port. @@ -250,19 +242,17 @@ def write_one_sample_port_byte(self, data, timeout=10): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. - """ + """ # noqa: W505 - doc line too long (106 > 100 characters) (auto-generated noqa) self._verify_array(data, True, False) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True return self._interpreter.write_digital_u8( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample_port_uint16(self, data, timeout=10): - """ - Writes a single 16-bit unsigned integer sample to one or more - digital output channels in a task. + """Writes a single 16-bit unsigned integer sample to one or more digital output channels in a task. Use this method for devices with up to 16 lines per port. @@ -285,19 +275,17 @@ def write_one_sample_port_uint16(self, data, timeout=10): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. - """ + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) self._verify_array(data, True, False) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True return self._interpreter.write_digital_u16( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample_port_uint32(self, data, timeout=10): - """ - Writes a single 32-bit unsigned integer sample to one or more - digital output channels in a task. + """Writes a single 32-bit unsigned integer sample to one or more digital output channels in a task. Use this method for devices with up to 32 lines per port. @@ -320,11 +308,11 @@ def write_one_sample_port_uint32(self, data, timeout=10): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. - """ + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) self._verify_array(data, True, False) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True return self._interpreter.write_digital_u32( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) diff --git a/src/handwritten/stream_writers/_digital_single_channel_writer.py b/src/handwritten/stream_writers/_digital_single_channel_writer.py index c1c731858..6f5dbb485 100644 --- a/src/handwritten/stream_writers/_digital_single_channel_writer.py +++ b/src/handwritten/stream_writers/_digital_single_channel_writer.py @@ -1,20 +1,17 @@ import numpy from nidaqmx.constants import FillMode - -from nidaqmx.stream_writers._channel_writer_base import ChannelWriterBase, AUTO_START_UNSET +from nidaqmx.stream_writers._channel_writer_base import ( + AUTO_START_UNSET, + ChannelWriterBase, +) class DigitalSingleChannelWriter(ChannelWriterBase): - """ - Writes samples to a single digital output channel in an NI-DAQmx - task. - """ + """Writes samples to a single digital output channel in an NI-DAQmx task.""" def write_many_sample_port_byte(self, data, timeout=10.0): - """ - Writes one or more 8-bit unsigned integer samples to a single - digital output channel in a task. + """Writes one or more 8-bit unsigned integer samples to a single digital output channel in a task. Use this method for devices with up to 8 lines per port. @@ -42,24 +39,23 @@ def write_many_sample_port_byte(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote. - """ + """ # noqa: W505 - doc line too long (106 > 100 characters) (auto-generated noqa) self._verify_array(data, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_digital_u8( - self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_many_sample_port_uint16(self, data, timeout=10.0): - """ - Writes one or more 16-bit unsigned integer samples to a single - digital output channel in a task. + """Writes one or more 16-bit unsigned integer samples to a single digital output channel in a task. Use this method for devices with up to 16 lines per port. @@ -87,24 +83,23 @@ def write_many_sample_port_uint16(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote. - """ + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) self._verify_array(data, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_digital_u16( - self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_many_sample_port_uint32(self, data, timeout=10.0): - """ - Writes one or more 32-bit unsigned integer samples to a single - digital output channel in a task. + """Writes one or more 32-bit unsigned integer samples to a single digital output channel in a task. Use this method for devices with up to 32 lines per port. @@ -132,25 +127,25 @@ def write_many_sample_port_uint32(self, data, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: Specifies the actual number of samples this method successfully wrote. - """ + """ # noqa: W505 - doc line too long (107 > 100 characters) (auto-generated noqa) self._verify_array(data, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else False) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else False return self._interpreter.write_digital_u32( - self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, data.shape[0], auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample_multi_line(self, data, timeout=10): - """ - Writes a single boolean sample to a single digital output - channel in a task. The channel can contain multiple digital - lines. + """Writes a single boolean sample to a single digital output channel in a task. + + The channel can contain multiple digital lines. Args: data (numpy.ndarray): Contains a 1D NumPy array of boolean @@ -169,18 +164,17 @@ def write_one_sample_multi_line(self, data, timeout=10): and the number of samples successfully written. """ self._verify_array_digital_lines(data, False, True) - - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) + + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True return self._interpreter.write_digital_lines( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data + ) def write_one_sample_one_line(self, data, timeout=10): - """ - Writes a single boolean sample to a single digital output - channel in a task. The channel can contain only one digital - line. + """Writes a single boolean sample to a single digital output channel in a task. + + The channel can contain only one digital line. Args: data (int): Specifies the boolean sample to write to the @@ -197,18 +191,16 @@ def write_one_sample_one_line(self, data, timeout=10): not write all the submitted samples, it returns an error and the number of samples successfully written. """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + numpy_array = numpy.asarray([data], dtype=bool) return self._interpreter.write_digital_lines( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, numpy_array) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, numpy_array + ) def write_one_sample_port_byte(self, data, timeout=10): - """ - Writes a single 8-bit unsigned integer sample to a single - digital output channel in a task. + """Writes a single 8-bit unsigned integer sample to a single digital output channel in a task. Use this method for devices with up to 8 lines per port. @@ -226,19 +218,17 @@ def write_one_sample_port_byte(self, data, timeout=10): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. - """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - + """ # noqa: W505 - doc line too long (102 > 100 characters) (auto-generated noqa) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + numpy_array = numpy.asarray([data], dtype=numpy.uint8) return self._interpreter.write_digital_u8( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, numpy_array) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, numpy_array + ) def write_one_sample_port_uint16(self, data, timeout=10): - """ - Writes a single 16-bit unsigned integer sample to a single - digital output channel in a task. + """Writes a single 16-bit unsigned integer sample to a single digital output channel in a task. Use this method for devices with up to 16 lines per port. @@ -256,19 +246,17 @@ def write_one_sample_port_uint16(self, data, timeout=10): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. - """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - + """ # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + numpy_array = numpy.asarray([data], dtype=numpy.uint16) return self._interpreter.write_digital_u16( - self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, numpy_array) + self._handle, 1, auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, numpy_array + ) def write_one_sample_port_uint32(self, data, timeout=10): - """ - Writes a single 32-bit unsigned integer sample to a single - digital output channel in a task. + """Writes a single 32-bit unsigned integer sample to a single digital output channel in a task. Use this method for devices with up to 32 lines per port. @@ -286,9 +274,7 @@ def write_one_sample_port_uint32(self, data, timeout=10): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. - """ - auto_start = (self._auto_start if self._auto_start is not - AUTO_START_UNSET else True) - - return self._interpreter.write_digital_scalar_u32( - self._handle, auto_start, timeout, data) + """ # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) + auto_start = self._auto_start if self._auto_start is not AUTO_START_UNSET else True + + return self._interpreter.write_digital_scalar_u32(self._handle, auto_start, timeout, data) diff --git a/src/handwritten/system/__init__.py b/src/handwritten/system/__init__.py index 6d57599ca..cbcc8f80f 100644 --- a/src/handwritten/system/__init__.py +++ b/src/handwritten/system/__init__.py @@ -1,9 +1,19 @@ -from nidaqmx.system.system import ( - System, AOPowerUpState, CDAQSyncConnection, DOPowerUpState, - DOResistorPowerUpState) +"""NI-DAQmx system classes.""" + from nidaqmx.system.device import Device from nidaqmx.system.physical_channel import PhysicalChannel +from nidaqmx.system.system import ( + AOPowerUpState, + CDAQSyncConnection, + DOPowerUpState, + DOResistorPowerUpState, + System, +) from nidaqmx.system.watchdog import ( - WatchdogTask, AOExpirationState, COExpirationState, DOExpirationState) + AOExpirationState, + COExpirationState, + DOExpirationState, + WatchdogTask, +) -__all__ = ['system', 'device', 'physical_channel', 'storage', 'watchdog'] +__all__ = ["system", "device", "physical_channel", "storage", "watchdog"] diff --git a/src/handwritten/system/_collections/device_collection.py b/src/handwritten/system/_collections/device_collection.py index 01262ee32..e1f13a38f 100644 --- a/src/handwritten/system/_collections/device_collection.py +++ b/src/handwritten/system/_collections/device_collection.py @@ -1,24 +1,24 @@ from collections.abc import Sequence -from nidaqmx.errors import DaqError from nidaqmx.error_codes import DAQmxErrors +from nidaqmx.errors import DaqError from nidaqmx.system.device import Device, _DeviceAlternateConstructor from nidaqmx.utils import unflatten_channel_string class DeviceCollection(Sequence): - """ - Contains the collection of devices for a DAQmx system. - + """Contains the collection of devices for a DAQmx system. + This class defines methods that implements a container object. """ + def __init__(self, interpreter): - """ - Do not construct this object directly; instead, call nidaqmx.system.System.local().devices. - """ + """Do not construct this object directly; instead, call nidaqmx.system.System.local().devices.""" # noqa: W505 - doc line too long (105 > 100 characters) (auto-generated noqa) self._interpreter = interpreter - - def __contains__(self, item): + + def __contains__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, item + ): device_names = self.device_names if isinstance(item, str): @@ -28,14 +28,13 @@ def __contains__(self, item): return item.name in device_names return False - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return True return False def __getitem__(self, index): - """ - Indexes a subset of devices on this device collection. + """Indexes a subset of devices on this device collection. Args: index: The value of the index. The following index types are @@ -48,15 +47,19 @@ def __getitem__(self, index): - int: Index/position of the device in the collection. - slice: Range of the indexes/positions of devices in the collection. + Returns: - List[nidaqmx.system.device.Device]: - + List[nidaqmx.system.device.Device]: + Indicates the subset of devices indexed. """ if isinstance(index, int): return _DeviceAlternateConstructor(self.device_names[index], self._interpreter) elif isinstance(index, slice): - return [_DeviceAlternateConstructor(name, self._interpreter) for name in self.device_names[index]] + return [ + _DeviceAlternateConstructor(name, self._interpreter) + for name in self.device_names[index] + ] elif isinstance(index, str): device_names = unflatten_channel_string(index) if len(device_names) == 1: @@ -64,20 +67,21 @@ def __getitem__(self, index): return [_DeviceAlternateConstructor(name, self._interpreter) for name in device_names] else: raise DaqError( - 'Invalid index type "{}" used to access collection.' - .format(type(index)), DAQmxErrors.UNKNOWN) + 'Invalid index type "{}" used to access collection.'.format(type(index)), + DAQmxErrors.UNKNOWN, + ) - def __iter__(self): + def __iter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) for device_name in self.device_names: yield _DeviceAlternateConstructor(device_name, self._interpreter) - def __len__(self): + def __len__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return len(self.device_names) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __reversed__(self): + def __reversed__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) device_names = self.device_names device_names.reverse() @@ -86,9 +90,6 @@ def __reversed__(self): @property def device_names(self): - """ - List[str]: Indicates the names of all devices on this device - collection. - """ - val = self._interpreter.get_system_info_attribute_string(0x193b) + """List[str]: Indicates the names of all devices on this device collection.""" + val = self._interpreter.get_system_info_attribute_string(0x193B) return unflatten_channel_string(val) diff --git a/src/handwritten/system/_collections/persisted_channel_collection.py b/src/handwritten/system/_collections/persisted_channel_collection.py index d389a5f84..06c0910e3 100644 --- a/src/handwritten/system/_collections/persisted_channel_collection.py +++ b/src/handwritten/system/_collections/persisted_channel_collection.py @@ -1,23 +1,27 @@ from collections.abc import Sequence -from nidaqmx.errors import DaqError from nidaqmx.error_codes import DAQmxErrors -from nidaqmx.system.storage.persisted_channel import PersistedChannel, _PersistedChannelAlternateConstructor +from nidaqmx.errors import DaqError +from nidaqmx.system.storage.persisted_channel import ( + PersistedChannel, + _PersistedChannelAlternateConstructor, +) from nidaqmx.utils import unflatten_channel_string + class PersistedChannelCollection(Sequence): - """ - Contains the collection of global channels for a DAQmx system. - + """Contains the collection of global channels for a DAQmx system. + This class defines methods that implements a container object. """ + def __init__(self, interpreter): - """ - Do not construct this object directly; instead, call nidaqmx.system.System.local().global_channels. - """ + """Do not construct this object directly; instead, call nidaqmx.system.System.local().global_channels.""" # noqa: W505 - doc line too long (113 > 100 characters) (auto-generated noqa) self._interpreter = interpreter - - def __contains__(self, item): + + def __contains__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, item + ): channel_names = self.global_channel_names if isinstance(item, str): @@ -26,15 +30,13 @@ def __contains__(self, item): elif isinstance(item, PersistedChannel): return item._name in channel_names - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return True return False def __getitem__(self, index): - """ - Indexes a subset of global channels on this global channel - collection. + """Indexes a subset of global channels on this global channel collection. Args: index: The value of the index. The following index types @@ -48,37 +50,45 @@ def __getitem__(self, index): collection. - slice: Range of the indexes/positions of global channels in the collection. + Returns: List[nidaqmx.system.storage.persisted_channel.PersistedChannel]: - + Indicates the of global channels indexed. """ if isinstance(index, int): - return _PersistedChannelAlternateConstructor(self.global_channel_names[index], self._interpreter) + return _PersistedChannelAlternateConstructor( + self.global_channel_names[index], self._interpreter + ) elif isinstance(index, slice): - return [_PersistedChannelAlternateConstructor(name, self._interpreter) for name in - self.global_channel_names[index]] + return [ + _PersistedChannelAlternateConstructor(name, self._interpreter) + for name in self.global_channel_names[index] + ] elif isinstance(index, str): names = unflatten_channel_string(index) if len(names) == 1: return _PersistedChannelAlternateConstructor(names[0], self._interpreter) - return [_PersistedChannelAlternateConstructor(name, self._interpreter) for name in names] + return [ + _PersistedChannelAlternateConstructor(name, self._interpreter) for name in names + ] else: raise DaqError( - 'Invalid index type "{}" used to access collection.' - .format(type(index)), DAQmxErrors.UNKNOWN) + 'Invalid index type "{}" used to access collection.'.format(type(index)), + DAQmxErrors.UNKNOWN, + ) - def __iter__(self): + def __iter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) for channel_name in self.global_channel_names: yield _PersistedChannelAlternateConstructor(channel_name, self._interpreter) - def __len__(self): + def __len__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return len(self.global_channel_names) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __reversed__(self): + def __reversed__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) channel_names = self.global_channel_names channel_names.reverse() @@ -87,9 +97,6 @@ def __reversed__(self): @property def global_channel_names(self): - """ - List[str]: The names of all the global channels on this - collection. - """ + """List[str]: The names of all the global channels on this collection.""" val = self._interpreter.get_system_info_attribute_string(0x1265) return unflatten_channel_string(val) diff --git a/src/handwritten/system/_collections/persisted_scale_collection.py b/src/handwritten/system/_collections/persisted_scale_collection.py index bdbcc5adb..dc1785c06 100644 --- a/src/handwritten/system/_collections/persisted_scale_collection.py +++ b/src/handwritten/system/_collections/persisted_scale_collection.py @@ -1,23 +1,27 @@ from collections.abc import Sequence -from nidaqmx.errors import DaqError from nidaqmx.error_codes import DAQmxErrors -from nidaqmx.system.storage.persisted_scale import PersistedScale, _PersistedScaleAlternateConstructor +from nidaqmx.errors import DaqError +from nidaqmx.system.storage.persisted_scale import ( + PersistedScale, + _PersistedScaleAlternateConstructor, +) from nidaqmx.utils import unflatten_channel_string + class PersistedScaleCollection(Sequence): - """ - Contains the collection of custom scales on a DAQmx system. - + """Contains the collection of custom scales on a DAQmx system. + This class defines methods that implements a container object. """ + def __init__(self, interpreter): - """ - Do not construct this object directly; instead, call nidaqmx.system.System.local().scales. - """ + """Do not construct this object directly; instead, call nidaqmx.system.System.local().scales.""" # noqa: W505 - doc line too long (104 > 100 characters) (auto-generated noqa) self._interpreter = interpreter - - def __contains__(self, item): + + def __contains__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, item + ): scale_names = self.scale_names if isinstance(item, str): @@ -26,14 +30,13 @@ def __contains__(self, item): elif isinstance(item, PersistedScale): return item._name in scale_names - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return True return False def __getitem__(self, index): - """ - Indexes a subset of custom scales on this collection. + """Indexes a subset of custom scales on this collection. Args: index: The value of the index. The following index types @@ -47,16 +50,19 @@ def __getitem__(self, index): collection. - slice: Range of the indexes/positions of custom scales in the collection. + Returns: List[nidaqmx.system.storage.persisted_scale.PersistedScale]: - + Indicates the subset of custom scales indexed. """ if isinstance(index, int): return _PersistedScaleAlternateConstructor(self.scale_names[index], self._interpreter) elif isinstance(index, slice): - return [_PersistedScaleAlternateConstructor(name, self._interpreter) for name in - self.scale_names[index]] + return [ + _PersistedScaleAlternateConstructor(name, self._interpreter) + for name in self.scale_names[index] + ] elif isinstance(index, str): names = unflatten_channel_string(index) if len(names) == 1: @@ -64,20 +70,21 @@ def __getitem__(self, index): return [_PersistedScaleAlternateConstructor(name, self._interpreter) for name in names] else: raise DaqError( - 'Invalid index type "{}" used to access collection.' - .format(type(index)), DAQmxErrors.UNKNOWN) + 'Invalid index type "{}" used to access collection.'.format(type(index)), + DAQmxErrors.UNKNOWN, + ) - def __iter__(self): + def __iter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) for scale_name in self.scale_names: yield _PersistedScaleAlternateConstructor(scale_name, self._interpreter) - def __len__(self): + def __len__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return len(self.scale_names) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __reversed__(self): + def __reversed__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) scale_names = self.scale_names scale_names.reverse() @@ -86,9 +93,6 @@ def __reversed__(self): @property def scale_names(self): - """ - List[str]: Indicates the names of all the custom scales on this - collection. - """ + """List[str]: Indicates the names of all the custom scales on this collection.""" val = self._interpreter.get_system_info_attribute_string(0x1266) return unflatten_channel_string(val) diff --git a/src/handwritten/system/_collections/persisted_task_collection.py b/src/handwritten/system/_collections/persisted_task_collection.py index 5d0adea4c..43b1a01e2 100644 --- a/src/handwritten/system/_collections/persisted_task_collection.py +++ b/src/handwritten/system/_collections/persisted_task_collection.py @@ -1,23 +1,27 @@ from collections.abc import Sequence -from nidaqmx.errors import DaqError from nidaqmx.error_codes import DAQmxErrors -from nidaqmx.system.storage.persisted_task import PersistedTask, _PersistedTaskAlternateConstructor +from nidaqmx.errors import DaqError +from nidaqmx.system.storage.persisted_task import ( + PersistedTask, + _PersistedTaskAlternateConstructor, +) from nidaqmx.utils import unflatten_channel_string + class PersistedTaskCollection(Sequence): - """ - Contains the collection of task saved on a DAQmx system. - + """Contains the collection of task saved on a DAQmx system. + This class defines methods that implements a container object. """ + def __init__(self, interpreter): - """ - Do not construct this object directly; instead, call nidaqmx.system.System.local().tasks. - """ + """Do not construct this object directly; instead, call nidaqmx.system.System.local().tasks.""" # noqa: W505 - doc line too long (103 > 100 characters) (auto-generated noqa) self._interpreter = interpreter - - def __contains__(self, item): + + def __contains__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, item + ): task_names = self.task_names if isinstance(item, str): @@ -26,14 +30,13 @@ def __contains__(self, item): elif isinstance(item, PersistedTask): return item._name in task_names - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return True return False def __getitem__(self, index): - """ - Indexes a subset of saved tasks on this collection. + """Indexes a subset of saved tasks on this collection. Args: index: The value of the index. The following index types @@ -47,16 +50,19 @@ def __getitem__(self, index): collection. - slice: Range of the indexes/positions of saved tasks in the collection. + Returns: List[nidaqmx.system.storage.persisted_task.PersistedTask]: - + Indicates the subset of saved tasks indexed. """ if isinstance(index, int): return _PersistedTaskAlternateConstructor(self.task_names[index], self._interpreter) elif isinstance(index, slice): - return [_PersistedTaskAlternateConstructor(name, self._interpreter) for name in - self.task_names[index]] + return [ + _PersistedTaskAlternateConstructor(name, self._interpreter) + for name in self.task_names[index] + ] elif isinstance(index, str): names = unflatten_channel_string(index) if len(names) == 1: @@ -64,20 +70,21 @@ def __getitem__(self, index): return [_PersistedTaskAlternateConstructor(name, self._interpreter) for name in names] else: raise DaqError( - 'Invalid index type "{}" used to access collection.' - .format(type(index)), DAQmxErrors.UNKNOWN) + 'Invalid index type "{}" used to access collection.'.format(type(index)), + DAQmxErrors.UNKNOWN, + ) - def __iter__(self): + def __iter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) for task_name in self.task_names: yield _PersistedTaskAlternateConstructor(task_name, self._interpreter) - def __len__(self): + def __len__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return len(self.task_names) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __reversed__(self): + def __reversed__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) task_names = self.task_names task_names.reverse() @@ -86,8 +93,6 @@ def __reversed__(self): @property def task_names(self): - """ - List[str]: Indicates the names of all the tasks on this collection. - """ + """List[str]: Indicates the names of all the tasks on this collection.""" val = self._interpreter.get_system_info_attribute_string(0x1267) return unflatten_channel_string(val) diff --git a/src/handwritten/system/_collections/physical_channel_collection.py b/src/handwritten/system/_collections/physical_channel_collection.py index 7eff2e40e..5248e15c9 100644 --- a/src/handwritten/system/_collections/physical_channel_collection.py +++ b/src/handwritten/system/_collections/physical_channel_collection.py @@ -1,24 +1,28 @@ from collections.abc import Sequence -from nidaqmx.errors import DaqError from nidaqmx.error_codes import DAQmxErrors -from nidaqmx.system.physical_channel import PhysicalChannel, _PhysicalChannelAlternateConstructor -from nidaqmx.utils import unflatten_channel_string, flatten_channel_string +from nidaqmx.errors import DaqError +from nidaqmx.system.physical_channel import ( + PhysicalChannel, + _PhysicalChannelAlternateConstructor, +) +from nidaqmx.utils import flatten_channel_string, unflatten_channel_string + class PhysicalChannelCollection(Sequence): - """ - Contains the collection of physical channels for a DAQmx device. - + """Contains the collection of physical channels for a DAQmx device. + This class defines methods that implements a container object. """ + def __init__(self, device_name, interpreter): - """ - Do not construct this object directly; instead, construct a nidaqmx.system.Device and use the appropriate property, such as device.ai_physical_channels. - """ + """Do not construct this object directly; instead, construct a nidaqmx.system.Device and use the appropriate property, such as device.ai_physical_channels.""" # noqa: W505 - doc line too long (166 > 100 characters) (auto-generated noqa) self._name = device_name self._interpreter = interpreter - def __contains__(self, item): + def __contains__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, item + ): channel_names = self.channel_names if isinstance(item, str): @@ -28,15 +32,13 @@ def __contains__(self, item): return item._name in channel_names return False - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return self._name == other._name return False def __getitem__(self, index): - """ - Indexes a subset of physical channels on this physical channel - collection. + """Indexes a subset of physical channels on this physical channel collection. Args: index: The value of the index. The following index types @@ -51,45 +53,55 @@ def __getitem__(self, index): collection. - slice: Range of the indexes/positions of physical channels in the collection. + Returns: - nidaqmx.system.physical_channel.PhysicalChannel: - + nidaqmx.system.physical_channel.PhysicalChannel: + Indicates the subset of physical channels indexed. """ if isinstance(index, int): - return _PhysicalChannelAlternateConstructor(self.channel_names[index], self._interpreter) + return _PhysicalChannelAlternateConstructor( + self.channel_names[index], self._interpreter + ) elif isinstance(index, slice): - return [_PhysicalChannelAlternateConstructor(channel, self._interpreter) for channel in self.channel_names[index]] + return [ + _PhysicalChannelAlternateConstructor(channel, self._interpreter) + for channel in self.channel_names[index] + ] elif isinstance(index, str): requested_channels = unflatten_channel_string(index) - # Ensure the channel names are fully qualified. If the channel is invalid, the user will get errors from the + # Ensure the channel names are fully qualified. If the channel is invalid, the user will get errors from the # noqa: W505 - doc line too long (120 > 100 characters) (auto-generated noqa) # channel objects on use. channels_to_use = [] for channel in requested_channels: if channel.startswith(f"{self._name}/"): channels_to_use.append(channel) else: - channels_to_use.append(f'{self._name}/{channel}') + channels_to_use.append(f"{self._name}/{channel}") if len(channels_to_use) == 1: return _PhysicalChannelAlternateConstructor(channels_to_use[0], self._interpreter) - return [_PhysicalChannelAlternateConstructor(channel, self._interpreter) for channel in channels_to_use] + return [ + _PhysicalChannelAlternateConstructor(channel, self._interpreter) + for channel in channels_to_use + ] else: raise DaqError( - 'Invalid index type "{}" used to access collection.' - .format(type(index)), DAQmxErrors.UNKNOWN) + 'Invalid index type "{}" used to access collection.'.format(type(index)), + DAQmxErrors.UNKNOWN, + ) - def __iter__(self): + def __iter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) for channel_name in self.channel_names: yield _PhysicalChannelAlternateConstructor(channel_name, self._interpreter) - def __len__(self): + def __len__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return len(self.channel_names) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __reversed__(self): + def __reversed__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) channel_names = self.channel_names channel_names.reverse() @@ -98,125 +110,124 @@ def __reversed__(self): @property def all(self): - """ - nidaqmx.system.physical_channel.PhysicalChannel: Specifies a - physical channel object that represents the entire list of - physical channels on this channel collection. - """ - return _PhysicalChannelAlternateConstructor(flatten_channel_string(self.channel_names), self._interpreter) + """nidaqmx.system.physical_channel.PhysicalChannel: Specifies a physical channel object that represents the entire list of physical channels on this channel collection.""" # noqa: W505 - doc line too long (179 > 100 characters) (auto-generated noqa) + return _PhysicalChannelAlternateConstructor( + flatten_channel_string(self.channel_names), self._interpreter + ) @property def channel_names(self): - """ - List[str]: Specifies the entire list of physical channels in this - collection. - """ + """List[str]: Specifies the entire list of physical channels in this collection.""" raise NotImplementedError() class AIPhysicalChannelCollection(PhysicalChannelCollection): - """ - Contains the collection of analog input physical channels for a - DAQmx device. - + """Contains the collection of analog input physical channels for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): - val = self._interpreter.get_device_attribute_string(self._name, 0x231e) + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): + val = self._interpreter.get_device_attribute_string(self._name, 0x231E) return unflatten_channel_string(val) class AOPhysicalChannelCollection(PhysicalChannelCollection): - """ - Contains the collection of analog output physical channels for a - DAQmx device. - + """Contains the collection of analog output physical channels for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): - val = self._interpreter.get_device_attribute_string(self._name, 0x231f) + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): + val = self._interpreter.get_device_attribute_string(self._name, 0x231F) return unflatten_channel_string(val) class CIPhysicalChannelCollection(PhysicalChannelCollection): - """ - Contains the collection of counter input physical channels for a - DAQmx device. - + """Contains the collection of counter input physical channels for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): val = self._interpreter.get_device_attribute_string(self._name, 0x2324) return unflatten_channel_string(val) class COPhysicalChannelCollection(PhysicalChannelCollection): - """ - Contains the collection of counter output physical channels for a - DAQmx device. - + """Contains the collection of counter output physical channels for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): val = self._interpreter.get_device_attribute_string(self._name, 0x2325) return unflatten_channel_string(val) class DILinesCollection(PhysicalChannelCollection): - """ - Contains the collection of digital input lines for a DAQmx device. - + """Contains the collection of digital input lines for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): val = self._interpreter.get_device_attribute_string(self._name, 0x2320) return unflatten_channel_string(val) class DOLinesCollection(PhysicalChannelCollection): - """ - Contains the collection of digital output lines for a DAQmx device. - + """Contains the collection of digital output lines for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): val = self._interpreter.get_device_attribute_string(self._name, 0x2322) return unflatten_channel_string(val) class DIPortsCollection(PhysicalChannelCollection): - """ - Contains the collection of digital input ports for a DAQmx device. - + """Contains the collection of digital input ports for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): val = self._interpreter.get_device_attribute_string(self._name, 0x2321) return unflatten_channel_string(val) class DOPortsCollection(PhysicalChannelCollection): - """ - Contains the collection of digital output ports for a DAQmx device. - + """Contains the collection of digital output ports for a DAQmx device. + This class defines methods that implements a container object. """ @property - def channel_names(self): + def channel_names( # noqa: D102 - Missing docstring in public method (auto-generated noqa) + self, + ): val = self._interpreter.get_device_attribute_string(self._name, 0x2323) return unflatten_channel_string(val) diff --git a/src/handwritten/system/_watchdog_modules/expiration_states_collection.py b/src/handwritten/system/_watchdog_modules/expiration_states_collection.py index 5d437ef92..6fee56327 100644 --- a/src/handwritten/system/_watchdog_modules/expiration_states_collection.py +++ b/src/handwritten/system/_watchdog_modules/expiration_states_collection.py @@ -3,41 +3,43 @@ class ExpirationStatesCollection: - """ - Contains the collection of expiration states for a DAQmx Watchdog Task. - + """Contains the collection of expiration states for a DAQmx Watchdog Task. + This class defines methods that implements a container object. """ - def __init__(self, task_handle, interpreter): + + def __init__( # noqa: D107 - Missing docstring in __init__ (auto-generated noqa) + self, task_handle, interpreter + ): self._handle = task_handle self._interpreter = interpreter - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return self._handle == other._handle return False - def __hash__(self): + def __hash__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return self._interpreter.hash_task_handle(self._handle) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) def __getitem__(self, index): - """ - Indexes an expiration state on this collection. + """Indexes an expiration state on this collection. Args: index (str): Name of the physical channel of which the expiration state to retrieve. + Returns: nidaqmx.system._watchdog_modules.expiration_state.ExpirationState: - + The object representing the indexed expiration state. """ if isinstance(index, str): return ExpirationState(self._handle, index, self._interpreter) else: raise DaqError( - 'Invalid index type "{}" used to access expiration states.' - .format(type(index)), -1) + 'Invalid index type "{}" used to access expiration states.'.format(type(index)), -1 + ) diff --git a/src/handwritten/system/storage/__init__.py b/src/handwritten/system/storage/__init__.py index 90e8571ba..eb2a0887a 100644 --- a/src/handwritten/system/storage/__init__.py +++ b/src/handwritten/system/storage/__init__.py @@ -1,5 +1,7 @@ +"""NI-DAQmx storage classes.""" + from nidaqmx.system.storage.persisted_channel import PersistedChannel from nidaqmx.system.storage.persisted_scale import PersistedScale from nidaqmx.system.storage.persisted_task import PersistedTask -__all__ = ['persisted_channel', 'persisted_scale', 'persisted_task'] +__all__ = ["persisted_channel", "persisted_scale", "persisted_task"] diff --git a/src/handwritten/system/storage/persisted_channel.py b/src/handwritten/system/storage/persisted_channel.py index fafa6aede..e0e4227e6 100644 --- a/src/handwritten/system/storage/persisted_channel.py +++ b/src/handwritten/system/storage/persisted_channel.py @@ -1,19 +1,22 @@ +"""NI-DAQmx persisted channel classes.""" + from nidaqmx import utils -__all__ = ['PersistedChannel'] +__all__ = ["PersistedChannel"] class PersistedChannel: - """ - Represents a saved DAQmx global channel. + """Represents a saved DAQmx global channel. Use the DAQmx Persisted Channel properties to query information about programmatically saved global channels. """ - __slots__ = ['_name', '_interpreter', '__weakref__'] + + __slots__ = ["_name", "_interpreter", "__weakref__"] def __init__(self, name, *, grpc_options=None): - """ + """Initialize a new PersistedChannel. + Args: name (str): Specifies the name of the global channel. grpc_options (Optional[:class:`~nidaqmx.GrpcSessionOptions`]): Specifies @@ -22,56 +25,45 @@ def __init__(self, name, *, grpc_options=None): self._name = name self._interpreter = utils._select_interpreter(grpc_options) - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return self._name == other._name return False - def __hash__(self): + def __hash__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return hash(self._name) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __repr__(self): - return f'PersistedChannel(name={self._name})' + def __repr__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + return f"PersistedChannel(name={self._name})" @property def name(self): - """ - str: Indicates the name of the global channel. - """ + """str: Indicates the name of the global channel.""" return self._name @property def author(self): - """ - str: Indicates the author of the global channel. - """ - val = self._interpreter.get_persisted_chan_attribute_string(self._name, 0x22d0) + """str: Indicates the author of the global channel.""" + val = self._interpreter.get_persisted_chan_attribute_string(self._name, 0x22D0) return val @property def allow_interactive_editing(self): - """ - bool: Indicates whether the global channel can be edited in the - DAQ Assistant. - """ - val = self._interpreter.get_persisted_chan_attribute_bool(self._name, 0x22d1) + """bool: Indicates whether the global channel can be edited in the DAQ Assistant.""" + val = self._interpreter.get_persisted_chan_attribute_bool(self._name, 0x22D1) return val @property def allow_interactive_deletion(self): - """ - bool: Indicates whether the global channel can be deleted - through MAX. - """ - val = self._interpreter.get_persisted_chan_attribute_bool(self._name, 0x22d2) + """bool: Indicates whether the global channel can be deleted through MAX.""" + val = self._interpreter.get_persisted_chan_attribute_bool(self._name, 0x22D2) return val def delete(self): - """ - Deletes this global channel from MAX. + """Deletes this global channel from MAX. This function does not remove the global channel from tasks that use it. @@ -80,16 +72,17 @@ def delete(self): class _PersistedChannelAlternateConstructor(PersistedChannel): - """ - Provide an alternate constructor for the PersistedChannel object. + """Provide an alternate constructor for the PersistedChannel object. This is a private API used to instantiate a PersistedChannel with an existing interpreter. """ - # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. + + # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. # noqa: W505 - doc line too long (108 > 100 characters) (auto-generated noqa) __slots__ = () def __init__(self, name, interpreter): - """ + """Initialize a new PersistedChannel with an existing interpreter. + Args: name: Specifies the name of the PersistedChannel. interpreter: Specifies the interpreter instance. @@ -100,4 +93,4 @@ def __init__(self, name, interpreter): # Use meta-programming to change the type of this object to PersistedChannel, # so the user isn't confused when doing introspection. - self.__class__ = PersistedChannel # type: ignore[assignment] \ No newline at end of file + self.__class__ = PersistedChannel # type: ignore[assignment] diff --git a/src/handwritten/system/storage/persisted_scale.py b/src/handwritten/system/storage/persisted_scale.py index 784f94244..c4d340a12 100644 --- a/src/handwritten/system/storage/persisted_scale.py +++ b/src/handwritten/system/storage/persisted_scale.py @@ -1,20 +1,23 @@ +"""NI-DAQmx persisted scale classes.""" + from nidaqmx import utils from nidaqmx.scale import _ScaleAlternateConstructor -__all__ = ['PersistedScale'] +__all__ = ["PersistedScale"] class PersistedScale: - """ - Represents a saved DAQmx custom scale. + """Represents a saved DAQmx custom scale. Use the DAQmx Persisted Scale properties to query information about programmatically saved custom scales. """ - __slots__ = ['_name', '_interpreter', '__weakref__'] + + __slots__ = ["_name", "_interpreter", "__weakref__"] def __init__(self, name, *, grpc_options=None): - """ + """Initialize a new PersistedScale. + Args: name (str): Specifies the name of the saved scale. grpc_options (Optional[:class:`~nidaqmx.GrpcSessionOptions`]): Specifies @@ -23,56 +26,45 @@ def __init__(self, name, *, grpc_options=None): self._name = name self._interpreter = utils._select_interpreter(grpc_options) - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return self._name == other._name return False - def __hash__(self): + def __hash__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return hash(self._name) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __repr__(self): - return f'PersistedScale(name={self._name})' + def __repr__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + return f"PersistedScale(name={self._name})" @property def name(self): - """ - str: Indicates the name of the custom scale. - """ + """str: Indicates the name of the custom scale.""" return self._name @property def author(self): - """ - str: Indicates the author of the custom scale. - """ - val = self._interpreter.get_persisted_scale_attribute_string(self._name, 0x22d4) + """str: Indicates the author of the custom scale.""" + val = self._interpreter.get_persisted_scale_attribute_string(self._name, 0x22D4) return val @property def allow_interactive_editing(self): - """ - bool: Indicates whether the custom scale can be edited in the - DAQ Assistant. - """ - val = self._interpreter.get_persisted_scale_attribute_bool(self._name, 0x22d5) + """bool: Indicates whether the custom scale can be edited in the DAQ Assistant.""" + val = self._interpreter.get_persisted_scale_attribute_bool(self._name, 0x22D5) return val @property def allow_interactive_deletion(self): - """ - bool: Indicates whether the custom scale can be deleted through - MAX. - """ - val = self._interpreter.get_persisted_scale_attribute_bool(self._name, 0x22d6) + """bool: Indicates whether the custom scale can be deleted through MAX.""" + val = self._interpreter.get_persisted_scale_attribute_bool(self._name, 0x22D6) return val def delete(self): - """ - Deletes this custom scale from MAX. + """Deletes this custom scale from MAX. This function does not remove the custom scale from virtual channels that use it. @@ -80,8 +72,7 @@ def delete(self): self._interpreter.delete_saved_scale(self._name) def load(self): - """ - Loads this custom scale. + """Loads this custom scale. Returns: nidaqmx.scale.Scale: Indicates the loaded Scale object. @@ -90,16 +81,17 @@ def load(self): class _PersistedScaleAlternateConstructor(PersistedScale): - """ - Provide an alternate constructor for the PersistedScale object. + """Provide an alternate constructor for the PersistedScale object. This is a private API used to instantiate a PersistedScale with an existing interpreter. """ - # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. + + # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. # noqa: W505 - doc line too long (108 > 100 characters) (auto-generated noqa) __slots__ = () def __init__(self, name, interpreter): - """ + """Initialize a new PersistedScale with an existing interpreter. + Args: name: Specifies the name of the PersistedScale. interpreter: Specifies the interpreter instance. @@ -110,4 +102,4 @@ def __init__(self, name, interpreter): # Use meta-programming to change the type of this object to PersistedScale, # so the user isn't confused when doing introspection. - self.__class__ = PersistedScale # type: ignore[assignment] \ No newline at end of file + self.__class__ = PersistedScale # type: ignore[assignment] diff --git a/src/handwritten/system/storage/persisted_task.py b/src/handwritten/system/storage/persisted_task.py index cf49bbdad..49493666f 100644 --- a/src/handwritten/system/storage/persisted_task.py +++ b/src/handwritten/system/storage/persisted_task.py @@ -1,20 +1,22 @@ -from nidaqmx import task -from nidaqmx import utils +"""NI-DAQmx persisted task classes.""" -__all__ = ['PersistedTask'] +from nidaqmx import task, utils + +__all__ = ["PersistedTask"] class PersistedTask: - """ - Represents a saved DAQmx task. + """Represents a saved DAQmx task. Use the DAQmx Persisted Task properties to query information about programmatically saved tasks. """ - __slots__ = ['_name', '_interpreter', '__weakref__'] + + __slots__ = ["_name", "_interpreter", "__weakref__"] def __init__(self, name, *, grpc_options=None): - """ + """Initialize a new PersistedTask. + Args: name (str): Specifies the name of the saved task. grpc_options (Optional[:class:`~nidaqmx.GrpcSessionOptions`]): Specifies @@ -23,55 +25,45 @@ def __init__(self, name, *, grpc_options=None): self._name = name self._interpreter = utils._select_interpreter(grpc_options) - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return self._name == other._name return False - def __hash__(self): + def __hash__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return hash(self._name) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __repr__(self): - return f'PersistedTask(name={self._name})' + def __repr__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + return f"PersistedTask(name={self._name})" @property def name(self): - """ - str: Indicates the name of the task. - """ + """str: Indicates the name of the task.""" return self._name @property def author(self): - """ - str: Indicates the author of the task. - """ - val = self._interpreter.get_persisted_task_attribute_string(self._name, 0x22cc) + """str: Indicates the author of the task.""" + val = self._interpreter.get_persisted_task_attribute_string(self._name, 0x22CC) return val @property def allow_interactive_editing(self): - """ - bool: Indicates whether the task can be edited in the DAQ - Assistant. - """ - val = self._interpreter.get_persisted_task_attribute_bool(self._name, 0x22cd) + """bool: Indicates whether the task can be edited in the DAQ Assistant.""" + val = self._interpreter.get_persisted_task_attribute_bool(self._name, 0x22CD) return val @property def allow_interactive_deletion(self): - """ - bool: Indicates whether the task can be deleted through MAX. - """ - val = self._interpreter.get_persisted_task_attribute_bool(self._name, 0x22ce) + """bool: Indicates whether the task can be deleted through MAX.""" + val = self._interpreter.get_persisted_task_attribute_bool(self._name, 0x22CE) return val def delete(self): - """ - Deletes this task from MAX. + """Deletes this task from MAX. This function does not clear the copy of the task stored in memory. Use the DAQmx Clear Task function to clear that copy of the task. @@ -79,8 +71,7 @@ def delete(self): self._interpreter.delete_saved_task(self._name) def load(self): - """ - Loads this saved task. + """Loads this saved task. If you use this function to load a task, you must use DAQmx Clear Task to destroy it. @@ -94,16 +85,17 @@ def load(self): class _PersistedTaskAlternateConstructor(PersistedTask): - """ - Provide an alternate constructor for the PersistedTask object. + """Provide an alternate constructor for the PersistedTask object. This is a private API used to instantiate a PersistedTask with an existing interpreter. """ - # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. + + # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. # noqa: W505 - doc line too long (108 > 100 characters) (auto-generated noqa) __slots__ = () def __init__(self, name, interpreter): - """ + """Initialize a new PersistedTask with an existing interpreter. + Args: name: Specifies the name of the PersistedTask. interpreter: Specifies the interpreter instance. diff --git a/src/handwritten/task/__init__.py b/src/handwritten/task/__init__.py index a5a3eef9b..202448c6a 100644 --- a/src/handwritten/task/__init__.py +++ b/src/handwritten/task/__init__.py @@ -1,9 +1,15 @@ -from nidaqmx.task._task import ( - Task, _TaskEventType, _TaskAlternateConstructor -) -from nidaqmx.task._in_stream import InStream -from nidaqmx.task._out_stream import OutStream +"""NI-DAQmx task and related classes.""" + from nidaqmx.task._export_signals import ExportSignals +from nidaqmx.task._in_stream import InStream +from nidaqmx.task._out_stream import OutStream +from nidaqmx.task._task import Task, _TaskAlternateConstructor, _TaskEventType from nidaqmx.task._timing import Timing -__all__ = ['Task', 'InStream', 'OutStream', 'ExportSignals', 'Timing',] \ No newline at end of file +__all__ = [ + "Task", + "InStream", + "OutStream", + "ExportSignals", + "Timing", +] diff --git a/src/handwritten/task/_task.py b/src/handwritten/task/_task.py index 49d954118..4977d25f8 100644 --- a/src/handwritten/task/_task.py +++ b/src/handwritten/task/_task.py @@ -7,37 +7,42 @@ import numpy from nitypes.waveform import AnalogWaveform, DigitalWaveform + from nidaqmx import utils from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature -from nidaqmx.task.channels._channel import Channel +from nidaqmx.constants import ( + READ_ALL_AVAILABLE, + AcquisitionType, + ChannelType, + EveryNSamplesEventType, + FillMode, + ShuntCalSelect, + ShuntCalSource, + ShuntElementLocation, + UsageTypeAI, + UsageTypeCI, + UsageTypeCO, + _Save, +) +from nidaqmx.error_codes import DAQmxErrors +from nidaqmx.errors import DaqError, DaqResourceWarning +from nidaqmx.system.device import _DeviceAlternateConstructor from nidaqmx.task._export_signals import ExportSignals from nidaqmx.task._in_stream import InStream +from nidaqmx.task._out_stream import OutStream from nidaqmx.task._timing import Timing +from nidaqmx.task.channels._channel import Channel +from nidaqmx.task.collections._ai_channel_collection import AIChannelCollection +from nidaqmx.task.collections._ao_channel_collection import AOChannelCollection +from nidaqmx.task.collections._ci_channel_collection import CIChannelCollection +from nidaqmx.task.collections._co_channel_collection import COChannelCollection +from nidaqmx.task.collections._di_channel_collection import DIChannelCollection +from nidaqmx.task.collections._do_channel_collection import DOChannelCollection from nidaqmx.task.triggering._triggers import Triggers -from nidaqmx.task._out_stream import OutStream -from nidaqmx.task.collections._ai_channel_collection import ( - AIChannelCollection) -from nidaqmx.task.collections._ao_channel_collection import ( - AOChannelCollection) -from nidaqmx.task.collections._ci_channel_collection import ( - CIChannelCollection) -from nidaqmx.task.collections._co_channel_collection import ( - COChannelCollection) -from nidaqmx.task.collections._di_channel_collection import ( - DIChannelCollection) -from nidaqmx.task.collections._do_channel_collection import ( - DOChannelCollection) -from nidaqmx.constants import ( - AcquisitionType, ChannelType, FillMode, UsageTypeAI, UsageTypeCI, EveryNSamplesEventType, - READ_ALL_AVAILABLE, UsageTypeCO, _Save, ShuntCalSelect, ShuntCalSource, ShuntElementLocation) -from nidaqmx.error_codes import DAQmxErrors -from nidaqmx.errors import ( - DaqError, DaqResourceWarning) -from nidaqmx.system.device import _DeviceAlternateConstructor from nidaqmx.types import CtrFreq, CtrTick, CtrTime, PowerMeasurement -from nidaqmx.utils import unflatten_channel_string, flatten_channel_string +from nidaqmx.utils import flatten_channel_string, unflatten_channel_string -__all__ = ['Task'] +__all__ = ["Task"] class UnsetNumSamplesSentinel: @@ -56,17 +61,32 @@ class UnsetAutoStartSentinel: class Task: - """ - Represents a DAQmx Task. - """ - __slots__ = ('_handle', '_close_on_exit', '_saved_name', '_grpc_options', '_event_handlers', '_interpreter', - '_ai_channels', '_ao_channels', '_ci_channels', '_co_channels', '_di_channels', '_do_channels', - '_export_signals', '_in_stream', '_timing', '_triggers', '_out_stream', '_event_handler_lock', - '__weakref__') - - def __init__(self, new_task_name='', *, grpc_options=None): - """ - Creates a DAQmx task. + """Represents a DAQmx Task.""" + + __slots__ = ( + "_handle", + "_close_on_exit", + "_saved_name", + "_grpc_options", + "_event_handlers", + "_interpreter", + "_ai_channels", + "_ao_channels", + "_ci_channels", + "_co_channels", + "_di_channels", + "_do_channels", + "_export_signals", + "_in_stream", + "_timing", + "_triggers", + "_out_stream", + "_event_handler_lock", + "__weakref__", + ) + + def __init__(self, new_task_name="", *, grpc_options=None): + """Creates a DAQmx task. Args: new_task_name (Optional[str]): Specifies the name to assign to @@ -81,7 +101,7 @@ def __init__(self, new_task_name='', *, grpc_options=None): grpc_options (Optional[:class:`~nidaqmx.GrpcSessionOptions`]): Specifies the gRPC session options. """ - # Initialize the fields that __del__ accesses so it doesn't crash when __init__ raises an exception. + # Initialize the fields that __del__ accesses so it doesn't crash when __init__ raises an exception. # noqa: W505 - doc line too long (108 > 100 characters) (auto-generated noqa) self._handle = None self._close_on_exit = False self._saved_name = new_task_name # _initialize sets this to the name assigned by DAQmx. @@ -94,188 +114,152 @@ def __init__(self, new_task_name='', *, grpc_options=None): raise DaqError( f'Unsupported session name: "{grpc_options.session_name}". If a session name is specified, it must match the task name.', DAQmxErrors.UNKNOWN, - task_name=new_task_name) + task_name=new_task_name, + ) self._interpreter = utils._select_interpreter(grpc_options) self._handle, self._close_on_exit = self._interpreter.create_task(new_task_name) self._initialize(self._handle, self._interpreter) - def __del__(self): + def __del__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if self._handle is not None and self._close_on_exit and self._grpc_options is None: warnings.warn( 'Task of name "{}" was not explicitly closed before it was ' - 'destructed. Resources on the task device may still be ' - 'reserved.'.format(self._saved_name), - DaqResourceWarning + "destructed. Resources on the task device may still be " + "reserved.".format(self._saved_name), + DaqResourceWarning, ) - elif ( - self._grpc_options is not None - and self._event_handlers - ): + elif self._grpc_options is not None and self._event_handlers: warnings.warn( 'Task of name "{}" was not explicitly closed before it was ' - 'destructed. Event handlers may still be active.'.format(self._saved_name), - DaqResourceWarning + "destructed. Event handlers may still be active.".format(self._saved_name), + DaqResourceWarning, ) - def __enter__(self): + def __enter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return self - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return self._handle == other._handle return False - def __exit__(self, type, value, traceback): + def __exit__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, type, value, traceback + ): if self._close_on_exit: self.close() - def __hash__(self): + def __hash__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return self._interpreter.hash_task_handle(self._handle) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __repr__(self): - return f'Task(name={self._saved_name})' + def __repr__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + return f"Task(name={self._saved_name})" @property def name(self): - """ - str: Indicates the name of the task. - """ + """str: Indicates the name of the task.""" val = self._interpreter.get_task_attribute_string(self._handle, 0x1276) return val @property def channels(self): - """ - :class:`nidaqmx.task.channels.Channel`: Specifies - a channel object that represents the entire list of virtual - channels in this task. - """ + """:class:`nidaqmx.task.channels.Channel`: Specifies a channel object that represents the entire list of virtual channels in this task.""" # noqa: W505 - doc line too long (146 > 100 characters) (auto-generated noqa) return Channel._factory( - self._handle, flatten_channel_string(self.channel_names), self._interpreter) + self._handle, flatten_channel_string(self.channel_names), self._interpreter + ) @property def channel_names(self): - """ - List[str]: Indicates the names of all virtual channels in the task. - """ + """List[str]: Indicates the names of all virtual channels in the task.""" val = self._interpreter.get_task_attribute_string(self._handle, 0x1273) return unflatten_channel_string(val) @property def number_of_channels(self): - """ - int: Indicates the number of virtual channels in the task. - """ + """int: Indicates the number of virtual channels in the task.""" val = self._interpreter.get_task_attribute_uint32(self._handle, 0x2181) return val @property def devices(self): - """ - List[:class:`nidaqmx.system.device.Device`]: Indicates a list - of Device objects representing all the devices in the task. - """ - val = self._interpreter.get_task_attribute_string(self._handle, 0x230e) - return [_DeviceAlternateConstructor(v, self._interpreter) for v in - unflatten_channel_string(val)] + """List[:class:`nidaqmx.system.device.Device`]: Indicates a list of Device objects representing all the devices in the task.""" # noqa: W505 - doc line too long (135 > 100 characters) (auto-generated noqa) + val = self._interpreter.get_task_attribute_string(self._handle, 0x230E) + return [ + _DeviceAlternateConstructor(v, self._interpreter) for v in unflatten_channel_string(val) + ] @property def number_of_devices(self): - """ - int: Indicates the number of devices in the task. - """ - val = self._interpreter.get_task_attribute_uint32(self._handle, 0x29ba) + """int: Indicates the number of devices in the task.""" + val = self._interpreter.get_task_attribute_uint32(self._handle, 0x29BA) return val @property def ai_channels(self) -> AIChannelCollection: - """ - Gets the collection of analog input channels for this task. - """ + """Gets the collection of analog input channels for this task.""" return self._ai_channels @property def ao_channels(self) -> AOChannelCollection: - """ - Gets the collection of analog output channels for this task. - """ + """Gets the collection of analog output channels for this task.""" return self._ao_channels @property def ci_channels(self) -> CIChannelCollection: - """ - Gets the collection of counter input channels for this task. - """ + """Gets the collection of counter input channels for this task.""" return self._ci_channels @property def co_channels(self) -> COChannelCollection: - """ - Gets the collection of counter output channels for this task. - """ + """Gets the collection of counter output channels for this task.""" return self._co_channels @property def di_channels(self) -> DIChannelCollection: - """ - Gets the collection of digital input channels for this task. - """ + """Gets the collection of digital input channels for this task.""" return self._di_channels @property def do_channels(self) -> DOChannelCollection: - """ - Gets the collection of digital output channels for this task. - """ + """Gets the collection of digital output channels for this task.""" return self._do_channels @property def export_signals(self) -> ExportSignals: - """ - Gets the exported signal configurations for the task. - """ + """Gets the exported signal configurations for the task.""" return self._export_signals @property def in_stream(self) -> InStream: - """ - Gets the read configurations for the task. - """ + """Gets the read configurations for the task.""" return self._in_stream @property def out_stream(self) -> OutStream: - """ - Gets the write configurations for the task. - """ + """Gets the write configurations for the task.""" return self._out_stream @property def timing(self) -> Timing: - """ - Gets the timing configurations for the task. - """ + """Gets the timing configurations for the task.""" return self._timing @property def triggers(self) -> Triggers: - """ - Gets the trigger configurations for the task. - """ + """Gets the trigger configurations for the task.""" return self._triggers def _initialize(self, task_handle, interpreter): - """ - Instantiates and populates various attributes used by this task. + """Instantiates and populates various attributes used by this task. Args: task_handle (TaskHandle): Specifies the handle for this task. - """ + """ # noqa: D417 - Missing argument descriptions in the docstring (auto-generated noqa) # Saved name is used in self.close() to throw graceful error on # double closes. self._saved_name = self.name @@ -295,8 +279,7 @@ def _initialize(self, task_handle, interpreter): self._event_handler_lock = threading.Lock() def _calculate_num_samps_per_chan(self, num_samps_per_chan): - """ - Calculates the actual number of samples per channel to read. + """Calculates the actual number of samples per channel to read. This method is necessary because the number of samples per channel can be set to NUM_SAMPLES_UNSET or -1, where each value entails a @@ -312,8 +295,7 @@ def _calculate_num_samps_per_chan(self, num_samps_per_chan): elif num_samps_per_chan == READ_ALL_AVAILABLE: acq_type = self.timing.samp_quant_samp_mode - if (acq_type == AcquisitionType.FINITE and - not self.in_stream.read_all_avail_samp): + if acq_type == AcquisitionType.FINITE and not self.in_stream.read_all_avail_samp: return self.timing.samp_quant_samp_per_chan else: return self.in_stream.avail_samp_per_chan @@ -321,8 +303,7 @@ def _calculate_num_samps_per_chan(self, num_samps_per_chan): return num_samps_per_chan def add_global_channels(self, global_channels): - """ - Adds global virtual channels from MAX to the given task. + """Adds global virtual channels from MAX to the given task. Args: global_channels (List[nidaqmx.system.storage.persisted_channel.PersistedChannel]): @@ -337,8 +318,7 @@ def add_global_channels(self, global_channels): self._interpreter.add_global_chans_to_task(self._handle, channels) def close(self): - """ - Clears the task. + """Clears the task. Before clearing, this method aborts the task, if necessary, and releases any resources the task reserved. You cannot use a task @@ -351,7 +331,9 @@ def close(self): if self._handle is None: warnings.warn( 'Attempted to close NI-DAQmx task of name "{}" but task was ' - 'already closed.'.format(self._saved_name), DaqResourceWarning) + "already closed.".format(self._saved_name), + DaqResourceWarning, + ) return first_exception = None @@ -375,8 +357,7 @@ def close(self): raise first_exception def control(self, action): - """ - Alters the state of a task according to the action you specify. + """Alters the state of a task according to the action you specify. Args: action (nidaqmx.constants.TaskMode): Specifies how to alter @@ -385,9 +366,9 @@ def control(self, action): self._interpreter.task_control(self._handle, action.value) def is_task_done(self): - """ - Queries the status of the task and indicates if it completed - execution. Use this function to ensure that the specified + """Queries the status of the task and indicates if it completed execution. + + Use this function to ensure that the specified operation is complete before you stop the task. Returns: @@ -400,8 +381,7 @@ def is_task_done(self): return is_task_done def perform_bridge_offset_nulling_cal(self, channel="", skip_unsupported_channels=False): - """ - Perform a bridge offset nulling calibration on the channels in the task. + """Perform a bridge offset nulling calibration on the channels in the task. If the task measures both bridge-based sensors and non-bridge-based sensors, use the channels input to specify the names of the channels that measure @@ -417,18 +397,22 @@ def perform_bridge_offset_nulling_cal(self, channel="", skip_unsupported_channel support calibration. If skip unsupported channels is TRUE, this VI calibrates only supported channels. If FALSE, this VI calibrates the channels specified by channels. The default is FALSE. - """ + """ # noqa: D202, W505 - No blank lines allowed after function docstring (auto-generated noqa), doc line too long (102 > 100 characters) (auto-generated noqa) self._interpreter.perform_bridge_offset_nulling_cal_ex( - self._handle, channel, skip_unsupported_channels) + self._handle, channel, skip_unsupported_channels + ) def perform_strain_shunt_cal( - self, channel="", shunt_resistor_value=100000, - shunt_resistor_location=ShuntElementLocation.R3, shunt_resistor_select=ShuntCalSelect.A, - shunt_resistor_source=ShuntCalSource.DEFAULT, skip_unsupported_channels=False): - """ - Perform shunt calibration for the specified channels using a strain - gage sensor. + self, + channel="", + shunt_resistor_value=100000, + shunt_resistor_location=ShuntElementLocation.R3, + shunt_resistor_select=ShuntCalSelect.A, + shunt_resistor_source=ShuntCalSource.DEFAULT, + skip_unsupported_channels=False, + ): + """Perform shunt calibration for the specified channels using a strain gage sensor. Refer to the calibration procedure for your module for detailed calibration instructions. @@ -449,17 +433,26 @@ def perform_strain_shunt_cal( the channels specified by channels. The default is False. """ self._interpreter.perform_strain_shunt_cal_ex( - self._handle, channel, shunt_resistor_value, - shunt_resistor_location.value, shunt_resistor_select.value, - shunt_resistor_source.value, skip_unsupported_channels) + self._handle, + channel, + shunt_resistor_value, + shunt_resistor_location.value, + shunt_resistor_select.value, + shunt_resistor_source.value, + skip_unsupported_channels, + ) def perform_bridge_shunt_cal( - self, channel="", shunt_resistor_value=100000, - shunt_resistor_location=ShuntElementLocation.R3, shunt_resistor_select=ShuntCalSelect.A, - shunt_resistor_source=ShuntCalSource.DEFAULT, bridge_resistance=120, - skip_unsupported_channels=False): - """ - Perform shunt calibration for the specified channels using a bridge sensor. + self, + channel="", + shunt_resistor_value=100000, + shunt_resistor_location=ShuntElementLocation.R3, + shunt_resistor_select=ShuntCalSelect.A, + shunt_resistor_source=ShuntCalSource.DEFAULT, + bridge_resistance=120, + skip_unsupported_channels=False, + ): + """Perform shunt calibration for the specified channels using a bridge sensor. Refer to the calibration procedure for your module for detailed calibration instructions. @@ -483,14 +476,18 @@ def perform_bridge_shunt_cal( the channels specified by channels. The default is False. """ self._interpreter.perform_bridge_shunt_cal_ex( - self._handle, channel, shunt_resistor_value, - shunt_resistor_location.value, shunt_resistor_select.value, - shunt_resistor_source.value, bridge_resistance, - skip_unsupported_channels) + self._handle, + channel, + shunt_resistor_value, + shunt_resistor_location.value, + shunt_resistor_select.value, + shunt_resistor_source.value, + bridge_resistance, + skip_unsupported_channels, + ) def perform_thrmcpl_lead_offset_nulling_cal(self, channel="", skip_unsupported_channels=False): - """ - Perform thermocouple lead offset nulling calibration on the channels in the task. + """Perform thermocouple lead offset nulling calibration on the channels in the task. This is to compensate for offsets introduced by open thermocouple detection. Keep the measured temperature as constant as possible while performing this @@ -506,15 +503,14 @@ def perform_thrmcpl_lead_offset_nulling_cal(self, channel="", skip_unsupported_c support calibration. If skip unsupported channels is TRUE, this VI calibrates only supported channels. If FALSE, this VI calibrates the channels specified by channels. The default is FALSE. - """ + """ # noqa: D202, W505 - No blank lines allowed after function docstring (auto-generated noqa), doc line too long (102 > 100 characters) (auto-generated noqa) self._interpreter.perform_thrmcpl_lead_offset_nulling_cal( - self._handle, channel, skip_unsupported_channels) + self._handle, channel, skip_unsupported_channels + ) - def read(self, number_of_samples_per_channel=NUM_SAMPLES_UNSET, - timeout=10.0): - """ - Reads samples from the task or virtual channels you specify. + def read(self, number_of_samples_per_channel=NUM_SAMPLES_UNSET, timeout=10.0): + """Reads samples from the task or virtual channels you specify. This read method is dynamic, and is capable of inferring an appropriate return type based on these factors: @@ -574,6 +570,7 @@ def read(self, number_of_samples_per_channel=NUM_SAMPLES_UNSET, indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: dynamic: @@ -597,18 +594,16 @@ def read(self, number_of_samples_per_channel=NUM_SAMPLES_UNSET, number_of_channels = len(channels_to_read.channel_names) read_chan_type = channels_to_read.chan_type - num_samples_not_set = (number_of_samples_per_channel is - NUM_SAMPLES_UNSET) + num_samples_not_set = number_of_samples_per_channel is NUM_SAMPLES_UNSET number_of_samples_per_channel = self._calculate_num_samps_per_chan( - number_of_samples_per_channel) + number_of_samples_per_channel + ) # Determine the array shape and size to create if number_of_channels > 1: if not num_samples_not_set: - array_shape: tuple[int, ...] = ( - number_of_channels, number_of_samples_per_channel - ) + array_shape: tuple[int, ...] = (number_of_channels, number_of_samples_per_channel) else: array_shape = (number_of_channels,) else: @@ -622,54 +617,77 @@ def read(self, number_of_samples_per_channel=NUM_SAMPLES_UNSET, else: data: numpy.typing.NDArray = numpy.zeros(array_shape, dtype=numpy.float64) _, samples_read = self._interpreter.read_analog_f64( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) - elif (read_chan_type == ChannelType.DIGITAL_INPUT or - read_chan_type == ChannelType.DIGITAL_OUTPUT): + elif ( + read_chan_type == ChannelType.DIGITAL_INPUT + or read_chan_type == ChannelType.DIGITAL_OUTPUT + ): if self.in_stream.di_num_booleans_per_chan == 1: data = numpy.zeros(array_shape, dtype=bool) _, samples_read, _ = self._interpreter.read_digital_lines( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) else: data = numpy.zeros(array_shape, dtype=numpy.uint32) _, samples_read = self._interpreter.read_digital_u32( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) elif read_chan_type == ChannelType.COUNTER_INPUT: meas_type = channels_to_read.ci_meas_type - if meas_type in [UsageTypeCI.PULSE_FREQ, UsageTypeCI.PULSE_TIME, UsageTypeCI.PULSE_TICKS]: + if meas_type in [ + UsageTypeCI.PULSE_FREQ, + UsageTypeCI.PULSE_TIME, + UsageTypeCI.PULSE_TICKS, + ]: return self._read_ctr_pulse( array_shape, meas_type, number_of_channels, number_of_samples_per_channel, num_samples_not_set, - timeout + timeout, ) else: data = numpy.zeros(array_shape, dtype=numpy.float64) _, samples_read = self._interpreter.read_counter_f64_ex( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) else: raise DaqError( - 'Read failed, because there are no channels in this task from ' - 'which data can be read.', + "Read failed, because there are no channels in this task from " + "which data can be read.", DAQmxErrors.READ_NO_INPUT_CHANS_IN_TASK, - task_name=self.name) + task_name=self.name, + ) if num_samples_not_set and array_shape == (1,): return data.tolist()[0] if samples_read != number_of_samples_per_channel: if number_of_channels > 1: - return data[:,:samples_read].tolist() + return data[:, :samples_read].tolist() else: return data[:samples_read].tolist() @@ -689,8 +707,13 @@ def _read_ctr_pulse( duty_cycles = numpy.zeros(array_shape, dtype=numpy.float64) _, _, samples_read = self._interpreter.read_ctr_freq( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, frequencies, duty_cycles) + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + frequencies, + duty_cycles, + ) data: list[CtrFreq] | list[CtrTick] | list[CtrTime] = [ CtrFreq(freq=f, duty_cycle=d) for f, d in zip(frequencies, duty_cycles) @@ -701,17 +724,27 @@ def _read_ctr_pulse( low_times = numpy.zeros(array_shape, dtype=numpy.float64) _, _, samples_read = self._interpreter.read_ctr_time( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_times, low_times) + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_times, + low_times, + ) data = [CtrTime(high_time=h, low_time=l) for h, l in zip(high_times, low_times)] elif meas_type == UsageTypeCI.PULSE_TICKS: high_ticks = numpy.zeros(array_shape, dtype=numpy.uint32) low_ticks = numpy.zeros(array_shape, dtype=numpy.uint32) - _, _ , samples_read = self._interpreter.read_ctr_ticks( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_ticks, low_ticks) + _, _, samples_read = self._interpreter.read_ctr_ticks( + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_ticks, + low_ticks, + ) data = [CtrTick(high_tick=h, low_tick=l) for h, l in zip(high_ticks, low_ticks)] else: @@ -741,16 +774,18 @@ def _read_power( currents = numpy.zeros(array_shape, dtype=numpy.float64) _, _, samples_read = self._interpreter.read_power_f64( - self._handle, number_of_samples_per_channel, timeout, - FillMode.GROUP_BY_CHANNEL.value, voltages, currents) + self._handle, + number_of_samples_per_channel, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + voltages, + currents, + ) if number_of_channels > 1: if number_of_samples_per_channel == 1: # n channel, 1 sample - return [ - PowerMeasurement(voltage=v, current=i) - for v, i in zip(voltages, currents) - ] + return [PowerMeasurement(voltage=v, current=i) for v, i in zip(voltages, currents)] else: # n channel, n samples return [ @@ -766,16 +801,13 @@ def _read_power( return PowerMeasurement(voltage=voltages[0], current=currents[0]) else: # 1 channel, n samples - return [ - PowerMeasurement(voltage=v, current=i) - for v, i in zip(voltages, currents) - ][:samples_read] + return [PowerMeasurement(voltage=v, current=i) for v, i in zip(voltages, currents)][ + :samples_read + ] @requires_feature(WAVEFORM_SUPPORT) - def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, - timeout=10.0): - """ - Reads samples from the task or virtual channels you specify, and returns them as waveforms. + def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, timeout=10.0): + """Reads samples from the task or virtual channels you specify, and returns them as waveforms. This read method is dynamic, and is capable of inferring an appropriate return type based on these factors: @@ -795,7 +827,7 @@ def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, number of samples to read. If this input is not set, it defaults to nidaqmx.constants.READ_ALL_AVAILABLE. - If this input is nidaqmx.constants.READ_ALL_AVAILABLE, + If this input is nidaqmx.constants.READ_ALL_AVAILABLE, NI-DAQmx determines how many samples to read based on if the task acquires samples continuously or acquires a finite number of samples. @@ -821,6 +853,7 @@ def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, indefinitely. If you set timeout to 0, the method tries once to read the requested samples and returns an error if it is unable to. + Returns: dynamic: @@ -838,13 +871,14 @@ def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, >>> data = task.read_waveform() >>> type(data) - """ + """ # noqa: W505 - doc line too long (102 > 100 characters) (auto-generated noqa) channels_to_read = self.in_stream.channels_to_read number_of_channels = len(channels_to_read.channel_names) read_chan_type = channels_to_read.chan_type number_of_samples_per_channel = self._calculate_num_samps_per_chan( - number_of_samples_per_channel) + number_of_samples_per_channel + ) if read_chan_type == ChannelType.ANALOG_INPUT: if number_of_channels == 1: @@ -859,8 +893,7 @@ def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, return analog_waveform else: analog_waveforms = [ - AnalogWaveform(number_of_samples_per_channel) - for _ in range(number_of_channels) + AnalogWaveform(number_of_samples_per_channel) for _ in range(number_of_channels) ] self._interpreter.read_analog_waveforms( self._handle, @@ -871,12 +904,14 @@ def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, ) return analog_waveforms - elif (read_chan_type == ChannelType.DIGITAL_INPUT or - read_chan_type == ChannelType.DIGITAL_OUTPUT): + elif ( + read_chan_type == ChannelType.DIGITAL_INPUT + or read_chan_type == ChannelType.DIGITAL_OUTPUT + ): if number_of_channels == 1: digital_waveform = DigitalWaveform( - number_of_samples_per_channel, - self.in_stream.di_num_booleans_per_chan) + number_of_samples_per_channel, self.in_stream.di_num_booleans_per_chan + ) self._interpreter.read_digital_waveform( self._handle, number_of_samples_per_channel, @@ -897,17 +932,16 @@ def read_waveform(self, number_of_samples_per_channel=READ_ALL_AVAILABLE, else: raise DaqError( - 'Read failed, because there are no channels in this task from ' - 'which data can be read.', + "Read failed, because there are no channels in this task from " + "which data can be read.", DAQmxErrors.READ_NO_INPUT_CHANS_IN_TASK, - task_name=self.name) + task_name=self.name, + ) def register_done_event(self, callback_method): - """ - Registers a callback function to receive an event when a task stops due - to an error or when a finite acquisition task or finite generation task - completes execution. A Done event does not occur when a task is stopped - explicitly, such as by calling DAQmx Stop Task. + """Registers a callback function to receive an event when a task stops due to an error or when a finite acquisition task or finite generation task completes execution. + + A Done event does not occur when a task is stopped explicitly, such as by calling DAQmx Stop Task. Args: callback_method (function): Specifies the function that you want @@ -928,11 +962,13 @@ def register_done_event(self, callback_method): Passing None for this parameter unregisters the event callback function. - """ + """ # noqa: W505 - doc line too long (175 > 100 characters) (auto-generated noqa) if callback_method is not None: # If the event is already registered, the interpreter should raise DaqError with code # DAQmxErrors.DONE_EVENT_ALREADY_REGISTERED. - event_handler = self._interpreter.register_done_event(self._handle, 0, callback_method, None) + event_handler = self._interpreter.register_done_event( + self._handle, 0, callback_method, None + ) with self._event_handler_lock: assert _TaskEventType.DONE not in self._event_handlers, "Event already registered." self._event_handlers[_TaskEventType.DONE] = event_handler @@ -943,12 +979,10 @@ def register_done_event(self, callback_method): if event_handler is not None: event_handler.close() # may raise an exception - def register_every_n_samples_acquired_into_buffer_event( - self, sample_interval, callback_method): - """ - Registers a callback function to receive an event when the specified - number of samples is written from the device to the buffer. This - function only works with devices that support buffered tasks. + def register_every_n_samples_acquired_into_buffer_event(self, sample_interval, callback_method): + """Registers a callback function to receive an event when the specified number of samples is written from the device to the buffer. + + This function only works with devices that support buffered tasks. When you stop a task explicitly any pending events are discarded. For example, if you call DAQmx Stop Task then you do not receive any @@ -976,30 +1010,42 @@ def register_every_n_samples_acquired_into_buffer_event( Passing None for this parameter unregisters the event callback function. - """ + """ # noqa: W505 - doc line too long (139 > 100 characters) (auto-generated noqa) if callback_method is not None: # If the event is already registered, the interpreter should raise DaqError with code # DAQmxErrors.EVERY_N_SAMPS_ACQ_INTO_BUFFER_EVENT_ALREADY_REGISTERED. event_handler = self._interpreter.register_every_n_samples_event( - self._handle, EveryNSamplesEventType.ACQUIRED_INTO_BUFFER.value, - sample_interval, 0, callback_method, None) + self._handle, + EveryNSamplesEventType.ACQUIRED_INTO_BUFFER.value, + sample_interval, + 0, + callback_method, + None, + ) with self._event_handler_lock: - assert _TaskEventType.EVERY_N_SAMPLES_ACQUIRED_INTO_BUFFER not in self._event_handlers, "Event already registered." - self._event_handlers[_TaskEventType.EVERY_N_SAMPLES_ACQUIRED_INTO_BUFFER] = event_handler + assert ( + _TaskEventType.EVERY_N_SAMPLES_ACQUIRED_INTO_BUFFER not in self._event_handlers + ), "Event already registered." + self._event_handlers[_TaskEventType.EVERY_N_SAMPLES_ACQUIRED_INTO_BUFFER] = ( + event_handler + ) else: self._interpreter.unregister_every_n_samples_event( - self._handle, EveryNSamplesEventType.ACQUIRED_INTO_BUFFER.value) + self._handle, EveryNSamplesEventType.ACQUIRED_INTO_BUFFER.value + ) with self._event_handler_lock: - event_handler = self._event_handlers.pop(_TaskEventType.EVERY_N_SAMPLES_ACQUIRED_INTO_BUFFER, None) + event_handler = self._event_handlers.pop( + _TaskEventType.EVERY_N_SAMPLES_ACQUIRED_INTO_BUFFER, None + ) if event_handler is not None: event_handler.close() # may raise an exception def register_every_n_samples_transferred_from_buffer_event( - self, sample_interval, callback_method): - """ - Registers a callback function to receive an event when the specified - number of samples is written from the buffer to the device. This - function only works with devices that support buffered tasks. + self, sample_interval, callback_method + ): + """Registers a callback function to receive an event when the specified number of samples is written from the buffer to the device. + + This function only works with devices that support buffered tasks. When you stop a task explicitly any pending events are discarded. For example, if you call DAQmx Stop Task then you do not receive any @@ -1027,28 +1073,39 @@ def register_every_n_samples_transferred_from_buffer_event( Passing None for this parameter unregisters the event callback function. - """ + """ # noqa: W505 - doc line too long (139 > 100 characters) (auto-generated noqa) if callback_method is not None: # If the event is already registered, the interpreter should raise DaqError with code # DAQmxErrors.EVERY_N_SAMPS_TRANSFERRED_FROM_BUFFER_EVENT_ALREADY_REGISTERED. event_handler = self._interpreter.register_every_n_samples_event( - self._handle, EveryNSamplesEventType.TRANSFERRED_FROM_BUFFER.value, - sample_interval, 0, callback_method, None) + self._handle, + EveryNSamplesEventType.TRANSFERRED_FROM_BUFFER.value, + sample_interval, + 0, + callback_method, + None, + ) with self._event_handler_lock: - assert _TaskEventType.EVERY_N_SAMPLES_TRANSFERRED_FROM_BUFFER not in self._event_handlers, "Event already registered." - self._event_handlers[_TaskEventType.EVERY_N_SAMPLES_TRANSFERRED_FROM_BUFFER] = event_handler + assert ( + _TaskEventType.EVERY_N_SAMPLES_TRANSFERRED_FROM_BUFFER + not in self._event_handlers + ), "Event already registered." + self._event_handlers[_TaskEventType.EVERY_N_SAMPLES_TRANSFERRED_FROM_BUFFER] = ( + event_handler + ) else: self._interpreter.unregister_every_n_samples_event( - self._handle, EveryNSamplesEventType.TRANSFERRED_FROM_BUFFER.value) + self._handle, EveryNSamplesEventType.TRANSFERRED_FROM_BUFFER.value + ) with self._event_handler_lock: - event_handler = self._event_handlers.pop(_TaskEventType.EVERY_N_SAMPLES_TRANSFERRED_FROM_BUFFER, None) + event_handler = self._event_handlers.pop( + _TaskEventType.EVERY_N_SAMPLES_TRANSFERRED_FROM_BUFFER, None + ) if event_handler is not None: event_handler.close() # may raise an exception def register_signal_event(self, signal_type, callback_method): - """ - Registers a callback function to receive an event when the specified - hardware event occurs. + """Registers a callback function to receive an event when the specified hardware event occurs. When you stop a task explicitly any pending events are discarded. For example, if you call DAQmx Stop Task then you do not receive any @@ -1073,14 +1130,17 @@ def register_signal_event(self, signal_type, callback_method): Passing None for this parameter unregisters the event callback function. - """ + """ # noqa: W505 - doc line too long (102 > 100 characters) (auto-generated noqa) if callback_method is not None: # If the event is already registered, the interpreter should raise DaqError with code # DAQmxErrors.SIGNAL_EVENT_ALREADY_REGISTERED. event_handler = self._interpreter.register_signal_event( - self._handle, signal_type.value, 0, callback_method, None) + self._handle, signal_type.value, 0, callback_method, None + ) with self._event_handler_lock: - assert _TaskEventType.SIGNAL not in self._event_handlers, "Event already registered." + assert ( + _TaskEventType.SIGNAL not in self._event_handlers + ), "Event already registered." self._event_handlers[_TaskEventType.SIGNAL] = event_handler else: self._interpreter.unregister_signal_event(self._handle, signal_type.value) @@ -1089,10 +1149,15 @@ def register_signal_event(self, signal_type, callback_method): if event_handler is not None: event_handler.close() # may raise an exception - def save(self, save_as="", author="", overwrite_existing_task=False, - allow_interactive_editing=True, allow_interactive_deletion=True): - """ - Saves this task and any local channels it contains to MAX. + def save( + self, + save_as="", + author="", + overwrite_existing_task=False, + allow_interactive_editing=True, + allow_interactive_deletion=True, + ): + """Saves this task and any local channels it contains to MAX. This function does not save global channels. Use the DAQmx Save Global Channel function to save global channels. @@ -1129,9 +1194,10 @@ def save(self, save_as="", author="", overwrite_existing_task=False, self._interpreter.save_task(self._handle, save_as, author, options) def start(self): - """ - Transitions the task to the running state to begin the measurement - or generation. Using this method is required for some applications and + """Start the task. + + This method transitions the task to the running state to begin the measurement or + generation. Using this method is required for some applications and is optional for others. If you do not use this method, a measurement task starts automatically @@ -1148,8 +1214,9 @@ def start(self): self._interpreter.start_task(self._handle) def stop(self): - """ - Stops the task and returns it to the state the task was in before the + """Stop the task. + + This method stops the task and returns it to the state the task was in before the DAQmx Start Task method ran or the DAQmx Write method ran with the autostart input set to TRUE. @@ -1162,8 +1229,7 @@ def stop(self): self._interpreter.stop_task(self._handle) def wait_for_valid_timestamp(self, timestamp_event, timeout=10.0): - """ - Wait until the specified timestamp has a value. + """Wait until the specified timestamp has a value. Use this method to ensure the timestamp has a valid value to prevent an error when querying a timestamp value. @@ -1179,12 +1245,13 @@ def wait_for_valid_timestamp(self, timestamp_event, timeout=10.0): datetime: The timestamp value of timestamp_event. - """ - return self._interpreter.wait_for_valid_timestamp(self._handle, timestamp_event.value, timeout) + """ # noqa: W505 - doc line too long (118 > 100 characters) (auto-generated noqa) + return self._interpreter.wait_for_valid_timestamp( + self._handle, timestamp_event.value, timeout + ) def wait_until_done(self, timeout=10.0): - """ - Waits for the measurement or generation to complete. + """Waits for the measurement or generation to complete. Use this method to ensure that the specified operation is complete before you stop the task. @@ -1200,38 +1267,36 @@ def wait_until_done(self, timeout=10.0): """ self._interpreter.wait_until_task_done(self._handle, timeout) - def _raise_invalid_num_lines_error( - self, num_lines_expected, num_lines_in_data): + def _raise_invalid_num_lines_error(self, num_lines_expected, num_lines_in_data): raise DaqError( - 'Specified read or write operation failed, because the number ' - 'of lines in the data for a channel does not match the number ' - 'of lines in the channel.\n\n' - 'If you are using boolean data, make sure the array dimension ' - 'for lines in the data matches the number of lines in the ' - 'channel.\n\n' - 'Number of Lines Per Channel in Task: {}\n' - 'Number of Lines Per Channel in Data: {}' - .format(num_lines_expected, num_lines_in_data), + "Specified read or write operation failed, because the number " + "of lines in the data for a channel does not match the number " + "of lines in the channel.\n\n" + "If you are using boolean data, make sure the array dimension " + "for lines in the data matches the number of lines in the " + "channel.\n\n" + "Number of Lines Per Channel in Task: {}\n" + "Number of Lines Per Channel in Data: {}".format(num_lines_expected, num_lines_in_data), DAQmxErrors.NUM_LINES_MISMATCH_IN_READ_OR_WRITE, - task_name=self.name) + task_name=self.name, + ) - def _raise_invalid_write_num_chans_error( - self, number_of_channels, number_of_channels_in_data): + def _raise_invalid_write_num_chans_error(self, number_of_channels, number_of_channels_in_data): raise DaqError( - 'Write cannot be performed, because the number of channels in the ' - 'data does not match the number of channels in the task.\n\n' - 'When writing, supply data for all channels in the task. ' - 'Alternatively, modify the task to contain the same number of ' - 'channels as the data written.\n\n' - 'Number of Channels in Task: {}\n' - 'Number of Channels in Data: {}' - .format(number_of_channels, number_of_channels_in_data), - DAQmxErrors.WRITE_NUM_CHANS_MISMATCH, task_name=self.name) + "Write cannot be performed, because the number of channels in the " + "data does not match the number of channels in the task.\n\n" + "When writing, supply data for all channels in the task. " + "Alternatively, modify the task to contain the same number of " + "channels as the data written.\n\n" + "Number of Channels in Task: {}\n" + "Number of Channels in Data: {}".format(number_of_channels, number_of_channels_in_data), + DAQmxErrors.WRITE_NUM_CHANS_MISMATCH, + task_name=self.name, + ) def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): - """ - Writes samples to the task or virtual channels you specify. + """Writes samples to the task or virtual channels you specify. This write method is dynamic, and is capable of accepting the samples to write in the various forms for most operations: @@ -1290,6 +1355,7 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): once to write the submitted samples. If the method could not write all the submitted samples, it returns an error and the number of samples successfully written. + Returns: int: @@ -1304,16 +1370,14 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): if number_of_channels == 1: if isinstance(data, list): if isinstance(data[0], list): - self._raise_invalid_write_num_chans_error( - number_of_channels, len(data)) + self._raise_invalid_write_num_chans_error(number_of_channels, len(data)) number_of_samples_per_channel = len(data) element = data[0] elif isinstance(data, numpy.ndarray): if len(data.shape) == 2: - self._raise_invalid_write_num_chans_error( - number_of_channels, data.shape[0]) + self._raise_invalid_write_num_chans_error(number_of_channels, data.shape[0]) number_of_samples_per_channel = len(data) element = data[0] @@ -1321,8 +1385,7 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): elif isinstance(data, AnalogWaveform): WAVEFORM_SUPPORT.raise_if_disabled() if number_of_channels != 1: - self._raise_invalid_write_num_chans_error( - number_of_channels, 1) + self._raise_invalid_write_num_chans_error(number_of_channels, 1) number_of_samples_per_channel = data.sample_count element = data.raw_data[0] @@ -1333,8 +1396,7 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): else: if isinstance(data, list): if len(data) != number_of_channels: - self._raise_invalid_write_num_chans_error( - number_of_channels, len(data)) + self._raise_invalid_write_num_chans_error(number_of_channels, len(data)) if isinstance(data[0], list): number_of_samples_per_channel = len(data[0]) @@ -1345,8 +1407,7 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): elif isinstance(data, numpy.ndarray): if data.shape[0] != number_of_channels: - self._raise_invalid_write_num_chans_error( - number_of_channels, data.shape[0]) + self._raise_invalid_write_num_chans_error(number_of_channels, data.shape[0]) if len(data.shape) == 2: number_of_samples_per_channel = data.shape[1] @@ -1356,8 +1417,7 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): element = data[0] else: - self._raise_invalid_write_num_chans_error( - number_of_channels, 1) + self._raise_invalid_write_num_chans_error(number_of_channels, 1) if auto_start is AUTO_START_UNSET: if number_of_samples_per_channel > 1: @@ -1368,42 +1428,60 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): if write_chan_type == ChannelType.ANALOG_OUTPUT: if isinstance(data, AnalogWaveform): return self._interpreter.write_analog_waveform( - self._handle, data, auto_start, timeout) + self._handle, data, auto_start, timeout + ) else: data = numpy.asarray(data, dtype=numpy.float64) return self._interpreter.write_analog_f64( - self._handle, number_of_samples_per_channel, auto_start, - timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, + number_of_samples_per_channel, + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) elif write_chan_type == ChannelType.DIGITAL_OUTPUT: if self.out_stream.do_num_booleans_per_chan == 1: - if (not isinstance(element, bool) and - not isinstance(element, numpy.bool_)): + if not isinstance(element, bool) and not isinstance(element, numpy.bool_): raise DaqError( - 'Write failed, because this write method only accepts ' - 'boolean samples when there is one digital line per ' - 'channel in a task.\n\n' - 'Requested sample type: {}'.format(type(element)), - DAQmxErrors.UNKNOWN, task_name=self.name) + "Write failed, because this write method only accepts " + "boolean samples when there is one digital line per " + "channel in a task.\n\n" + "Requested sample type: {}".format(type(element)), + DAQmxErrors.UNKNOWN, + task_name=self.name, + ) data = numpy.asarray(data, dtype=bool) return self._interpreter.write_digital_lines( - self._handle, number_of_samples_per_channel, - auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, + number_of_samples_per_channel, + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) else: - if (not isinstance(element, int) and - not isinstance(element, numpy.uint32)): + if not isinstance(element, int) and not isinstance(element, numpy.uint32): raise DaqError( - 'Write failed, because this write method only accepts ' - 'unsigned 32-bit integer samples when there are ' - 'multiple digital lines per channel in a task.\n\n' - 'Requested sample type: {}'.format(type(element)), - DAQmxErrors.UNKNOWN, task_name=self.name) + "Write failed, because this write method only accepts " + "unsigned 32-bit integer samples when there are " + "multiple digital lines per channel in a task.\n\n" + "Requested sample type: {}".format(type(element)), + DAQmxErrors.UNKNOWN, + task_name=self.name, + ) data = numpy.asarray(data, dtype=numpy.uint32) return self._interpreter.write_digital_u32( - self._handle, number_of_samples_per_channel, - auto_start, timeout, FillMode.GROUP_BY_CHANNEL.value, data) + self._handle, + number_of_samples_per_channel, + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + data, + ) elif write_chan_type == ChannelType.COUNTER_OUTPUT: output_type = channels_to_write.co_output_type @@ -1412,20 +1490,30 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): data = [data] elif not isinstance(data, Iterable): raise DaqError( - 'Write failed, because the provided data type is not supported ' - 'for counter output channels.', - DAQmxErrors.UNKNOWN, task_name=self.name) + "Write failed, because the provided data type is not supported " + "for counter output channels.", + DAQmxErrors.UNKNOWN, + task_name=self.name, + ) if output_type == UsageTypeCO.PULSE_FREQUENCY: if not all(isinstance(sample, CtrFreq) for sample in data): raise TypeError(f"Output type {output_type} requires samples of type CtrFreq.") frequencies = numpy.array([sample.freq for sample in data], dtype=numpy.float64) - duty_cycles = numpy.array([sample.duty_cycle for sample in data], dtype=numpy.float64) + duty_cycles = numpy.array( + [sample.duty_cycle for sample in data], dtype=numpy.float64 + ) return self._interpreter.write_ctr_freq( - self._handle, number_of_samples_per_channel, auto_start, timeout, - FillMode.GROUP_BY_CHANNEL.value, frequencies, duty_cycles) + self._handle, + number_of_samples_per_channel, + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + frequencies, + duty_cycles, + ) elif output_type == UsageTypeCO.PULSE_TIME: if not all(isinstance(sample, CtrTime) for sample in data): @@ -1435,8 +1523,14 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): low_times = numpy.array([sample.low_time for sample in data], dtype=numpy.float64) return self._interpreter.write_ctr_time( - self._handle, number_of_samples_per_channel, auto_start, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_times, low_times) + self._handle, + number_of_samples_per_channel, + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_times, + low_times, + ) elif output_type == UsageTypeCO.PULSE_TICKS: if not all(isinstance(sample, CtrTick) for sample in data): @@ -1446,8 +1540,14 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): low_ticks = numpy.array([sample.low_tick for sample in data], dtype=numpy.uint32) return self._interpreter.write_ctr_ticks( - self._handle, number_of_samples_per_channel, auto_start, timeout, - FillMode.GROUP_BY_CHANNEL.value, high_ticks, low_ticks) + self._handle, + number_of_samples_per_channel, + auto_start, + timeout, + FillMode.GROUP_BY_CHANNEL.value, + high_ticks, + low_ticks, + ) else: raise DaqError( @@ -1459,31 +1559,32 @@ def write(self, data, auto_start=AUTO_START_UNSET, timeout=10.0): else: raise DaqError( - 'Write failed, because there are no output channels in this ' - 'task to which data can be written.', + "Write failed, because there are no output channels in this " + "task to which data can be written.", DAQmxErrors.WRITE_NO_OUTPUT_CHANS_IN_TASK, - task_name=self.name) + task_name=self.name, + ) class _TaskAlternateConstructor(Task): - """ - Provide an alternate constructor for the Task object. + """Provide an alternate constructor for the Task object. This is a private API used to instantiate a Task with an existing task handle and interpreter. """ - # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. + + # Setting __slots__ avoids TypeError: __class__ assignment: 'Base' object layout differs from 'Derived'. # noqa: W505 - doc line too long (108 > 100 characters) (auto-generated noqa) __slots__ = () def __init__(self, task_handle, interpreter, close_on_exit): - """ + """Initialize a new Task with an existing interpreter. + Args: task_handle: Specifies the task handle from which to create a Task object. interpreter: Specifies the interpreter instance. close_on_exit: Specifies whether the task's context manager closes the task. - """ - # Initialize the fields that __del__ accesses so it doesn't crash when _initialize raises an exception. + # Initialize the fields that __del__ accesses so it doesn't crash when _initialize raises an exception. # noqa: W505 - doc line too long (111 > 100 characters) (auto-generated noqa) self._handle = task_handle self._close_on_exit = close_on_exit self._saved_name = "" # _initialize sets this to the name assigned by DAQmx. @@ -1500,7 +1601,8 @@ def __init__(self, task_handle, interpreter, close_on_exit): class _TaskEventType(Enum): """Internal enum for task event bookkeeping.""" + DONE = 1 EVERY_N_SAMPLES_ACQUIRED_INTO_BUFFER = 2 EVERY_N_SAMPLES_TRANSFERRED_FROM_BUFFER = 3 - SIGNAL = 4 \ No newline at end of file + SIGNAL = 4 diff --git a/src/handwritten/task/channels/__init__.py b/src/handwritten/task/channels/__init__.py index 1427c46d1..c9c0a4a88 100644 --- a/src/handwritten/task/channels/__init__.py +++ b/src/handwritten/task/channels/__init__.py @@ -1,9 +1,19 @@ -from nidaqmx.task.channels._channel import Channel +"""NI-DAQmx channel classes.""" + from nidaqmx.task.channels._ai_channel import AIChannel from nidaqmx.task.channels._ao_channel import AOChannel +from nidaqmx.task.channels._channel import Channel from nidaqmx.task.channels._ci_channel import CIChannel from nidaqmx.task.channels._co_channel import COChannel from nidaqmx.task.channels._di_channel import DIChannel from nidaqmx.task.channels._do_channel import DOChannel -__all__ = ['Channel', 'AIChannel', 'AOChannel', 'CIChannel', 'COChannel', 'DIChannel', 'DOChannel',] \ No newline at end of file +__all__ = [ + "Channel", + "AIChannel", + "AOChannel", + "CIChannel", + "COChannel", + "DIChannel", + "DOChannel", +] diff --git a/src/handwritten/task/collections/__init__.py b/src/handwritten/task/collections/__init__.py index 2c93309e5..09748517e 100644 --- a/src/handwritten/task/collections/__init__.py +++ b/src/handwritten/task/collections/__init__.py @@ -1,9 +1,19 @@ -from nidaqmx.task.collections._channel_collection import ChannelCollection +"""NI-DAQmx channel collection classes.""" + from nidaqmx.task.collections._ai_channel_collection import AIChannelCollection from nidaqmx.task.collections._ao_channel_collection import AOChannelCollection +from nidaqmx.task.collections._channel_collection import ChannelCollection from nidaqmx.task.collections._ci_channel_collection import CIChannelCollection from nidaqmx.task.collections._co_channel_collection import COChannelCollection from nidaqmx.task.collections._di_channel_collection import DIChannelCollection from nidaqmx.task.collections._do_channel_collection import DOChannelCollection -__all__ = ['ChannelCollection', 'AIChannelCollection', 'AOChannelCollection', 'CIChannelCollection', 'COChannelCollection', 'DIChannelCollection', 'DOChannelCollection',] \ No newline at end of file +__all__ = [ + "ChannelCollection", + "AIChannelCollection", + "AOChannelCollection", + "CIChannelCollection", + "COChannelCollection", + "DIChannelCollection", + "DOChannelCollection", +] diff --git a/src/handwritten/task/collections/_channel_collection.py b/src/handwritten/task/collections/_channel_collection.py index e8d4cb0c9..a42200f53 100644 --- a/src/handwritten/task/collections/_channel_collection.py +++ b/src/handwritten/task/collections/_channel_collection.py @@ -1,25 +1,25 @@ from collections.abc import Sequence -from nidaqmx.task.channels._channel import Channel -from nidaqmx.errors import DaqError from nidaqmx.error_codes import DAQmxErrors -from nidaqmx.utils import unflatten_channel_string, flatten_channel_string +from nidaqmx.errors import DaqError +from nidaqmx.task.channels._channel import Channel +from nidaqmx.utils import flatten_channel_string, unflatten_channel_string class ChannelCollection(Sequence): - """ - Contains the collection of channels for a DAQmx Task. - + """Contains the collection of channels for a DAQmx Task. + This class defines methods that implements a container object. """ + def __init__(self, task_handle, interpreter): - """ - Do not construct this object directly; instead, construct a nidaqmx.Task and use the appropriate property, such as task.ai_channels. - """ + """Do not construct this object directly; instead, construct a nidaqmx.Task and use the appropriate property, such as task.ai_channels.""" # noqa: W505 - doc line too long (146 > 100 characters) (auto-generated noqa) self._handle = task_handle self._interpreter = interpreter - def __contains__(self, item): + def __contains__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa) + self, item + ): channel_names = self.channel_names if isinstance(item, str): @@ -29,14 +29,13 @@ def __contains__(self, item): return all([item in channel_names for item in items]) - def __eq__(self, other): + def __eq__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) if isinstance(other, self.__class__): return self._handle == other._handle return False def __getitem__(self, index): - """ - Indexes a subset of virtual channels on this channel collection. + """Indexes a subset of virtual channels on this channel collection. Args: index: The value of the index. The following index types are @@ -49,9 +48,10 @@ def __getitem__(self, index): - int: Index/position of the virtual channel in the collection. - slice: Range of the indexes/positions of virtual channels in the collection. + Returns: - nidaqmx.task.channels.Channel: - + nidaqmx.task.channels.Channel: + Indicates a channel object representing the subset of virtual channels indexed. """ @@ -63,30 +63,33 @@ def __getitem__(self, index): channel_names = index else: raise DaqError( - 'Invalid index type "{}" used to access channels.' - .format(type(index)), DAQmxErrors.UNKNOWN) + 'Invalid index type "{}" used to access channels.'.format(type(index)), + DAQmxErrors.UNKNOWN, + ) if channel_names: return Channel._factory(self._handle, channel_names, self._interpreter) else: raise DaqError( - 'You cannot specify an empty index when indexing channels.\n' - 'Index used: {}'.format(index), DAQmxErrors.UNKNOWN) + "You cannot specify an empty index when indexing channels.\n" + "Index used: {}".format(index), + DAQmxErrors.UNKNOWN, + ) - def __hash__(self): + def __hash__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return self._interpreter.hash_task_handle(self._handle) - def __iter__(self): + def __iter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) for channel_name in self.channel_names: yield Channel._factory(self._handle, channel_name, self._interpreter) - def __len__(self): + def __len__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return len(self.channel_names) - def __ne__(self, other): + def __ne__(self, other): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) return not self.__eq__(other) - def __reversed__(self): + def __reversed__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa) channel_names = self.channel_names channel_names.reverse() @@ -95,19 +98,12 @@ def __reversed__(self): @property def all(self): - """ - :class:`nidaqmx.task.channels.Channel`: - Specifies a channel object that represents the entire list of - virtual channels on this channel collection. - """ + """:class:`nidaqmx.task.channels.Channel`: Specifies a channel object that represents the entire list of virtual channels on this channel collection.""" # noqa: W505 - doc line too long (160 > 100 characters) (auto-generated noqa) # Passing a blank string means all channels. - return Channel._factory(self._handle, '', self._interpreter) + return Channel._factory(self._handle, "", self._interpreter) @property def channel_names(self): - """ - List[str]: Specifies the entire list of virtual channels on this - channel collection. - """ + """List[str]: Specifies the entire list of virtual channels on this channel collection.""" val = self._interpreter.get_task_attribute_string(self._handle, 0x1273) return unflatten_channel_string(val) diff --git a/src/handwritten/task/triggering/__init__.py b/src/handwritten/task/triggering/__init__.py index b1d4de025..e4359185d 100644 --- a/src/handwritten/task/triggering/__init__.py +++ b/src/handwritten/task/triggering/__init__.py @@ -1,8 +1,17 @@ -from nidaqmx.task.triggering._triggers import Triggers +"""NI-DAQmx task triggering classes.""" + from nidaqmx.task.triggering._arm_start_trigger import ArmStartTrigger from nidaqmx.task.triggering._handshake_trigger import HandshakeTrigger from nidaqmx.task.triggering._pause_trigger import PauseTrigger from nidaqmx.task.triggering._reference_trigger import ReferenceTrigger from nidaqmx.task.triggering._start_trigger import StartTrigger +from nidaqmx.task.triggering._triggers import Triggers -__all__ = ['Triggers', 'ArmStartTrigger', 'HandshakeTrigger', 'PauseTrigger', 'ReferenceTrigger', 'StartTrigger'] \ No newline at end of file +__all__ = [ + "Triggers", + "ArmStartTrigger", + "HandshakeTrigger", + "PauseTrigger", + "ReferenceTrigger", + "StartTrigger", +] diff --git a/src/handwritten/types.py b/src/handwritten/types.py index 12955c5ff..42a67e2f9 100644 --- a/src/handwritten/types.py +++ b/src/handwritten/types.py @@ -1,62 +1,63 @@ +"""NI-DAQmx data types.""" + import collections import typing # region Task Counter IO namedtuples -CtrFreq = collections.namedtuple( - 'CtrFreq', ['freq', 'duty_cycle']) +CtrFreq = collections.namedtuple("CtrFreq", ["freq", "duty_cycle"]) -CtrTick = collections.namedtuple( - 'CtrTick', ['high_tick', 'low_tick']) +CtrTick = collections.namedtuple("CtrTick", ["high_tick", "low_tick"]) -CtrTime = collections.namedtuple( - 'CtrTime', ['high_time', 'low_time']) +CtrTime = collections.namedtuple("CtrTime", ["high_time", "low_time"]) # endregion # region Power IO namedtuples -PowerMeasurement = collections.namedtuple( - 'PowerMeasurement', ['voltage', 'current']) +PowerMeasurement = collections.namedtuple("PowerMeasurement", ["voltage", "current"]) # endregion # region Watchdog namedtuples AOExpirationState = collections.namedtuple( - 'AOExpirationState', - ['physical_channel', 'expiration_state', 'output_type']) + "AOExpirationState", ["physical_channel", "expiration_state", "output_type"] +) COExpirationState = collections.namedtuple( - 'COExpirationState', ['physical_channel', 'expiration_state']) + "COExpirationState", ["physical_channel", "expiration_state"] +) DOExpirationState = collections.namedtuple( - 'DOExpirationState', ['physical_channel', 'expiration_state']) + "DOExpirationState", ["physical_channel", "expiration_state"] +) # endregion # region Power Up States namedtuples AOPowerUpState = collections.namedtuple( - 'AOPowerUpState', ['physical_channel', 'power_up_state', 'channel_type']) + "AOPowerUpState", ["physical_channel", "power_up_state", "channel_type"] +) -DOPowerUpState = collections.namedtuple( - 'DOPowerUpState', ['physical_channel', 'power_up_state']) +DOPowerUpState = collections.namedtuple("DOPowerUpState", ["physical_channel", "power_up_state"]) DOResistorPowerUpState = collections.namedtuple( - 'DOResistorPowerUpState', ['physical_channel', 'power_up_state']) + "DOResistorPowerUpState", ["physical_channel", "power_up_state"] +) # endregion # region System namedtuples -CDAQSyncConnection = collections.namedtuple( - 'CDAQSyncConnection', ['output_port', 'input_port']) +CDAQSyncConnection = collections.namedtuple("CDAQSyncConnection", ["output_port", "input_port"]) # endregion # region ID Pin namedtuples + class IDPinContents(typing.NamedTuple): """IDPinContents represent the contents of the memory connected to the ID pin.""" @@ -66,4 +67,5 @@ class IDPinContents(typing.NamedTuple): format_code: int """The format code of the binary data.""" + # endregion diff --git a/src/handwritten/utils.py b/src/handwritten/utils.py index 72de56a1a..3eb25f7b1 100644 --- a/src/handwritten/utils.py +++ b/src/handwritten/utils.py @@ -1,13 +1,13 @@ +"""NI-DAQmx utility functions.""" + from __future__ import annotations import re from dataclasses import dataclass -from typing import List, Optional +from nidaqmx._base_interpreter import BaseInterpreter from nidaqmx.errors import DaqError from nidaqmx.grpc_session_options import GrpcSessionOptions -from nidaqmx._base_interpreter import BaseInterpreter - # Method logic adapted from # //Measurements/Infrastructure/dmxf/trunk/2.5/source/nimuck/parseUtilities.cpp @@ -18,7 +18,8 @@ "every colon (':') in the input string. Or, if a name is specified after " "the colon, it must be identical to the name specified immediately before " "the colon. Colons are not allowed within the names of the individual " - "objects.") + "objects." +) @dataclass @@ -40,8 +41,7 @@ def to_flattened_name(self) -> str: def flatten_channel_string(channel_names: list[str]) -> str: - """ - Converts a list of channel names to a comma-delimited list of names. + """Converts a list of channel names to a comma-delimited list of names. You can use this method to convert a list of physical or virtual channel names to a single string prior to using the DAQmx Create Channel methods or @@ -56,6 +56,7 @@ def flatten_channel_string(channel_names: list[str]) -> str: Args: channel_names: The list of physical or virtual channel names. + Returns: The resulting comma-delimited list of physical or virtual channel names. """ @@ -67,7 +68,7 @@ def flatten_channel_string(channel_names: list[str]) -> str: flattened_channel_list = [] previous = _ChannelInfo() for channel_name in unflattened_channel_names: - m = re.search('(.*[^0-9])?([0-9]+)$', channel_name) + m = re.search("(.*[^0-9])?([0-9]+)$", channel_name) if not m: # If the channel name doesn't end in a valid number, just use the # channel name as-is. @@ -81,10 +82,15 @@ def flatten_channel_string(channel_names: list[str]) -> str: current_index = int(current_index_str) if current_base_name == previous.base_name and ( - (current_index == previous.end_index + 1 and - previous.end_index >= previous.start_index) or - (current_index == previous.end_index - 1 and - previous.end_index <= previous.start_index)): + ( + current_index == previous.end_index + 1 + and previous.end_index >= previous.start_index + ) + or ( + current_index == previous.end_index - 1 + and previous.end_index <= previous.start_index + ) + ): # If the current channel name has the same base name as the # previous and it's end index differs by 1, change the end # index value. It gets flattened later. @@ -96,11 +102,11 @@ def flatten_channel_string(channel_names: list[str]) -> str: # get flattened with the previous channel. flattened_channel_list.append(previous.to_flattened_name()) previous = _ChannelInfo( - current_base_name, - current_index, - current_index_str, - current_index, - current_index_str + current_base_name, + current_index, + current_index_str, + current_index, + current_index_str, ) # Convert the final channel dictionary to a flattened string @@ -108,12 +114,11 @@ def flatten_channel_string(channel_names: list[str]) -> str: # Remove empty strings in list, convert to comma-delimited string, then trim # whitespace. - return ','.join([_f for _f in flattened_channel_list if _f]).strip() + return ",".join([_f for _f in flattened_channel_list if _f]).strip() + - def unflatten_channel_string(channel_names: str) -> list[str]: - """ - Converts a comma-delimited list of channel names to a list of names. + """Converts a comma-delimited list of channel names to a list of names. You can use this method to convert a comma-delimited list or range of physical or virtual channels into a list of physical or virtual channel @@ -128,36 +133,33 @@ def unflatten_channel_string(channel_names: str) -> list[str]: Args: channel_names: The list or range of physical or virtual channels. - + Returns: - The list of physical or virtual channel names. - + The list of physical or virtual channel names. + Each element of the list contains a single channel. """ channel_list_to_return = [] - channel_list = [c for c in channel_names.strip().split(',') if c] + channel_list = [c for c in channel_names.strip().split(",") if c] for channel in channel_list: channel = channel.strip() - colon_index = channel.find(':') + colon_index = channel.find(":") if colon_index == -1: channel_list_to_return.append(channel) else: before = channel[:colon_index] - after = channel[colon_index+1:] + after = channel[colon_index + 1 :] - m_before = re.match('(.*?)([0-9]+)$', before) - m_after = re.match('(.*?)([0-9]+)$', after) + m_before = re.match("(.*?)([0-9]+)$", before) + m_after = re.match("(.*?)([0-9]+)$", after) if not m_before or not m_after: - raise DaqError(_invalid_range_syntax_message, - error_code=-200498) + raise DaqError(_invalid_range_syntax_message, error_code=-200498) - if m_after.group(1) and ( - m_before.group(1).lower() != m_after.group(1).lower()): - raise DaqError(_invalid_range_syntax_message, - error_code=-200498) + if m_after.group(1) and (m_before.group(1).lower() != m_after.group(1).lower()): + raise DaqError(_invalid_range_syntax_message, error_code=-200498) num_before_str = m_before.group(2) num_before = int(num_before_str) @@ -168,7 +170,7 @@ def unflatten_channel_string(channel_names: str) -> list[str]: # If there are any leading 0s in the first number, we want to ensure # match that width. This is established precedence in the DAQmx # algorithm. - if num_before > 0 and len(num_before_str.lstrip('0')) < len(num_before_str): + if num_before > 0 and len(num_before_str.lstrip("0")) < len(num_before_str): num_min_width = len(num_before_str) num_max = max([num_before, num_after]) @@ -176,8 +178,7 @@ def unflatten_channel_string(channel_names: str) -> list[str]: number_of_channels = (num_max - num_min) + 1 if number_of_channels >= 15000: - raise DaqError(_invalid_range_syntax_message, - error_code=-200498) + raise DaqError(_invalid_range_syntax_message, error_code=-200498) colon_expanded_channel = [] for i in range(number_of_channels): @@ -199,15 +200,16 @@ def unflatten_channel_string(channel_names: str) -> list[str]: def _select_interpreter( - grpc_options: GrpcSessionOptions | None = None, - interpreter: BaseInterpreter | None = None + grpc_options: GrpcSessionOptions | None = None, interpreter: BaseInterpreter | None = None ) -> BaseInterpreter: if interpreter: return interpreter else: if grpc_options: from nidaqmx._grpc_interpreter import GrpcStubInterpreter + return GrpcStubInterpreter(grpc_options) else: from nidaqmx._library_interpreter import LibraryInterpreter + return LibraryInterpreter()