-
Notifications
You must be signed in to change notification settings - Fork 198
Expand file tree
/
Copy path_task.py
More file actions
1751 lines (1486 loc) · 75.5 KB
/
Copy path_task.py
File metadata and controls
1751 lines (1486 loc) · 75.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import threading
import warnings
from collections.abc import Iterable, Sequence
from enum import Enum
from typing import Any, NoReturn
import numpy
from nitypes.waveform import AnalogWaveform, DigitalWaveform
from nidaqmx import utils
from nidaqmx._feature_toggles import WAVEFORM_SUPPORT, requires_feature
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.types import CtrFreq, CtrTick, CtrTime, PowerMeasurement
from nidaqmx.utils import flatten_channel_string, unflatten_channel_string
__all__ = ["Task"]
class UnsetNumSamplesSentinel:
pass
class UnsetAutoStartSentinel:
pass
NUM_SAMPLES_UNSET = UnsetNumSamplesSentinel()
AUTO_START_UNSET = UnsetAutoStartSentinel()
del UnsetNumSamplesSentinel
del 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.
Args:
new_task_name (Optional[str]): Specifies the name to assign to
the task.
If you use this method in a loop and specify a name for the
task, you must use the DAQmx Clear Task method within the loop
after you are finished with the task. Otherwise, NI-DAQmx
attempts to create multiple tasks with the same name, which
results in an error.
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. # 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.
self._grpc_options = grpc_options
self._event_handlers = {}
if grpc_options and not (
grpc_options.session_name == "" or grpc_options.session_name == new_task_name
):
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,
)
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): # 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,
)
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,
)
def __enter__(self): # noqa: D105 - Missing docstring in magic method (auto-generated noqa)
return self
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__( # noqa: D105 - Missing docstring in magic method (auto-generated noqa)
self, type, value, traceback
):
if self._close_on_exit:
self.close()
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): # noqa: D105 - Missing docstring in magic method (auto-generated noqa)
return not self.__eq__(other)
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."""
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.""" # 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
)
@property
def channel_names(self):
"""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."""
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.""" # 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)
return val
@property
def ai_channels(self) -> AIChannelCollection:
"""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."""
return self._ao_channels
@property
def ci_channels(self) -> CIChannelCollection:
"""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."""
return self._co_channels
@property
def di_channels(self) -> DIChannelCollection:
"""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."""
return self._do_channels
@property
def export_signals(self) -> ExportSignals:
"""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."""
return self._in_stream
@property
def out_stream(self) -> OutStream:
"""Gets the write configurations for the task."""
return self._out_stream
@property
def timing(self) -> Timing:
"""Gets the timing configurations for the task."""
return self._timing
@property
def triggers(self) -> Triggers:
"""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.
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
self._ai_channels = AIChannelCollection(task_handle, interpreter)
self._ao_channels = AOChannelCollection(task_handle, interpreter)
self._ci_channels = CIChannelCollection(task_handle, interpreter)
self._co_channels = COChannelCollection(task_handle, interpreter)
self._di_channels = DIChannelCollection(task_handle, interpreter)
self._do_channels = DOChannelCollection(task_handle, interpreter)
self._export_signals = ExportSignals(task_handle, interpreter)
self._in_stream = InStream(self, interpreter)
self._timing = Timing(task_handle, interpreter)
self._triggers = Triggers(task_handle, interpreter)
self._out_stream = OutStream(self, 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.
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
different method of calculating the actual number of samples per
channel to read.
Args:
num_samps_per_chan (int): Specifies the number of samples per
channel.
"""
if num_samps_per_chan is NUM_SAMPLES_UNSET:
return 1
elif num_samps_per_chan == READ_ALL_AVAILABLE:
if self._interpreter.driver_version >= (24, 5):
# DAQmx_DefaultNumberOfSamplesToRead is 0x31E8
return self._interpreter.get_read_attribute_uint32(self._handle, 0x31E8)
else:
acq_type = self.timing.samp_quant_samp_mode
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
else:
return num_samps_per_chan
def add_global_channels(self, global_channels):
"""Adds global virtual channels from MAX to the given task.
Args:
global_channels (List[nidaqmx.system.storage.persisted_channel.PersistedChannel]):
Specifies the channels to add to the task.
These channels must be valid channels available from MAX.
If you pass an invalid channel, NI-DAQmx returns an error.
This value is ignored if it is empty.
"""
channels = flatten_channel_string([g._name for g in global_channels])
self._interpreter.add_global_chans_to_task(self._handle, channels)
def clear(self):
"""Clears the task.
Before clearing, this method aborts the task, if necessary,
and releases any resources the task reserved. You cannot use a task
after you clear it unless you recreate the task.
If you create a DAQmx Task object within a loop, use this method
within the loop after you are finished with the task to avoid
allocating unnecessary memory.
"""
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,
)
return
first_exception = None
try:
self._interpreter.clear_task(self._handle)
except Exception as ex:
first_exception = first_exception or ex
self._handle = None
with self._event_handler_lock:
event_handlers = self._event_handlers
self._event_handlers = {}
for event_handler in event_handlers.values():
try:
event_handler.close()
except Exception as ex:
first_exception = first_exception or ex
if first_exception:
raise first_exception
close = clear
"""Clears the task.
:meth:`close` is an alias for :meth:`clear`.
"""
def control(self, action):
"""Alters the state of a task according to the action you specify.
Args:
action (nidaqmx.constants.TaskMode): Specifies how to alter
the task state.
"""
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
operation is complete before you stop the task.
Returns:
bool:
Indicates if the measurement or generation completed.
"""
is_task_done = self._interpreter.is_task_done(self._handle)
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.
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
bridge-based sensors.
Args:
channel: is a subset of virtual channels in the task that you want to calibrate.
Use this input if you do not want to calibrate all the channels in the task or
if some channels in the task have open thermocouple detection disabled.
If the input is empty, this VI attempts to calibrate all virtual channels in the task.
skip_unsupported_channels: specifies whether or not to skip channels that do not
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
)
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.
Refer to the calibration procedure for your module for detailed
calibration instructions.
Args:
channel: Specifies a subset of virtual channels in the task that you
want to calibrate. Use this input if you do not want to calibrate
all the channels in the task or if some channels in the task measure
non-bridge-based sensors. If the input is empty, this method attempts
to calibrate all virtual channels in the task.
shunt_resistor_value: Specifies the shunt resistance in ohms.
shunt_resistor_location: Specifies the location of the shunt resistor.
shunt_resistor_select: Specifies which shunt calibration switch to enable.
shunt_resistor_source: Specifies which shunt to use.
skip_unsupported_channels: Specifies whether or not to skip channels that
do not support calibration. If skip_unsupported_channels is True, this
method calibrates only supported channels. If False, this method calibrates
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,
)
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.
Refer to the calibration procedure for your module for detailed
calibration instructions.
Args:
channel: Specifies a subset of virtual channels in the task that you
want to calibrate. Use this input if you do not want to calibrate
all the channels in the task or if some channels in the task measure
non-bridge-based sensors. If the input is empty, this method attempts
to calibrate all virtual channels in the task.
shunt_resistor_value: Specifies the shunt resistance in ohms.
shunt_resistor_location: Specifies the location of the shunt resistor.
shunt_resistor_select: Specifies which shunt calibration switch to enable.
shunt_resistor_source: Specifies which shunt to use.
bridge_resistance: Specifies the bridge resistance in ohms. A value of -1
means to use the nominal bridge resistance specified when you created
the virtual channel.
skip_unsupported_channels: Specifies whether or not to skip channels that
do not support calibration. If skip_unsupported_channels is True, this
method calibrates only supported channels. If False, this method calibrates
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,
)
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.
This is to compensate for offsets introduced by open thermocouple detection.
Keep the measured temperature as constant as possible while performing this
adjustment.
Args:
channel: is a subset of virtual channels in the task that you want to calibrate.
Use this input if you do not want to calibrate all the channels in the task or
if some channels in the task have open thermocouple detection disabled.
If the input is empty, this VI attempts to calibrate all virtual channels in the task.
skip_unsupported_channels: specifies whether or not to skip channels that do not
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
)
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:
- The channel type of the task.
- The number of channels to read.
- The number of samples per channel.
The data type of the samples returned is independently determined by
the channel type of the task.
For digital input measurements, the data type of the samples returned
is determined by the line grouping format of the digital lines.
If the line grouping format is set to "one channel for all lines", the
data type of the samples returned is int. If the line grouping
format is set to "one channel per line", the data type of the samples
returned is boolean.
If you do not set the number of samples per channel, this method
assumes one sample was requested. This method then returns either a
scalar (1 channel to read) or a list (N channels to read).
If you set the number of samples per channel to ANY value (even 1),
this method assumes multiple samples were requested. This method then
returns either a list (1 channel to read) or a list of lists (N
channels to read).
Args:
number_of_samples_per_channel (Optional[int]): Specifies the
number of samples to read. If this input is not set,
assumes samples to read is 1. Conversely, if this input
is set, assumes there are multiple samples to read.
If you set this input to 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.
If the task acquires samples continuously and you set
this input to nidaqmx.constants.READ_ALL_AVAILABLE, this
method reads all the samples currently available in the
buffer.
If the task acquires a finite number of samples and you
set this input to nidaqmx.constants.READ_ALL_AVAILABLE,
the method waits for the task to acquire all requested
samples, then reads those samples. If you set the
"read_all_avail_samp" property to True, the method reads
the samples currently available in the buffer and does
not wait for the task to acquire all requested samples.
timeout (Optional[float]): Specifies the amount of time in
seconds to wait for samples to become available. If the
time elapses, the method returns an error and any
samples read before the timeout elapsed. The default
timeout is 10 seconds. If you set timeout to
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.
Returns:
dynamic:
The samples requested in the form of a scalar, a list, or a
list of lists. See method docstring for more info.
NI-DAQmx scales the data to the units of the measurement,
including any custom scaling you apply to the channels. Use a
DAQmx Create Channel method to specify these units.
Example:
>>> task = Task()
>>> task.ai_channels.add_ai_voltage_chan('Dev1/ai0:3')
>>> data = task.read()
>>> type(data)
<type 'list'>
>>> type(data[0])
<type 'float'>
"""
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
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
)
# 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)
else:
array_shape = (number_of_channels,)
else:
array_shape = (number_of_samples_per_channel,)
if read_chan_type == ChannelType.ANALOG_INPUT:
if any(chan.ai_meas_type == UsageTypeAI.POWER for chan in channels_to_read):
return self._read_power(
array_shape, number_of_channels, number_of_samples_per_channel, timeout
)
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,
)
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,
)
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,
)
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,
]:
return self._read_ctr_pulse(
array_shape,
meas_type,
number_of_channels,
number_of_samples_per_channel,
num_samples_not_set,
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,
)
else:
raise DaqError(
"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,
)
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()
else:
return data[:samples_read].tolist()
return data.tolist()
def _read_ctr_pulse(
self,
array_shape: tuple[int, ...],
meas_type: UsageTypeCI,
number_of_channels: int,
number_of_samples_per_channel: int,
num_samples_not_set: bool,
timeout: float,
) -> CtrFreq | CtrTick | CtrTime | list[CtrFreq] | list[CtrTick] | list[CtrTime]:
if meas_type == UsageTypeCI.PULSE_FREQ:
frequencies = numpy.zeros(array_shape, dtype=numpy.float64)
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,
)
data: list[CtrFreq] | list[CtrTick] | list[CtrTime] = [
CtrFreq(freq=f, duty_cycle=d) for f, d in zip(frequencies, duty_cycles)
]
elif meas_type == UsageTypeCI.PULSE_TIME:
high_times = numpy.zeros(array_shape, dtype=numpy.float64)
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,
)
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,
)
data = [CtrTick(high_tick=h, low_tick=l) for h, l in zip(high_ticks, low_ticks)]
else:
assert False, f"{meas_type} is not a counter pulse measurement type."
if num_samples_not_set and array_shape == (1,):
return data[0]
# Counter pulse measurements should not have N channel versions.
#
# https://github.com/ni/nidaqmx-python/issues/498 - Missing support for
# multi-channel counter reads in stream_readers and task
if samples_read != number_of_samples_per_channel:
assert number_of_channels == 1
return data[:samples_read]
return data
def _read_power(
self,
array_shape: tuple[int, ...],
number_of_channels: int,
number_of_samples_per_channel: int,
timeout: float,
) -> PowerMeasurement | list[PowerMeasurement] | list[list[PowerMeasurement]]:
voltages = numpy.zeros(array_shape, dtype=numpy.float64)
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,
)
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)]
else:
# n channel, n samples
return [
[
PowerMeasurement(voltage=v, current=i)
for v, i in zip(voltages[channel_index], currents[channel_index])
]
for channel_index in range(number_of_channels)
]
else:
if number_of_samples_per_channel == 1:
# 1 channel, 1 sample
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
]
@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.
This read method is dynamic, and is capable of inferring an appropriate
return type based on these factors:
- The channel type of the task.
- The number of channels to read.
- The number of samples per channel.
The data type of the samples returned is independently determined by
the channel type of the task.
If you do not set the number of samples per channel, this method
reads all available data for each channel.
Args:
number_of_samples_per_channel (Optional[int]): Specifies the
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,
NI-DAQmx determines how many samples
to read based on if the task acquires samples
continuously or acquires a finite number of samples.
If the task acquires samples continuously and you set
this input to nidaqmx.constants.READ_ALL_AVAILABLE, this
method reads all the samples currently available in the
buffer.
If the task acquires a finite number of samples and you
set this input to nidaqmx.constants.READ_ALL_AVAILABLE,
the method waits for the task to acquire all requested
samples, then reads those samples. If you set the
"read_all_avail_samp" property to True, the method reads
the samples currently available in the buffer and does
not wait for the task to acquire all requested samples.
timeout (Optional[float]): Specifies the amount of time in
seconds to wait for samples to become available. If the
time elapses, the method returns an error and any
samples read before the timeout elapsed. The default
timeout is 10 seconds. If you set timeout to
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.
Returns:
dynamic:
The samples requested in the form of a waveform (for a single channel)
or a list of waveforms (for multiple channels).
See method docstring for more info.
NI-DAQmx scales the data to the units of the measurement,
including any custom scaling you apply to the channels. Use a
DAQmx Create Channel method to specify these units.
Example:
>>> task = Task()
>>> task.ai_channels.add_ai_voltage_chan('Dev1/ai0')
>>> data = task.read_waveform()
>>> type(data)
<type 'AnalogWaveform'>
""" # 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
)
if read_chan_type == ChannelType.ANALOG_INPUT:
if number_of_channels == 1:
analog_waveform = AnalogWaveform(number_of_samples_per_channel)
self._interpreter.read_analog_waveform(
self._handle,
number_of_samples_per_channel,
timeout,
analog_waveform,
self._in_stream.waveform_attribute_mode,
)
return analog_waveform
else:
analog_waveforms = [
AnalogWaveform(number_of_samples_per_channel) for _ in range(number_of_channels)
]
self._interpreter.read_analog_waveforms(
self._handle,
number_of_samples_per_channel,
timeout,
analog_waveforms,
self._in_stream.waveform_attribute_mode,
)
return analog_waveforms
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
)
self._interpreter.read_digital_waveform(
self._handle,
number_of_samples_per_channel,
timeout,
digital_waveform,
self._in_stream.waveform_attribute_mode,
)
return digital_waveform
else:
return self._interpreter.read_new_digital_waveforms(
self._handle,
number_of_channels,
number_of_samples_per_channel,
self.in_stream.di_num_booleans_per_chan,
timeout,
self._in_stream.waveform_attribute_mode,
)
else:
raise DaqError(
"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,
)
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.
Args:
callback_method (function): Specifies the function that you want
DAQmx to call when the event occurs. The function you pass in
this parameter must have the following prototype:
>>> def callback(task_handle, status, callback_data):
>>> return 0
Upon entry to the callback, the task_handle parameter contains
the handle to the task on which the event occurred. The status
parameter contains the status of the task when the event
occurred. If the status value is negative, it indicates an
error. If the status value is zero, it indicates no error.
If the status value is positive, it indicates a warning. The
callbackData parameter contains the value you passed in the
callbackData parameter of this function.
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
)
with self._event_handler_lock:
assert _TaskEventType.DONE not in self._event_handlers, "Event already registered."
self._event_handlers[_TaskEventType.DONE] = event_handler
else:
self._interpreter.unregister_done_event(self._handle)
with self._event_handler_lock:
event_handler = self._event_handlers.pop(_TaskEventType.DONE, None)
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.
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
pending events.