from io import BytesIO
from math import sqrt
from re import search
import matplotlib.image as mpimg # type: ignore
import matplotlib.pyplot as plt # type: ignore
import numpy as np
from pyvisa import ResourceManager
from pyvisa.errors import LibraryError
def find_visas():
# Return all VISA addresses (and the backend) which map to a Rigol DS1000Z.
RIGOL_IDN_REGEX = "^RIGOL TECHNOLOGIES,DS1[01][057]4Z(-S)?( Plus)?,.+$"
visas = []
for visa_backend in ["@ivi", "@py"]:
try:
visa_manager = ResourceManager(visa_backend)
except (LibraryError, OSError, ValueError):
# The backend is unavailable (e.g. no NI-VISA library installed for
# "@ivi", which raises a plain OSError rather than a LibraryError);
# skip it instead of letting the error propagate.
continue
try:
resource_names = visa_manager.list_resources()
except Exception:
# Enumerating a backend can itself fail (e.g. a wedged USB layer);
# skip the whole backend rather than crashing discovery.
continue
for visa_name in resource_names:
try:
visa_resource = visa_manager.open_resource(visa_name)
except Exception:
# Any backend (serial/USB/TCPIP) can fail to open a given
# resource — a busy serial port (e.g. a Bluetooth /dev/cu.*),
# missing permissions, or no device behind it. Discovery is
# best-effort: skip this resource and keep scanning.
continue
try:
if search(RIGOL_IDN_REGEX, visa_resource.query("*IDN?")):
visas.append((visa_name, visa_backend))
except Exception:
pass
finally:
visa_resource.close()
return visas
[docs]
def process_display(display, show=False, filename=None):
"""
Convert the query of the display byte array into an image.
Args:
display: The namedtuple returned from ``Rigol_DS100Z().display()``.
show (bool): Draw the display image to a new matplotlib figure.
filename (str): Save the display image to a file (PNG recommended).
"""
byte_stream = BytesIO(bytearray(display.data))
with byte_stream:
img = mpimg.imread(byte_stream, format="jpeg")
if filename is not None:
plt.imsave(filename, img)
if show:
rigol_xpx, rigol_ypx = 800, 480
rigol_diagin = 17.8 * 0.393701
rigol_dpi = sqrt(rigol_xpx**2 + rigol_ypx**2) / rigol_diagin
figsize = rigol_xpx / rigol_dpi, rigol_ypx / rigol_dpi
fig = plt.figure(figsize=figsize, dpi=rigol_dpi)
ax = fig.add_axes([0, 0, 1, 1])
ax.axis("off")
ax.imshow(img)
plt.show()