Skip to content

Commit 729d631

Browse files
committed
handwritten: Run nps fix
1 parent e21b0df commit 729d631

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+1433
-1003
lines changed

src/handwritten/__init__.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
from nidaqmx.errors import DaqError, DaqReadError, DaqWriteError, DaqWarning, DaqResourceWarning
1+
from nidaqmx.errors import (
2+
DaqError,
3+
DaqReadError,
4+
DaqResourceWarning,
5+
DaqWarning,
6+
DaqWriteError,
7+
)
28
from nidaqmx.grpc_session_options import *
39
from nidaqmx.scale import Scale
410
from nidaqmx.task import Task

src/handwritten/_bitfield_utils.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
def enum_bitfield_to_list(bitfield_value, bitfield_enum_type,
2-
actual_enum_type):
1+
def enum_bitfield_to_list(bitfield_value, bitfield_enum_type, actual_enum_type):
32
"""
43
Converts a bitfield value to a list of enums.
54
@@ -14,8 +13,7 @@ def enum_bitfield_to_list(bitfield_value, bitfield_enum_type,
1413
supported_values = []
1514
for bitfield_mask in bitfield_enum_type:
1615
if bitfield_value & bitfield_mask.value:
17-
enum_value = next(
18-
e for e in actual_enum_type if e.name == bitfield_mask.name)
16+
enum_value = next(e for e in actual_enum_type if e.name == bitfield_mask.name)
1917
supported_values.append(enum_value)
2018

2119
return supported_values
@@ -34,8 +32,7 @@ def enum_list_to_bitfield(enum_list, bitfield_enum_type):
3432
"""
3533
bitfield_value = 0
3634
for enum_value in enum_list:
37-
bitfield_mask = next(
38-
b for b in bitfield_enum_type if b.name == enum_value.name)
35+
bitfield_mask = next(b for b in bitfield_enum_type if b.name == enum_value.name)
3936
bitfield_value |= bitfield_mask.value
4037

41-
return bitfield_value
38+
return bitfield_value

src/handwritten/_dotenvpath.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,4 +70,4 @@ def _get_package_path() -> Path:
7070
"""Get the path of this package."""
7171
module = sys.modules[__package__]
7272
assert module.__file__ and module.__file__.endswith("__init__.py")
73-
return Path(module.__file__).parent
73+
return Path(module.__file__).parent

src/handwritten/_feature_toggles.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@
44

55
import functools
66
import sys
7-
from decouple import AutoConfig, Undefined, undefined
87
from enum import Enum
98
from typing import TYPE_CHECKING, Callable, TypeVar
9+
10+
from decouple import AutoConfig, Undefined, undefined
11+
1012
from nidaqmx._dotenvpath import get_dotenv_search_path
1113
from nidaqmx.errors import FeatureNotSupportedError
1214

@@ -36,6 +38,7 @@ def _config(
3638
cast: Callable[[str], _T] | Undefined = undefined,
3739
) -> _T: ...
3840

41+
3942
# Based on the recipe at https://docs.python.org/3/howto/enum.html
4043
class _OrderedEnum(Enum):
4144
def __ge__(self, other: Self) -> bool:
@@ -156,4 +159,4 @@ def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T:
156159
# Define feature toggle constants here:
157160
# --------------------------------------
158161

159-
WAVEFORM_SUPPORT = FeatureToggle("WAVEFORM_SUPPORT", CodeReadiness.INCOMPLETE)
162+
WAVEFORM_SUPPORT = FeatureToggle("WAVEFORM_SUPPORT", CodeReadiness.INCOMPLETE)

src/handwritten/_grpc_time.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
from __future__ import annotations
22

3-
from datetime import timezone
4-
from datetime import datetime as std_datetime
5-
from datetime import tzinfo as dt_tzinfo
6-
from hightime import datetime as ht_datetime
7-
from hightime import timedelta as ht_timedelta
3+
from datetime import datetime as std_datetime, timezone, tzinfo as dt_tzinfo
84
from typing import Optional, Union
9-
from nidaqmx._time import _convert_to_desired_timezone
105

