|
| 1 | +"""Example of logging multiple synchronized tasks to a single TDMS file using a queue. |
| 2 | +
|
| 3 | +This example demonstrates how to: |
| 4 | +1. Synchronize multiple DAQmx tasks using a shared clock |
| 5 | +2. Use a producer-consumer pattern with a queue |
| 6 | +3. Log data from multiple tasks to a single TDMS file |
| 7 | +""" |
| 8 | + |
| 9 | +import os |
| 10 | +import queue |
| 11 | +import threading |
| 12 | +import time |
| 13 | +from collections.abc import Sequence |
| 14 | +from concurrent.futures import ThreadPoolExecutor |
| 15 | +from pathlib import Path |
| 16 | + |
| 17 | +import numpy as np |
| 18 | +from nitypes.waveform import AnalogWaveform |
| 19 | +from nptdms import ChannelObject, GroupObject, RootObject, TdmsFile, TdmsWriter |
| 20 | + |
| 21 | +import nidaqmx |
| 22 | +from nidaqmx.constants import ( |
| 23 | + AcquisitionType, |
| 24 | + Edge, |
| 25 | +) |
| 26 | +from nidaqmx.stream_readers import AnalogMultiChannelReader, CounterReader |
| 27 | + |
| 28 | +os.environ["NIDAQMX_ENABLE_WAVEFORM_SUPPORT"] = "1" |
| 29 | + |
| 30 | +# Configuration |
| 31 | +SAMPLE_RATE = 1000 |
| 32 | +SAMPLES_PER_CHANNEL = 1000 |
| 33 | +TIMEOUT = 10.0 |
| 34 | +# Note: This example currently assumes all tasks run on a single synchronized device. |
| 35 | +# To make this example work across multiple devices, share the sample clock |
| 36 | +# between devices using the PXI trigger bus or a PFI line. |
| 37 | +DEVICE_NAME = "Dev1" |
| 38 | + |
| 39 | +TaskData = tuple[ |
| 40 | + Sequence[AnalogWaveform[np.float64]], # Analog input: sequence of waveforms |
| 41 | + AnalogWaveform[np.float64], # Counter input: waveform |
| 42 | +] |
| 43 | + |
| 44 | +data_queue: queue.Queue[TaskData | None] = queue.Queue(maxsize=10) |
| 45 | + |
| 46 | + |
| 47 | +def producer( |
| 48 | + tasks: Sequence[nidaqmx.Task], |
| 49 | + data_queue: queue.Queue[TaskData | None], |
| 50 | + stop_event: threading.Event, |
| 51 | +) -> None: |
| 52 | + """Producer function that reads data from DAQmx tasks and puts it in the queue.""" |
| 53 | + # The queue holds a tuple with task data: |
| 54 | + # ( |
| 55 | + # Sequence[AnalogWaveform], # Element 0: AI data - sequence of waveform objects |
| 56 | + # AnalogWaveform, # Element 1: Counter data - single waveform object |
| 57 | + # ) |
| 58 | + ai_reader = AnalogMultiChannelReader(tasks[0].in_stream) |
| 59 | + counter_reader = CounterReader(tasks[1].in_stream) |
| 60 | + |
| 61 | + num_ai_channels = len(tasks[0].ai_channels.all) |
| 62 | + |
| 63 | + try: |
| 64 | + while not stop_event.is_set(): |
| 65 | + |
| 66 | + ai_waveforms = [ |
| 67 | + AnalogWaveform(sample_count=SAMPLES_PER_CHANNEL) for _ in range(num_ai_channels) |
| 68 | + ] |
| 69 | + counter_waveform = AnalogWaveform(sample_count=SAMPLES_PER_CHANNEL) |
| 70 | + |
| 71 | + ai_reader.read_waveforms( |
| 72 | + ai_waveforms, number_of_samples_per_channel=SAMPLES_PER_CHANNEL, timeout=TIMEOUT |
| 73 | + ) |
| 74 | + |
| 75 | + counter_reader.read_many_sample_double( |
| 76 | + counter_waveform.raw_data, |
| 77 | + number_of_samples_per_channel=SAMPLES_PER_CHANNEL, |
| 78 | + timeout=TIMEOUT, |
| 79 | + ) |
| 80 | + counter_waveform.timing = ai_waveforms[0].timing |
| 81 | + counter_waveform.channel_name = tasks[1].channel_names[0] |
| 82 | + |
| 83 | + data_queue.put((ai_waveforms, counter_waveform)) |
| 84 | + |
| 85 | + except Exception as e: |
| 86 | + print(f"Error in producer: {e}") |
| 87 | + stop_event.set() |
| 88 | + finally: |
| 89 | + data_queue.put(None) |
| 90 | + |
| 91 | + |
| 92 | +def consumer( |
| 93 | + data_queue: queue.Queue[TaskData | None], |
| 94 | + tdms_path: str, |
| 95 | + group_names: Sequence[str], |
| 96 | + channel_names: Sequence[Sequence[str]], |
| 97 | + stop_event: threading.Event, |
| 98 | +) -> None: |
| 99 | + """Consumer function that writes data from the queue to a TDMS file.""" |
| 100 | + with TdmsWriter(tdms_path) as tdms_writer: |
| 101 | + while not stop_event.is_set(): |
| 102 | + try: |
| 103 | + data = data_queue.get(timeout=TIMEOUT) |
| 104 | + |
| 105 | + except queue.Empty: |
| 106 | + continue |
| 107 | + |
| 108 | + if data is None: |
| 109 | + break |
| 110 | + |
| 111 | + ai_waveforms, counter_waveform = data |
| 112 | + |
| 113 | + sample_rate = 1.0 / ai_waveforms[0].timing.sample_interval.total_seconds() |
| 114 | + |
| 115 | + root_object = RootObject( |
| 116 | + properties={"Creation Time": time.strftime("%Y-%m-%d %H:%M:%S")} |
| 117 | + ) |
| 118 | + |
| 119 | + objects_to_write = [root_object] |
| 120 | + |
| 121 | + ai_group = GroupObject("AI_Task", properties={"Sample Rate": sample_rate}) |
| 122 | + objects_to_write.append(ai_group) |
| 123 | + |
| 124 | + for chan_idx, waveform in enumerate(ai_waveforms): |
| 125 | + |
| 126 | + channel = ChannelObject( |
| 127 | + "AI_Task", |
| 128 | + f"Channel{chan_idx + 1:02d}", |
| 129 | + waveform.raw_data, |
| 130 | + properties={ |
| 131 | + "Sample Rate": sample_rate, |
| 132 | + "wf_increment": waveform.timing.sample_interval.total_seconds(), |
| 133 | + "wf_samples": len(waveform.raw_data), |
| 134 | + "wf_start_offset": 0.0, |
| 135 | + "wf_start_time": waveform.timing.to_datetime().start_time.strftime( |
| 136 | + "%Y-%m-%d %H:%M:%S" |
| 137 | + ), |
| 138 | + }, |
| 139 | + ) |
| 140 | + objects_to_write.append(channel) |
| 141 | + |
| 142 | + ci_group = GroupObject("CI_Task", properties={"Sample Rate": sample_rate}) |
| 143 | + objects_to_write.append(ci_group) |
| 144 | + |
| 145 | + channel = ChannelObject( |
| 146 | + "CI_Task", |
| 147 | + "Counter0", |
| 148 | + counter_waveform.raw_data, |
| 149 | + properties={ |
| 150 | + "Sample Rate": sample_rate, |
| 151 | + "wf_increment": counter_waveform.timing.sample_interval.total_seconds(), |
| 152 | + "wf_samples": len(counter_waveform.raw_data), |
| 153 | + "wf_start_offset": 0.0, |
| 154 | + "wf_start_time": counter_waveform.timing.to_datetime().start_time.strftime( |
| 155 | + "%Y-%m-%d %H:%M:%S" |
| 156 | + ), |
| 157 | + }, |
| 158 | + ) |
| 159 | + objects_to_write.append(channel) |
| 160 | + |
| 161 | + # Write all objects to TDMS file |
| 162 | + tdms_writer.write_segment(objects_to_write) |
| 163 | + |
| 164 | + |
| 165 | +def main(): |
| 166 | + """Run the synchronized data acquisition and logging example. |
| 167 | +
|
| 168 | + Creates multiple synchronized DAQmx tasks: |
| 169 | + - A counter output task for the sample clock |
| 170 | + - An analog input task reading from two voltage channels |
| 171 | + - A counter input task counting edges |
| 172 | +
|
| 173 | + Data is acquired continuously until user presses Enter, then saved to a TDMS file |
| 174 | + using a producer-consumer pattern with a queue for thread-safe data transfer. |
| 175 | + """ |
| 176 | + data_queue: queue.Queue[TaskData | None] = queue.Queue(maxsize=10) |
| 177 | + stop_event = threading.Event() |
| 178 | + |
| 179 | + ai_task = nidaqmx.Task() |
| 180 | + ci_task = nidaqmx.Task() |
| 181 | + |
| 182 | + script_dir = Path(__file__).resolve().parent |
| 183 | + tdms_filepath = script_dir / "multi_task_data.tdms" |
| 184 | + |
| 185 | + try: |
| 186 | + |
| 187 | + ai_task.ai_channels.add_ai_voltage_chan(f"{DEVICE_NAME}/ai0", "Channel01") |
| 188 | + ai_task.ai_channels.add_ai_voltage_chan(f"{DEVICE_NAME}/ai1", "Channel02") |
| 189 | + ai_task.timing.cfg_samp_clk_timing( |
| 190 | + SAMPLE_RATE, sample_mode=AcquisitionType.CONTINUOUS, samps_per_chan=SAMPLES_PER_CHANNEL |
| 191 | + ) |
| 192 | + |
| 193 | + ci_chan = ci_task.ci_channels.add_ci_count_edges_chan( |
| 194 | + f"{DEVICE_NAME}/ctr0", "Counter0", edge=Edge.RISING, initial_count=0 |
| 195 | + ) |
| 196 | + ci_chan.ci_count_edges_term = f"{DEVICE_NAME}/PFI0" |
| 197 | + ci_task.timing.cfg_samp_clk_timing( |
| 198 | + SAMPLE_RATE, |
| 199 | + f"/{DEVICE_NAME}/ai/SampleClock", |
| 200 | + sample_mode=AcquisitionType.CONTINUOUS, |
| 201 | + samps_per_chan=SAMPLES_PER_CHANNEL, |
| 202 | + ) |
| 203 | + |
| 204 | + # Start the Analog task last since the Counter task is using its clock |
| 205 | + ci_task.start() |
| 206 | + ai_task.start() |
| 207 | + |
| 208 | + with ThreadPoolExecutor(max_workers=2) as executor: |
| 209 | + producer_future = executor.submit(producer, [ai_task, ci_task], data_queue, stop_event) |
| 210 | + consumer_future = executor.submit( |
| 211 | + consumer, |
| 212 | + data_queue, |
| 213 | + str(tdms_filepath), |
| 214 | + ["AI_Task", "CI_Task"], |
| 215 | + [["Channel01", "Channel02"], ["Counter0"]], |
| 216 | + stop_event, |
| 217 | + ) |
| 218 | + |
| 219 | + print("Acquiring and logging data. Press Enter to stop...") |
| 220 | + input() |
| 221 | + |
| 222 | + stop_event.set() |
| 223 | + |
| 224 | + producer_future.result() |
| 225 | + consumer_future.result() |
| 226 | + |
| 227 | + finally: |
| 228 | + for task in [ai_task, ci_task]: |
| 229 | + if task: |
| 230 | + task.stop() |
| 231 | + task.close() |
| 232 | + |
| 233 | + print("\nAcquisition complete. Data saved to multi_task_data.tdms") |
| 234 | + |
| 235 | + if os.path.exists("multi_task_data.tdms_index"): |
| 236 | + os.remove("multi_task_data.tdms_index") |
| 237 | + |
| 238 | + with TdmsFile.open(tdms_filepath) as tdms_file: |
| 239 | + for group in tdms_file.groups(): |
| 240 | + print("Group:", group.name) |
| 241 | + for channel in group.channels(): |
| 242 | + data = channel[:] |
| 243 | + print(f"\nFirst 10 samples from {group.name}/{channel.name}:") |
| 244 | + print(data[:10]) |
| 245 | + |
| 246 | + |
| 247 | +if __name__ == "__main__": |
| 248 | + main() |
0 commit comments