API streaming and stream_to_file | Python
-
Moku:Go
Moku:Go Arbitrary Waveform Generator Moku:Go Data Logger Moku:Go Frequency Response Analyzer Moku:Go Logic Analyzer & Pattern Generator Moku:Go Oscilloscope & Voltmeter Moku:Go PID Controller Moku:Go Spectrum Analyzer Moku:Go Waveform Generator Moku:Go Power Supplies Moku:Go Digital Filter Box Moku:Go FIR Filter Builder Moku:Go Lock-in Amplifier Moku:Go General Moku:Go Logic Analyzer/Pattern Generator Moku:Go Time & Frequency Analyzer Moku:Go Laser Lock Box Moku:Go Phasemeter
-
Moku:Lab
Moku:Lab General Moku:Lab Arbitrary Waveform Generator Moku:Lab Data Logger Moku:Lab Digital Filter Box Moku:Lab FIR Filter Builder Moku:Lab Frequency Response Analyzer Moku:Lab Laser Lock Box Moku:Lab Lock-in Amplifier Moku:Lab Oscilloscope Moku:Lab Phasemeter Moku:Lab PID Controller Moku:Lab Spectrum Analyzer Moku:Lab Waveform Generator Moku:Lab Time & Frequency Analyzer Moku:Lab Logic Analyzer/Pattern Generator
-
Moku:Pro
Moku:Pro Arbitrary Waveform Generator Moku:Pro Data Logger Moku:Pro Frequency Response Analyzer Moku:Pro Oscilloscope Moku:Pro PID Controller Moku:Pro Spectrum Analyzer Moku:Pro Waveform Generator Moku:Pro Lock-in Amplifier Moku:Pro Digital Filter Box Moku:Pro FIR Filter Builder Moku:Pro Phasemeter Moku:Pro Multi-instrument Mode Moku:Pro General Moku:Pro Logic Analyzer/Pattern Generator Moku:Pro Time & Frequency Analyzer
- Python API
- MATLAB API
- Arbitrary Waveform Generator
- Data Logger
- Digital Filter Box
- FIR Filter Builder
- Frequency Response Analyzer
- Laser Lock Box
- Lock-in Amplifier
- Oscilloscope
- Phasemeter
- PID Controller
- Spectrum Analyzer
- Time & Frequency Analyzer
- Waveform Generator
- Logic Analyzer & Pattern Generator
- Multi Instrument Mode
- Moku Cloud Compile
- Moku general
- LabVIEW
Streaming options
stream_to_file method
This is useful for when you want to log data but you don't want to convert it externally using mokucli, see API download log file and convert | Python for this use case. This converts the file as it in being downloaded and will be ready to analyze once the streaming session is complete.
# moku example: Datalogger Stream to File
# (c) 2025 Liquid Instruments Pty. Ltd.
import os
import csv
import time
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
from moku.instruments import Datalogger
# Connect to your Moku
i = Datalogger('192.168.###.###', force_connect=False)
try:
# Set-up the Datalogger
i.set_samplerate(100)
i.set_acquisition_mode(mode='Precision')
i.generate_waveform(channel=1, type='Sine', amplitude=1, frequency=10e3)
# Start a streaming session and stream to a file, include the file type in the
# file name; csv, hdf5, npy, or mat
i.start_streaming(duration=10)
now = datetime.now().strftime("%Y%m%d_%H%M%S")
file_name = f'MokuDataStreamingData_{now}.csv'
i.stream_to_file(file_name)
print(f"Streaming to file: {file_name}")
print(i.get_stream_status()['status'])
# Track progress percentage of the data streaming session
status = 'RUNNING'
while status == 'RUNNING':
time.sleep(0.5)
progress = i.get_stream_status()
status = progress['status']
# It may take a few moments for the file to appear in the system as accessible
time.sleep(5)
channels = 2
print(file_name)
except Exception as e:
i.relinquish_ownership()
raise e
else:
# Close the connection to the Moku device
i.relinquish_ownership()
# Check for the file, then open the file and create data dictionary
assert os.path.isfile(file_name), "Streaming failed, no file received"
data = {'time':[], 'ch1':[]}
with open(file_name, 'r') as f:
load = csv.reader(f)
file = np.array([[float(row[0])] + [float(row[i]) for i in range(1, channels+1)] for row in load if row[0][0] != '%'])
f.close()
data['time'] = file[:,0]
for i in range(1, channels+1):
data[f'ch{i}'] = file[:,i]
# Display the streamed data
keys = data.keys()
for key in keys:
print(f"'{key}': {str(data[key][:3])[:-1]} ... {data[key][-1]}]")
# Plot the streamed data
fig = plt.figure(figsize=(10, 3))
for i in range(1, channels+1):
plt.plot(data['time'], data[f'ch{i}'], label=f'Channel {i}')
plt.xlim([data['time'][0], data['time'][-1]])
plt.title("Logged Data")
plt.grid(True)
plt.xlabel("Time (s)")
plt.ylabel("Voltage (V)")
plt.legend(loc=0)
plt.show()
The output will look similar to:
Streaming to file: MokuDataStreamingData_20250116_165246.csv
RUNNING
MokuDataStreamingData_20250116_165246.csv
'time': [0. 0.01 0.02 ... 9.99]
'ch1': [0.00117748 0.00105914 0.00114431 ... 0.001142182695]
'ch2': [0.01485419 0.01477556 0.01476971 ... 0.01479722506]
For streaming to other file types:
file_name = f'MokuDataStreamingData_{now}.npy'
i.stream_to_file(file_name)
file_name = f'MokuDataStreamingData_{now}.hdf5'
i.stream_to_file(file_name)
file_name = f'MokuDataStreamingData_{now}.mat'
i.stream_to_file(file_name)
To analyze the data from these file types, refer to this article:
Other file type conversions and reading methods for Python
streaming method
This method is useful for when you want to analyze the data in real-time rather than waiting for the streaming session to complete.
# moku example: Datalogger Streaming
# (c) 2025 Liquid Instruments Pty. Ltd.
import os
import time
from moku.instruments import Datalogger
import matplotlib.pyplot as plt
# Connect to your Moku
i = Datalogger('192.168.###.###', force_connect=False)
try:
# Set-up the Datalogger
i.set_samplerate(100)
i.set_acquisition_mode(mode='Precision')
i.generate_waveform(channel=1, type='Sine', amplitude=1, frequency=10e3)
# stream the data for 10 seconds..
i.start_streaming(duration=10)
# Set up the plotting parameters
plt.ion()
plt.show()
plt.grid(visible=True)
plt.ylim([-1, 1])
plt.title("Streamed Data")
plt.xlabel("Time (s)")
plt.ylabel("Voltage (V)")
line1, = plt.plot([])
line2, = plt.plot([])
plt.legend(['Channel 1', 'Channel 2'], loc=1)
# Configure labels for axes
ax = plt.gca()
# This loops continuously updates the plot with new data
while True:
# get the chunk of streamed data
data = i.get_stream_data()
if data:
plt.xlim([data['time'][0], data['time'][-1]])
# Update the plot
line1.set_ydata(data['ch1'])
line1.set_xdata(data['time'])
line2.set_ydata(data['ch2'])
line2.set_xdata(data['time'])
plt.pause(0.001)
except Exception as e:
i.stop_streaming()
print(e)
finally:
i.relinquish_ownership()