116
from google.protobuf.timestamp_pb2 import Timestamp as GrpcTimestamp
7+
from hightime import datetime as ht_datetime, timedelta as ht_timedelta
8+
9+
from nidaqmx._time import _convert_to_desired_timezone
1210

1311
# 66 years, 17 leap days = 24107 days = 2082844800 seconds
1412
_BIAS_FROM_1970_EPOCH = 2082844800
@@ -22,7 +20,10 @@
2220

2321
_EPOCH_1970 = ht_datetime(1970, 1, 1, tzinfo=timezone.utc)
2422

25-
def convert_time_to_timestamp(dt: std_datetime | ht_datetime, ts: GrpcTimestamp | None = None) -> GrpcTimestamp:
23+
24+
def convert_time_to_timestamp(
25+
dt: std_datetime | ht_datetime, ts: GrpcTimestamp | None = None
26+
) -> GrpcTimestamp:
2627
seconds_since_1970 = 0
2728

2829
if ts is None:
@@ -44,10 +45,11 @@ def convert_time_to_timestamp(dt: std_datetime | ht_datetime, ts: GrpcTimestamp
4445
ts.FromNanoseconds(seconds_since_1970 * _NS_PER_S + nanos)
4546
return ts
4647

48+
4749
def convert_timestamp_to_time(ts: GrpcTimestamp, tzinfo: dt_tzinfo | None = None) -> ht_datetime:
4850
total_nanos = ts.ToNanoseconds()
4951
seconds, nanos = divmod(total_nanos, _NS_PER_S)
5052
# Convert the nanoseconds to yoctoseconds.
5153
total_yoctoseconds = int(round(_YS_PER_NS * nanos))
52-
dt = _EPOCH_1970 + ht_timedelta(seconds = seconds) + ht_timedelta(yoctoseconds=total_yoctoseconds)
54+
dt = _EPOCH_1970 + ht_timedelta(seconds=seconds) + ht_timedelta(yoctoseconds=total_yoctoseconds)
5355
return _convert_to_desired_timezone(dt, tzinfo)

src/handwritten/_install_daqmx.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,12 @@
1313
import sys
1414
import tempfile
1515
import traceback
16-
import requests
1716
import zipfile
1817
from typing import Generator, List, Optional, Tuple
1918
from urllib.parse import urlparse
2019

2120
import click
21+
import requests
2222

2323
if sys.platform.startswith("win"):
2424
import winreg
@@ -101,7 +101,9 @@ def _get_daqmx_installed_version() -> str | None:
101101
commands_info = LINUX_COMMANDS[distribution]
102102
query_command = commands_info.get_daqmx_version
103103
# Run the package query command defined by _linux_installation_commands.py.
104-
query_output = subprocess.run(query_command, stdout=subprocess.PIPE, text=True).stdout # nosec: B603
104+
query_output = subprocess.run(
105+
query_command, stdout=subprocess.PIPE, text=True
106+
).stdout # nosec: B603
105107

106108
if distribution == "ubuntu":
107109
version_match = re.search(r"ii\s+ni-daqmx\s+(\d+\.\d+\.\d+)", query_output)
@@ -127,9 +129,7 @@ def _get_daqmx_installed_version() -> str | None:
127129

128130
# Creating a temp file that we then close and yield - this is used to allow subprocesses to access
129131
@contextlib.contextmanager
130-
def _multi_access_temp_file(
131-
*, suffix: str = ".exe", delete: bool = True
132-
) -> Generator[str]:
132+
def _multi_access_temp_file(*, suffix: str = ".exe", delete: bool = True) -> Generator[str]:
133133
"""
134134
Context manager for creating a temporary file.
135135
@@ -244,7 +244,7 @@ def _install_daqmx_driver_windows_core(download_url: str) -> None:
244244
_logger.info("Downloading Driver to %s", temp_file)
245245
response = requests.get(download_url, timeout=_NETWORK_TIMEOUT_IN_SECONDS)
246246
response.raise_for_status()
247-
with open(temp_file, 'wb') as f:
247+
with open(temp_file, "wb") as f:
248248
f.write(response.content)
249249
_logger.info("Installing NI-DAQmx")
250250
# Run the installer that we just downloaded from https://download.ni.com.
@@ -274,7 +274,7 @@ def _install_daqmx_driver_linux_core(download_url: str, release: str) -> None:
274274
_logger.info("Downloading Driver to %s", temp_file)
275275
response = requests.get(download_url, timeout=_NETWORK_TIMEOUT_IN_SECONDS)
276276
response.raise_for_status()
277-
with open(temp_file, 'wb') as f:
277+
with open(temp_file, "wb") as f:
278278
f.write(response.content)
279279

280280
with tempfile.TemporaryDirectory() as temp_folder:
@@ -443,9 +443,7 @@ def _install_daqmx_driver():
443443
installed_version, latest_version, release
444444
)
445445
else:
446-
user_response = _fresh_install_daqmx_user_confirmation(
447-
latest_version, release
448-
)
446+
user_response = _fresh_install_daqmx_user_confirmation(latest_version, release)
449447

450448
if user_response:
451449
if platform == "Linux":

src/handwritten/_lib.py

Lines changed: 46 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,40 @@
11
from __future__ import annotations
22

3-
from ctypes.util import find_library
43
import ctypes
5-
from numpy.ctypeslib import ndpointer
4+
import locale
65
import platform
76
import sys
87
import threading
9-
import locale
8+
from ctypes.util import find_library
9+
from typing import TYPE_CHECKING, cast
10+
1011
from decouple import config
11-
from typing import cast, TYPE_CHECKING
12+
from numpy.ctypeslib import ndpointer
1213

13-
from nidaqmx.errors import DaqNotFoundError, DaqNotSupportedError, DaqFunctionNotSupportedError
14+
from nidaqmx.errors import (
15+
DaqFunctionNotSupportedError,
16+
DaqNotFoundError,
17+
DaqNotSupportedError,
18+
)
1419

1520
if TYPE_CHECKING:
1621
from typing_extensions import TypeAlias
1722

1823

19-
_DAQ_NOT_FOUND_MESSAGE = "Could not find an installation of NI-DAQmx. Please ensure that NI-DAQmx " \
20-
"is installed on this machine or contact National Instruments for support."
24+
_DAQ_NOT_FOUND_MESSAGE = (
25+
"Could not find an installation of NI-DAQmx. Please ensure that NI-DAQmx "
26+
"is installed on this machine or contact National Instruments for support."
27+
)
2128

22-
_DAQ_NOT_SUPPORTED_MESSAGE = "NI-DAQmx Python is not supported on this platform: {0}. Please " \
23-
"direct any questions or feedback to National Instruments."
29+
_DAQ_NOT_SUPPORTED_MESSAGE = (
30+
"NI-DAQmx Python is not supported on this platform: {0}. Please "
31+
"direct any questions or feedback to National Instruments."
32+
)
2433

25-
_FUNCTION_NOT_SUPPORTED_MESSAGE = "The NI-DAQmx function \"{0}\" is not supported in this version " \
26-
"of NI-DAQmx. Visit ni.com/downloads to upgrade."
34+
_FUNCTION_NOT_SUPPORTED_MESSAGE = (
35+
'The NI-DAQmx function "{0}" is not supported in this version '
36+
"of NI-DAQmx. Visit ni.com/downloads to upgrade."
37+
)
2738

2839

2940
class c_bool32(ctypes.c_uint):
@@ -48,9 +59,10 @@ def _setter(self, val):
4859

4960
class CtypesByteString:
5061
"""
51-
Custom argtype that automatically converts unicode strings to encoding
62+
Custom argtype that automatically converts unicode strings to encoding
5263
used by the DAQmx C API DLL in Python 3.
5364
"""
65+
5466
@classmethod
5567
def from_param(cls, param):
5668
if isinstance(param, str):
@@ -75,8 +87,7 @@ def from_param(cls, obj):
7587
return obj
7688
return base.from_param(obj)
7789

78-
return type(base.__name__, (base,),
79-
{'from_param': classmethod(from_param)})
90+
return type(base.__name__, (base,), {"from_param": classmethod(from_param)})
8091

8192

8293
class DaqFunctionImporter:
@@ -94,9 +105,9 @@ def __init__(self, library):
94105
def __getattr__(self, function):
95106
try:
96107
cfunc = getattr(self._library, function)
97-
if not hasattr(cfunc, 'arglock'):
108+
if not hasattr(cfunc, "arglock"):
98109
with self._lib_lock:
99-
if not hasattr(cfunc, 'arglock'):
110+
if not hasattr(cfunc, "arglock"):
100111
cfunc.arglock = threading.Lock()
101112
return cfunc
102113
except AttributeError:
@@ -125,7 +136,7 @@ def get_encoding_from_locale() -> str:
125136
Gets the current locale encoding handling cases where it is unset.
126137
"""
127138
_, encoding = locale.getlocale()
128-
return encoding or 'ascii'
139+
return encoding or "ascii"
129140

130141

131142
class DaqLibImporter:
@@ -159,7 +170,7 @@ def task_handle(self) -> type:
159170
@property
160171
def cal_handle(self) -> type:
161172
return CalHandle
162-
173+
163174
@property
164175
def encoding(self):
165176
if self._encoding is None:
@@ -178,42 +189,44 @@ def _import_lib(self):
178189
cdll = None
179190
encoding = None
180191

181-
if sys.platform.startswith('win'):
192+
if sys.platform.startswith("win"):
182193

183194
def _load_lib(libname: str):
184195
windll = ctypes.windll.LoadLibrary(libname)
185196
cdll = ctypes.cdll.LoadLibrary(libname)
186-
return windll, cdll
187-
197+
return windll, cdll
198+
188199
# Feature Toggle to load nicaiu.dll or nicai_utf8.dll
189200
# The Feature Toggle can be set in the .env file
190-
nidaqmx_c_library = config('NIDAQMX_C_LIBRARY', default=None)
191-
201+
nidaqmx_c_library = config("NIDAQMX_C_LIBRARY", default=None)
202+
192203
if nidaqmx_c_library is not None:
193-
try:
194-
if nidaqmx_c_library=="nicaiu":
204+
try:
205+
if nidaqmx_c_library == "nicaiu":
195206
windll, cdll = _load_lib("nicaiu")
196207
encoding = get_encoding_from_locale()
197-
elif nidaqmx_c_library=="nicai_utf8":
208+
elif nidaqmx_c_library == "nicai_utf8":
198209
windll, cdll = _load_lib("nicai_utf8")
199-
encoding = 'utf-8'
210+
encoding = "utf-8"
200211
else:
201-
raise ValueError(f"Unsupported NIDAQMX_C_LIBRARY value: {nidaqmx_c_library}")
212+
raise ValueError(
213+
f"Unsupported NIDAQMX_C_LIBRARY value: {nidaqmx_c_library}"
214+
)
202215
except OSError as e:
203-
raise DaqNotFoundError(_DAQ_NOT_FOUND_MESSAGE) from e
216+
raise DaqNotFoundError(_DAQ_NOT_FOUND_MESSAGE) from e
204217
else:
205218
try:
206219
windll, cdll = _load_lib("nicai_utf8")
207-
encoding = 'utf-8'
220+
encoding = "utf-8"
208221
except OSError:
209222
# Fallback to nicaiu.dll if nicai_utf8.dll cannot be loaded
210223
try:
211224
windll, cdll = _load_lib("nicaiu")
212225
encoding = get_encoding_from_locale()
213226
except OSError as e:
214-
raise DaqNotFoundError(_DAQ_NOT_FOUND_MESSAGE) from e
215-
elif sys.platform.startswith('linux'):
216-
library_path = find_library('nidaqmx')
227+
raise DaqNotFoundError(_DAQ_NOT_FOUND_MESSAGE) from e
228+
elif sys.platform.startswith("linux"):
229+
library_path = find_library("nidaqmx")
217230
if library_path is not None:
218231
cdll = ctypes.cdll.LoadLibrary(library_path)
219232
windll = cdll

0 commit comments

Comments
 (0)