INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
|---|---|
Moves an 8-bit block of data from local memory to the specified address space and offset.
Corresponds to viMoveOut8* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
Corresponds to viMoveOut8 function of the VISA library.
|
def move_out_8(library, session, space, offset, length, data, extended=False):
"""Moves an 8-bit block of data from local memory to the specified address space and offset.
Corresponds to viMoveOut8* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
Corresponds to viMoveOut8 function of the VISA library.
"""
converted_buffer = (ViUInt8 * length)(*tuple(data))
if extended:
return library.viMoveOut8Ex(session, space, offset, length, converted_buffer)
else:
return library.viMoveOut8(session, space, offset, length, converted_buffer)
|
Moves an 16-bit block of data from local memory to the specified address space and offset.
Corresponds to viMoveOut16* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def move_out_16(library, session, space, offset, length, data, extended=False):
"""Moves an 16-bit block of data from local memory to the specified address space and offset.
Corresponds to viMoveOut16* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
converted_buffer = (ViUInt16 * length)(*tuple(data))
if extended:
return library.viMoveOut16Ex(session, space, offset, length, converted_buffer)
else:
return library.viMoveOut16(session, space, offset, length, converted_buffer)
|
Moves an 64-bit block of data from local memory to the specified address space and offset.
Corresponds to viMoveOut64* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def move_out_64(library, session, space, offset, length, data, extended=False):
"""Moves an 64-bit block of data from local memory to the specified address space and offset.
Corresponds to viMoveOut64* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
converted_buffer = (ViUInt64 * length)(*tuple(data))
if extended:
return library.viMoveOut64Ex(session, space, offset, length, converted_buffer)
else:
return library.viMoveOut64(session, space, offset, length, converted_buffer)
|
Moves an 32-bit block of data from local memory to the specified address space and offset.
Corresponds to viMoveOut32* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def move_out_32(library, session, space, offset, length, data, extended=False):
"""Moves an 32-bit block of data from local memory to the specified address space and offset.
Corresponds to viMoveOut32* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
converted_buffer = (ViUInt32 * length)(*tuple(data))
if extended:
return library.viMoveOut32Ex(session, space, offset, length, converted_buffer)
else:
return library.viMoveOut32(session, space, offset, length, converted_buffer)
|
Opens a session to the specified resource.
Corresponds to viOpen function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Resource Manager session (should always be a session returned from open_default_resource_manager()).
:param resource_name: Unique symbolic name of a resource.
:param access_mode: Specifies the mode by which the resource is to be accessed. (constants.AccessModes)
:param open_timeout: Specifies the maximum time period (in milliseconds) that this operation waits
before returning an error.
:return: Unique logical identifier reference to a session, return value of the library call.
:rtype: session, :class:`pyvisa.constants.StatusCode`
|
def open(library, session, resource_name,
access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE):
"""Opens a session to the specified resource.
Corresponds to viOpen function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Resource Manager session (should always be a session returned from open_default_resource_manager()).
:param resource_name: Unique symbolic name of a resource.
:param access_mode: Specifies the mode by which the resource is to be accessed. (constants.AccessModes)
:param open_timeout: Specifies the maximum time period (in milliseconds) that this operation waits
before returning an error.
:return: Unique logical identifier reference to a session, return value of the library call.
:rtype: session, :class:`pyvisa.constants.StatusCode`
"""
try:
open_timeout = int(open_timeout)
except ValueError:
raise ValueError('open_timeout (%r) must be an integer (or compatible type)' % open_timeout)
out_session = ViSession()
# [ViSession, ViRsrc, ViAccessMode, ViUInt32, ViPSession]
# ViRsrc converts from (str, unicode, bytes) to bytes
ret = library.viOpen(session, resource_name, access_mode, open_timeout, byref(out_session))
return out_session.value, ret
|
This function returns a session to the Default Resource Manager resource.
Corresponds to viOpenDefaultRM function of the VISA library.
:param library: the visa library wrapped by ctypes.
:return: Unique logical identifier to a Default Resource Manager session, return value of the library call.
:rtype: session, :class:`pyvisa.constants.StatusCode`
|
def open_default_resource_manager(library):
"""This function returns a session to the Default Resource Manager resource.
Corresponds to viOpenDefaultRM function of the VISA library.
:param library: the visa library wrapped by ctypes.
:return: Unique logical identifier to a Default Resource Manager session, return value of the library call.
:rtype: session, :class:`pyvisa.constants.StatusCode`
"""
session = ViSession()
ret = library.viOpenDefaultRM(byref(session))
return session.value, ret
|
Write in an 8-bit, 16-bit, 32-bit, value to the specified memory space and offset.
Corresponds to viOut* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param data: Data to write to bus.
:param width: Number of bits to read.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def write_memory(library, session, space, offset, data, width, extended=False):
"""Write in an 8-bit, 16-bit, 32-bit, value to the specified memory space and offset.
Corresponds to viOut* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param data: Data to write to bus.
:param width: Number of bits to read.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
if width == 8:
return out_8(library, session, space, offset, data, extended)
elif width == 16:
return out_16(library, session, space, offset, data, extended)
elif width == 32:
return out_32(library, session, space, offset, data, extended)
raise ValueError('%s is not a valid size. Valid values are 8, 16 or 32' % width)
|
Write in an 8-bit value from the specified memory space and offset.
Corresponds to viOut8* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def out_8(library, session, space, offset, data, extended=False):
"""Write in an 8-bit value from the specified memory space and offset.
Corresponds to viOut8* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
if extended:
return library.viOut8Ex(session, space, offset, data)
else:
return library.viOut8(session, space, offset, data)
|
Write in an 16-bit value from the specified memory space and offset.
Corresponds to viOut16* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def out_16(library, session, space, offset, data, extended=False):
"""Write in an 16-bit value from the specified memory space and offset.
Corresponds to viOut16* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
if extended:
return library.viOut16Ex(session, space, offset, data, extended=False)
else:
return library.viOut16(session, space, offset, data, extended=False)
|
Write in an 32-bit value from the specified memory space and offset.
Corresponds to viOut32* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def out_32(library, session, space, offset, data, extended=False):
"""Write in an 32-bit value from the specified memory space and offset.
Corresponds to viOut32* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
if extended:
return library.viOut32Ex(session, space, offset, data)
else:
return library.viOut32(session, space, offset, data)
|
Write in an 64-bit value from the specified memory space and offset.
Corresponds to viOut64* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def out_64(library, session, space, offset, data, extended=False):
"""Write in an 64-bit value from the specified memory space and offset.
Corresponds to viOut64* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param data: Data to write to bus.
:param extended: Use 64 bits offset independent of the platform.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
if extended:
return library.viOut64Ex(session, space, offset, data)
else:
return library.viOut64(session, space, offset, data)
|
Parse a resource string to get the interface information.
Corresponds to viParseRsrc function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Resource Manager session (should always be the Default Resource Manager for VISA
returned from open_default_resource_manager()).
:param resource_name: Unique symbolic name of a resource.
:return: Resource information with interface type and board number, return value of the library call.
:rtype: :class:`pyvisa.highlevel.ResourceInfo`, :class:`pyvisa.constants.StatusCode`
|
def parse_resource(library, session, resource_name):
"""Parse a resource string to get the interface information.
Corresponds to viParseRsrc function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Resource Manager session (should always be the Default Resource Manager for VISA
returned from open_default_resource_manager()).
:param resource_name: Unique symbolic name of a resource.
:return: Resource information with interface type and board number, return value of the library call.
:rtype: :class:`pyvisa.highlevel.ResourceInfo`, :class:`pyvisa.constants.StatusCode`
"""
interface_type = ViUInt16()
interface_board_number = ViUInt16()
# [ViSession, ViRsrc, ViPUInt16, ViPUInt16]
# ViRsrc converts from (str, unicode, bytes) to bytes
ret = library.viParseRsrc(session, resource_name, byref(interface_type),
byref(interface_board_number))
return ResourceInfo(constants.InterfaceType(interface_type.value),
interface_board_number.value,
None, None, None), ret
|
Parse a resource string to get extended interface information.
Corresponds to viParseRsrcEx function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Resource Manager session (should always be the Default Resource Manager for VISA
returned from open_default_resource_manager()).
:param resource_name: Unique symbolic name of a resource.
:return: Resource information, return value of the library call.
:rtype: :class:`pyvisa.highlevel.ResourceInfo`, :class:`pyvisa.constants.StatusCode`
|
def parse_resource_extended(library, session, resource_name):
"""Parse a resource string to get extended interface information.
Corresponds to viParseRsrcEx function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Resource Manager session (should always be the Default Resource Manager for VISA
returned from open_default_resource_manager()).
:param resource_name: Unique symbolic name of a resource.
:return: Resource information, return value of the library call.
:rtype: :class:`pyvisa.highlevel.ResourceInfo`, :class:`pyvisa.constants.StatusCode`
"""
interface_type = ViUInt16()
interface_board_number = ViUInt16()
resource_class = create_string_buffer(constants.VI_FIND_BUFLEN)
unaliased_expanded_resource_name = create_string_buffer(constants.VI_FIND_BUFLEN)
alias_if_exists = create_string_buffer(constants.VI_FIND_BUFLEN)
# [ViSession, ViRsrc, ViPUInt16, ViPUInt16, ViAChar, ViAChar, ViAChar]
# ViRsrc converts from (str, unicode, bytes) to bytes
ret = library.viParseRsrcEx(session, resource_name, byref(interface_type),
byref(interface_board_number), resource_class,
unaliased_expanded_resource_name,
alias_if_exists)
res = [buffer_to_text(val)
for val in (resource_class,
unaliased_expanded_resource_name,
alias_if_exists)]
if res[-1] == '':
res[-1] = None
return ResourceInfo(constants.InterfaceType(interface_type.value),
interface_board_number.value, *res), ret
|
Read an 8, 16 or 32-bit value from the specified address.
Corresponds to viPeek* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param width: Number of bits to read.
:return: Data read from bus, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
|
def peek(library, session, address, width):
"""Read an 8, 16 or 32-bit value from the specified address.
Corresponds to viPeek* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param width: Number of bits to read.
:return: Data read from bus, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
"""
if width == 8:
return peek_8(library, session, address)
elif width == 16:
return peek_16(library, session, address)
elif width == 32:
return peek_32(library, session, address)
elif width == 64:
return peek_64(library, session, address)
raise ValueError('%s is not a valid size. Valid values are 8, 16, 32 or 64' % width)
|
Read an 8-bit value from the specified address.
Corresponds to viPeek8 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:return: Data read from bus, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
|
def peek_8(library, session, address):
"""Read an 8-bit value from the specified address.
Corresponds to viPeek8 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:return: Data read from bus, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
"""
value_8 = ViUInt8()
ret = library.viPeek8(session, address, byref(value_8))
return value_8.value, ret
|
Read an 16-bit value from the specified address.
Corresponds to viPeek16 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:return: Data read from bus, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
|
def peek_16(library, session, address):
"""Read an 16-bit value from the specified address.
Corresponds to viPeek16 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:return: Data read from bus, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
"""
value_16 = ViUInt16()
ret = library.viPeek16(session, address, byref(value_16))
return value_16.value, ret
|
Read an 32-bit value from the specified address.
Corresponds to viPeek32 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:return: Data read from bus, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
|
def peek_32(library, session, address):
"""Read an 32-bit value from the specified address.
Corresponds to viPeek32 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:return: Data read from bus, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
"""
value_32 = ViUInt32()
ret = library.viPeek32(session, address, byref(value_32))
return value_32.value, ret
|
Read an 64-bit value from the specified address.
Corresponds to viPeek64 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:return: Data read from bus, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
|
def peek_64(library, session, address):
"""Read an 64-bit value from the specified address.
Corresponds to viPeek64 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:return: Data read from bus, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
"""
value_64 = ViUInt64()
ret = library.viPeek64(session, address, byref(value_64))
return value_64.value, ret
|
Writes an 8, 16 or 32-bit value from the specified address.
Corresponds to viPoke* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param width: Number of bits to read.
:param data: Data to be written to the bus.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def poke(library, session, address, width, data):
"""Writes an 8, 16 or 32-bit value from the specified address.
Corresponds to viPoke* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param width: Number of bits to read.
:param data: Data to be written to the bus.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
if width == 8:
return poke_8(library, session, address, data)
elif width == 16:
return poke_16(library, session, address, data)
elif width == 32:
return poke_32(library, session, address, data)
raise ValueError('%s is not a valid size. Valid values are 8, 16 or 32' % width)
|
Write an 8-bit value from the specified address.
Corresponds to viPoke8 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param data: value to be written to the bus.
:return: Data read from bus.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def poke_8(library, session, address, data):
"""Write an 8-bit value from the specified address.
Corresponds to viPoke8 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param data: value to be written to the bus.
:return: Data read from bus.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viPoke8(session, address, data)
|
Write an 16-bit value from the specified address.
Corresponds to viPoke16 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param data: value to be written to the bus.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def poke_16(library, session, address, data):
"""Write an 16-bit value from the specified address.
Corresponds to viPoke16 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param data: value to be written to the bus.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viPoke16(session, address, data)
|
Write an 32-bit value from the specified address.
Corresponds to viPoke32 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param data: value to be written to the bus.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def poke_32(library, session, address, data):
"""Write an 32-bit value from the specified address.
Corresponds to viPoke32 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param data: value to be written to the bus.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viPoke32(session, address, data)
|
Write an 64-bit value from the specified address.
Corresponds to viPoke64 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param data: value to be written to the bus.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def poke_64(library, session, address, data):
"""Write an 64-bit value from the specified address.
Corresponds to viPoke64 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param data: value to be written to the bus.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viPoke64(session, address, data)
|
Reads data from device or interface synchronously.
Corresponds to viRead function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param count: Number of bytes to be read.
:return: data read, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
|
def read(library, session, count):
"""Reads data from device or interface synchronously.
Corresponds to viRead function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param count: Number of bytes to be read.
:return: data read, return value of the library call.
:rtype: bytes, :class:`pyvisa.constants.StatusCode`
"""
buffer = create_string_buffer(count)
return_count = ViUInt32()
ret = library.viRead(session, buffer, count, byref(return_count))
return buffer.raw[:return_count.value], ret
|
Reads data from device or interface asynchronously.
Corresponds to viReadAsync function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param count: Number of bytes to be read.
:return: result, jobid, return value of the library call.
:rtype: ctypes buffer, jobid, :class:`pyvisa.constants.StatusCode`
|
def read_asynchronously(library, session, count):
"""Reads data from device or interface asynchronously.
Corresponds to viReadAsync function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param count: Number of bytes to be read.
:return: result, jobid, return value of the library call.
:rtype: ctypes buffer, jobid, :class:`pyvisa.constants.StatusCode`
"""
buffer = create_string_buffer(count)
job_id = ViJobId()
ret = library.viReadAsync(session, buffer, count, byref(job_id))
return buffer, job_id, ret
|
Reads a status byte of the service request.
Corresponds to viReadSTB function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:return: Service request status byte, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
|
def read_stb(library, session):
"""Reads a status byte of the service request.
Corresponds to viReadSTB function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:return: Service request status byte, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
status = ViUInt16()
ret = library.viReadSTB(session, byref(status))
return status.value, ret
|
Read data synchronously, and store the transferred data in a file.
Corresponds to viReadToFile function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param filename: Name of file to which data will be written.
:param count: Number of bytes to be read.
:return: Number of bytes actually transferred, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
|
def read_to_file(library, session, filename, count):
"""Read data synchronously, and store the transferred data in a file.
Corresponds to viReadToFile function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param filename: Name of file to which data will be written.
:param count: Number of bytes to be read.
:return: Number of bytes actually transferred, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
return_count = ViUInt32()
ret = library.viReadToFile(session, filename, count, return_count)
return return_count, ret
|
Sets the state of an attribute.
Corresponds to viSetAttribute function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param attribute: Attribute for which the state is to be modified. (Attributes.*)
:param attribute_state: The state of the attribute to be set for the specified object.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def set_attribute(library, session, attribute, attribute_state):
"""Sets the state of an attribute.
Corresponds to viSetAttribute function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param attribute: Attribute for which the state is to be modified. (Attributes.*)
:param attribute_state: The state of the attribute to be set for the specified object.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viSetAttribute(session, attribute, attribute_state)
|
Sets the size for the formatted I/O and/or low-level I/O communication buffer(s).
Corresponds to viSetBuf function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param mask: Specifies the type of buffer. (Constants.READ_BUF, .WRITE_BUF, .IO_IN_BUF, .IO_OUT_BUF)
:param size: The size to be set for the specified buffer(s).
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def set_buffer(library, session, mask, size):
"""Sets the size for the formatted I/O and/or low-level I/O communication buffer(s).
Corresponds to viSetBuf function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param mask: Specifies the type of buffer. (Constants.READ_BUF, .WRITE_BUF, .IO_IN_BUF, .IO_OUT_BUF)
:param size: The size to be set for the specified buffer(s).
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viSetBuf(session, mask, size)
|
Returns a user-readable description of the status code passed to the operation.
Corresponds to viStatusDesc function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param status: Status code to interpret.
:return: - The user-readable string interpretation of the status code passed to the operation,
- return value of the library call.
:rtype: - unicode (Py2) or str (Py3)
- :class:`pyvisa.constants.StatusCode`
|
def status_description(library, session, status):
"""Returns a user-readable description of the status code passed to the operation.
Corresponds to viStatusDesc function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param status: Status code to interpret.
:return: - The user-readable string interpretation of the status code passed to the operation,
- return value of the library call.
:rtype: - unicode (Py2) or str (Py3)
- :class:`pyvisa.constants.StatusCode`
"""
description = create_string_buffer(256)
ret = library.viStatusDesc(session, status, description)
return buffer_to_text(description), ret
|
Requests a VISA session to terminate normal execution of an operation.
Corresponds to viTerminate function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param degree: Constants.NULL
:param job_id: Specifies an operation identifier.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def terminate(library, session, degree, job_id):
"""Requests a VISA session to terminate normal execution of an operation.
Corresponds to viTerminate function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param degree: Constants.NULL
:param job_id: Specifies an operation identifier.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viTerminate(session, degree, job_id)
|
Uninstalls handlers for events.
Corresponds to viUninstallHandler function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application.
:param user_handle: The user_handle (a ctypes object) in the returned value from install_handler.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def uninstall_handler(library, session, event_type, handler, user_handle=None):
"""Uninstalls handlers for events.
Corresponds to viUninstallHandler function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application.
:param user_handle: The user_handle (a ctypes object) in the returned value from install_handler.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
set_user_handle_type(library, user_handle)
if user_handle != None:
user_handle = byref(user_handle)
return library.viUninstallHandler(session, event_type, handler, user_handle)
|
Undo a previous map from the specified trigger source line to the specified destination line.
Corresponds to viUnmapTrigger function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param trigger_source: Source line used in previous map. (Constants.TRIG*)
:param trigger_destination: Destination line used in previous map. (Constants.TRIG*)
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def unmap_trigger(library, session, trigger_source, trigger_destination):
"""Undo a previous map from the specified trigger source line to the specified destination line.
Corresponds to viUnmapTrigger function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param trigger_source: Source line used in previous map. (Constants.TRIG*)
:param trigger_destination: Destination line used in previous map. (Constants.TRIG*)
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viUnmapTrigger(session, trigger_source, trigger_destination)
|
Performs a USB control pipe transfer from the device.
Corresponds to viUsbControlIn function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer.
:param request_id: bRequest parameter of the setup stage of a USB control transfer.
:param request_value: wValue parameter of the setup stage of a USB control transfer.
:param index: wIndex parameter of the setup stage of a USB control transfer.
This is usually the index of the interface or endpoint.
:param length: wLength parameter of the setup stage of a USB control transfer.
This value also specifies the size of the data buffer to receive the data from the
optional data stage of the control transfer.
:return: - The data buffer that receives the data from the optional data stage of the control transfer
- return value of the library call.
:rtype: - bytes
- :class:`pyvisa.constants.StatusCode`
|
def usb_control_in(library, session, request_type_bitmap_field, request_id, request_value,
index, length=0):
"""Performs a USB control pipe transfer from the device.
Corresponds to viUsbControlIn function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer.
:param request_id: bRequest parameter of the setup stage of a USB control transfer.
:param request_value: wValue parameter of the setup stage of a USB control transfer.
:param index: wIndex parameter of the setup stage of a USB control transfer.
This is usually the index of the interface or endpoint.
:param length: wLength parameter of the setup stage of a USB control transfer.
This value also specifies the size of the data buffer to receive the data from the
optional data stage of the control transfer.
:return: - The data buffer that receives the data from the optional data stage of the control transfer
- return value of the library call.
:rtype: - bytes
- :class:`pyvisa.constants.StatusCode`
"""
buffer = create_string_buffer(length)
return_count = ViUInt16()
ret = library.viUsbControlIn(session, request_type_bitmap_field, request_id,
request_value, index, length, buffer,
byref(return_count))
return buffer.raw[:return_count.value], ret
|
Performs a USB control pipe transfer to the device.
Corresponds to viUsbControlOut function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer.
:param request_id: bRequest parameter of the setup stage of a USB control transfer.
:param request_value: wValue parameter of the setup stage of a USB control transfer.
:param index: wIndex parameter of the setup stage of a USB control transfer.
This is usually the index of the interface or endpoint.
:param data: The data buffer that sends the data in the optional data stage of the control transfer.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def usb_control_out(library, session, request_type_bitmap_field, request_id, request_value,
index, data=""):
"""Performs a USB control pipe transfer to the device.
Corresponds to viUsbControlOut function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer.
:param request_id: bRequest parameter of the setup stage of a USB control transfer.
:param request_value: wValue parameter of the setup stage of a USB control transfer.
:param index: wIndex parameter of the setup stage of a USB control transfer.
This is usually the index of the interface or endpoint.
:param data: The data buffer that sends the data in the optional data stage of the control transfer.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
length = len(data)
return library.viUsbControlOut(session, request_type_bitmap_field, request_id,
request_value, index, length, data)
|
Sends the device a miscellaneous command or query and/or retrieves the response to a previous query.
Corresponds to viVxiCommandQuery function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param mode: Specifies whether to issue a command and/or retrieve a response. (Constants.VXI_CMD*, .VXI_RESP*)
:param command: The miscellaneous command to send.
:return: The response retrieved from the device, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
|
def vxi_command_query(library, session, mode, command):
"""Sends the device a miscellaneous command or query and/or retrieves the response to a previous query.
Corresponds to viVxiCommandQuery function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param mode: Specifies whether to issue a command and/or retrieve a response. (Constants.VXI_CMD*, .VXI_RESP*)
:param command: The miscellaneous command to send.
:return: The response retrieved from the device, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
response = ViUInt32()
ret = library.viVxiCommandQuery(session, mode, command, byref(response))
return response.value, ret
|
Waits for an occurrence of the specified event for a given session.
Corresponds to viWaitOnEvent function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param in_event_type: Logical identifier of the event(s) to wait for.
:param timeout: Absolute time period in time units that the resource shall wait for a specified event to
occur before returning the time elapsed error. The time unit is in milliseconds.
:return: - Logical identifier of the event actually received
- A handle specifying the unique occurrence of an event
- return value of the library call.
:rtype: - eventtype
- event
- :class:`pyvisa.constants.StatusCode`
|
def wait_on_event(library, session, in_event_type, timeout):
"""Waits for an occurrence of the specified event for a given session.
Corresponds to viWaitOnEvent function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param in_event_type: Logical identifier of the event(s) to wait for.
:param timeout: Absolute time period in time units that the resource shall wait for a specified event to
occur before returning the time elapsed error. The time unit is in milliseconds.
:return: - Logical identifier of the event actually received
- A handle specifying the unique occurrence of an event
- return value of the library call.
:rtype: - eventtype
- event
- :class:`pyvisa.constants.StatusCode`
"""
out_event_type = ViEventType()
out_context = ViEvent()
ret = library.viWaitOnEvent(session, in_event_type, timeout,
byref(out_event_type), byref(out_context))
return out_event_type.value, out_context, ret
|
Writes data to device or interface synchronously.
Corresponds to viWrite function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param data: data to be written.
:type data: str
:return: Number of bytes actually transferred, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
|
def write(library, session, data):
"""Writes data to device or interface synchronously.
Corresponds to viWrite function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param data: data to be written.
:type data: str
:return: Number of bytes actually transferred, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
return_count = ViUInt32()
# [ViSession, ViBuf, ViUInt32, ViPUInt32]
ret = library.viWrite(session, data, len(data), byref(return_count))
return return_count.value, ret
|
Writes data to device or interface asynchronously.
Corresponds to viWriteAsync function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param data: data to be written.
:return: Job ID of this asynchronous write operation, return value of the library call.
:rtype: jobid, :class:`pyvisa.constants.StatusCode`
|
def write_asynchronously(library, session, data):
"""Writes data to device or interface asynchronously.
Corresponds to viWriteAsync function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param data: data to be written.
:return: Job ID of this asynchronous write operation, return value of the library call.
:rtype: jobid, :class:`pyvisa.constants.StatusCode`
"""
job_id = ViJobId()
# [ViSession, ViBuf, ViUInt32, ViPJobId]
ret = library.viWriteAsync(session, data, len(data), byref(job_id))
return job_id, ret
|
Take data from a file and write it out synchronously.
Corresponds to viWriteFromFile function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param filename: Name of file from which data will be read.
:param count: Number of bytes to be written.
:return: Number of bytes actually transferred, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
|
def write_from_file(library, session, filename, count):
"""Take data from a file and write it out synchronously.
Corresponds to viWriteFromFile function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param filename: Name of file from which data will be read.
:param count: Number of bytes to be written.
:return: Number of bytes actually transferred, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
return_count = ViUInt32()
ret = library.viWriteFromFile(session, filename, count, return_count)
return return_count, ret
|
Reads in an 8-bit, 16-bit, 32-bit, or 64-bit value from the specified memory space and offset.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param width: Number of bits to read.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from memory.
Corresponds to viIn* functions of the visa library.
|
def read_memory(self, space, offset, width, extended=False):
"""Reads in an 8-bit, 16-bit, 32-bit, or 64-bit value from the specified memory space and offset.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param width: Number of bits to read.
:param extended: Use 64 bits offset independent of the platform.
:return: Data read from memory.
Corresponds to viIn* functions of the visa library.
"""
return self.visalib.read_memory(self.session, space, offset, width, extended)
|
Write in an 8-bit, 16-bit, 32-bit, value to the specified memory space and offset.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param data: Data to write to bus.
:param width: Number of bits to read.
:param extended: Use 64 bits offset independent of the platform.
Corresponds to viOut* functions of the visa library.
|
def write_memory(self, space, offset, data, width, extended=False):
"""Write in an 8-bit, 16-bit, 32-bit, value to the specified memory space and offset.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param data: Data to write to bus.
:param width: Number of bits to read.
:param extended: Use 64 bits offset independent of the platform.
Corresponds to viOut* functions of the visa library.
"""
return self.visalib.write_memory(self.session, space, offset, data, width, extended)
|
Moves a block of data to local memory from the specified address space and offset.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param width: Number of bits to read per element.
:param extended: Use 64 bits offset independent of the platform.
|
def move_in(self, space, offset, length, width, extended=False):
"""Moves a block of data to local memory from the specified address space and offset.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param width: Number of bits to read per element.
:param extended: Use 64 bits offset independent of the platform.
"""
return self.visalib.move_in(self.session, space, offset, length, width, extended)
|
Moves a block of data from local memory to the specified address space and offset.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param data: Data to write to bus.
:param width: Number of bits to read per element.
:param extended: Use 64 bits offset independent of the platform.
|
def move_out(self, space, offset, length, data, width, extended=False):
"""Moves a block of data from local memory to the specified address space and offset.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to read.
:param length: Number of elements to transfer, where the data width of the elements to transfer
is identical to the source data width.
:param data: Data to write to bus.
:param width: Number of bits to read per element.
:param extended: Use 64 bits offset independent of the platform.
"""
return self.visalib.move_out(space, offset, length, data, width, extended)
|
Returns True if the attribute is part of a given session type.
The session_type is a tuple with the interface type and resource_class
:type session_type: (constants.InterfaceType, str)
:rtype: bool
|
def in_resource(cls, session_type):
"""Returns True if the attribute is part of a given session type.
The session_type is a tuple with the interface type and resource_class
:type session_type: (constants.InterfaceType, str)
:rtype: bool
"""
if cls.resources is AllSessionTypes:
return True
return session_type in cls.resources
|
List all connected resources.
|
def do_list(self, args):
"""List all connected resources."""
try:
resources = self.resource_manager.list_resources_info()
except Exception as e:
print(e)
else:
self.resources = []
for ndx, (resource_name, value) in enumerate(resources.items()):
if not args:
print('({0:2d}) {1}'.format(ndx, resource_name))
if value.alias:
print(' alias: {}'.format(value.alias))
self.resources.append((resource_name, value.alias or None))
|
Open resource by number, resource name or alias: open 3
|
def do_open(self, args):
"""Open resource by number, resource name or alias: open 3"""
if not args:
print('A resource name must be specified.')
return
if self.current:
print('You can only open one resource at a time. Please close the current one first.')
return
if args.isdigit():
try:
args = self.resources[int(args)][0]
except IndexError:
print('Not a valid resource number. Use the command "list".')
return
try:
self.current = self.resource_manager.open_resource(args)
print('{} has been opened.\n'
'You can talk to the device using "write", "read" or "query".\n'
'The default end of message is added to each message.'.format(args))
self.py_attr = []
self.vi_attr = []
for attr in getattr(self.current, 'visa_attributes_classes', ()):
if attr.py_name:
self.py_attr.append(attr.py_name)
self.vi_attr.append(attr.visa_name)
self.prompt = '(open) '
except Exception as e:
print(e)
|
Close resource in use.
|
def do_close(self, args):
"""Close resource in use."""
if not self.current:
print('There are no resources in use. Use the command "open".')
return
try:
self.current.close()
except Exception as e:
print(e)
else:
print('The resource has been closed.')
self.current = None
self.prompt = self.default_prompt
|
Query resource in use: query *IDN?
|
def do_query(self, args):
"""Query resource in use: query *IDN? """
if not self.current:
print('There are no resources in use. Use the command "open".')
return
try:
print('Response: {}'.format(self.current.query(args)))
except Exception as e:
print(e)
|
Receive from the resource in use.
|
def do_read(self, args):
"""Receive from the resource in use."""
if not self.current:
print('There are no resources in use. Use the command "open".')
return
try:
print(self.current.read())
except Exception as e:
print(e)
|
Send to the resource in use: send *IDN?
|
def do_write(self, args):
"""Send to the resource in use: send *IDN? """
if not self.current:
print('There are no resources in use. Use the command "open".')
return
try:
self.current.write(args)
except Exception as e:
print(e)
|
Get or set timeout (in ms) for resource in use.
Get timeout:
timeout
Set timeout:
timeout <mstimeout>
|
def do_timeout(self, args):
"""Get or set timeout (in ms) for resource in use.
Get timeout:
timeout
Set timeout:
timeout <mstimeout>
"""
if not self.current:
print('There are no resources in use. Use the command "open".')
return
args = args.strip()
if not args:
try:
print('Timeout: {}ms'.format(self.current.timeout))
except Exception as e:
print(e)
else:
args = args.split(' ')
try:
self.current.timeout = float(args[0])
print('Done')
except Exception as e:
print(e)
|
Get or set the state for a visa attribute.
List all attributes:
attr
Get an attribute state:
attr <name>
Set an attribute state:
attr <name> <state>
|
def do_attr(self, args):
"""Get or set the state for a visa attribute.
List all attributes:
attr
Get an attribute state:
attr <name>
Set an attribute state:
attr <name> <state>
"""
if not self.current:
print('There are no resources in use. Use the command "open".')
return
args = args.strip()
if not args:
self.print_attribute_list()
return
args = args.split(' ')
if len(args) > 2:
print('Invalid syntax, use `attr <name>` to get; or `attr <name> <value>` to set')
elif len(args) == 1:
# Get
attr_name = args[0]
if attr_name.startswith('VI_'):
try:
print(self.current.get_visa_attribute(getattr(constants, attr_name)))
except Exception as e:
print(e)
else:
try:
print(getattr(self.current, attr_name))
except Exception as e:
print(e)
else:
attr_name, attr_state = args[0], args[1]
if attr_name.startswith('VI_'):
try:
attributeId = getattr(constants, attr_name)
attr = attributes.AttributesByID[attributeId]
datatype = attr.visa_type
retcode = None
if datatype == 'ViBoolean':
if attr_state == 'True':
attr_state = True
elif attr_state == 'False':
attr_state = False
else:
retcode = constants.StatusCode.error_nonsupported_attribute_state
elif datatype in ['ViUInt8', 'ViUInt16', 'ViUInt32', 'ViInt8', 'ViInt16', 'ViInt32']:
try:
attr_state = int(attr_state)
except ValueError:
retcode = constants.StatusCode.error_nonsupported_attribute_state
if not retcode:
retcode = self.current.set_visa_attribute(attributeId, attr_state)
if retcode:
print('Error {}'.format(str(retcode)))
else:
print('Done')
except Exception as e:
print(e)
else:
print('Setting Resource Attributes by python name is not yet supported.')
return
try:
print(getattr(self.current, attr_name))
print('Done')
except Exception as e:
print(e)
|
Get or set termination character for resource in use.
<termchar> can be one of: CR, LF, CRLF, NUL or None.
None is used to disable termination character
Get termination character:
termchar
Set termination character read or read+write:
termchar <termchar> [<termchar>]
|
def do_termchar(self, args):
"""Get or set termination character for resource in use.
<termchar> can be one of: CR, LF, CRLF, NUL or None.
None is used to disable termination character
Get termination character:
termchar
Set termination character read or read+write:
termchar <termchar> [<termchar>]
"""
if not self.current:
print('There are no resources in use. Use the command "open".')
return
args = args.strip()
if not args:
try:
charmap = { u'\r': 'CR', u'\n': 'LF', u'\r\n': 'CRLF', u'\0': 'NUL' }
chr = self.current.read_termination
if chr in charmap:
chr = charmap[chr]
chw = self.current.write_termination
if chw in charmap:
chw = charmap[chw]
print('Termchar read: {} write: {}'.format(chr, chw))
except Exception as e:
print(e)
else:
args = args.split(' ')
charmap = { 'CR': u'\r', 'LF': u'\n', 'CRLF': u'\r\n', 'NUL': u'\0', 'None': None }
chr = args[0]
chw = args[0 if len(args) == 1 else 1]
if chr in charmap and chw in charmap:
try:
self.current.read_termination = charmap[chr]
self.current.write_termination = charmap[chw]
print('Done')
except Exception as e:
print(e)
else:
print('use CR, LF, CRLF, NUL or None to set termchar')
return
|
Exit the shell session.
|
def do_exit(self, arg):
"""Exit the shell session."""
if self.current:
self.current.close()
self.resource_manager.close()
del self.resource_manager
return True
|
The timeout in milliseconds for all resource I/O operations.
Special values:
- **immediate** (``VI_TMO_IMMEDIATE``): 0
(for convenience, any value smaller than 1 is considered as 0)
- **infinite** (``VI_TMO_INFINITE``): ``float('+inf')``
(for convenience, None is considered as ``float('+inf')``)
To set an **infinite** timeout, you can also use:
>>> del instrument.timeout
|
def timeout(self):
"""The timeout in milliseconds for all resource I/O operations.
Special values:
- **immediate** (``VI_TMO_IMMEDIATE``): 0
(for convenience, any value smaller than 1 is considered as 0)
- **infinite** (``VI_TMO_INFINITE``): ``float('+inf')``
(for convenience, None is considered as ``float('+inf')``)
To set an **infinite** timeout, you can also use:
>>> del instrument.timeout
"""
timeout = self.get_visa_attribute(constants.VI_ATTR_TMO_VALUE)
if timeout == constants.VI_TMO_INFINITE:
return float('+inf')
return timeout
|
Get the extended information of this resource.
:param resource_name: Unique symbolic name of a resource.
:rtype: :class:`pyvisa.highlevel.ResourceInfo`
|
def resource_info(self):
"""Get the extended information of this resource.
:param resource_name: Unique symbolic name of a resource.
:rtype: :class:`pyvisa.highlevel.ResourceInfo`
"""
return self.visalib.parse_resource_extended(self._resource_manager.session, self.resource_name)
|
The interface type of the resource as a number.
|
def interface_type(self):
"""The interface type of the resource as a number.
"""
return self.visalib.parse_resource(self._resource_manager.session,
self.resource_name)[0].interface_type
|
Opens a session to the specified resource.
:param access_mode: Specifies the mode by which the resource is to be accessed.
:type access_mode: :class:`pyvisa.constants.AccessModes`
:param open_timeout: Milliseconds before the open operation times out.
:type open_timeout: int
|
def open(self, access_mode=constants.AccessModes.no_lock, open_timeout=5000):
"""Opens a session to the specified resource.
:param access_mode: Specifies the mode by which the resource is to be accessed.
:type access_mode: :class:`pyvisa.constants.AccessModes`
:param open_timeout: Milliseconds before the open operation times out.
:type open_timeout: int
"""
logger.debug('%s - opening ...', self._resource_name, extra=self._logging_extra)
with self._resource_manager.ignore_warning(constants.VI_SUCCESS_DEV_NPRESENT):
self.session, status = self._resource_manager.open_bare_resource(self._resource_name, access_mode, open_timeout)
if status == constants.VI_SUCCESS_DEV_NPRESENT:
# The device was not ready when we opened the session.
# Now it gets five seconds more to become ready.
# Every 0.1 seconds we probe it with viClear.
start_time = time.time()
sleep_time = 0.1
try_time = 5
while time.time() - start_time < try_time:
time.sleep(sleep_time)
try:
self.clear()
break
except errors.VisaIOError as error:
if error.error_code != constants.VI_ERROR_NLISTENERS:
raise
self._logging_extra['session'] = self.session
logger.debug('%s - is open with session %s',
self._resource_name, self.session,
extra=self._logging_extra)
|
Closes the VISA session and marks the handle as invalid.
|
def close(self):
"""Closes the VISA session and marks the handle as invalid.
"""
try:
logger.debug('%s - closing', self._resource_name,
extra=self._logging_extra)
self.before_close()
self.visalib.close(self.session)
logger.debug('%s - is closed', self._resource_name,
extra=self._logging_extra)
self.session = None
except errors.InvalidSession:
pass
|
Sets the state of an attribute.
:param name: Attribute for which the state is to be modified. (Attributes.*)
:param state: The state of the attribute to be set for the specified object.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
|
def set_visa_attribute(self, name, state):
"""Sets the state of an attribute.
:param name: Attribute for which the state is to be modified. (Attributes.*)
:param state: The state of the attribute to be set for the specified object.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return self.visalib.set_attribute(self.session, name, state)
|
Installs handlers for event callbacks in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be installed by a client application.
:param user_handle: A value specified by an application that can be used for identifying handlers
uniquely for an event type.
:returns: user handle (a ctypes object)
|
def install_handler(self, event_type, handler, user_handle=None):
"""Installs handlers for event callbacks in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be installed by a client application.
:param user_handle: A value specified by an application that can be used for identifying handlers
uniquely for an event type.
:returns: user handle (a ctypes object)
"""
return self.visalib.install_visa_handler(self.session, event_type, handler, user_handle)
|
Uninstalls handlers for events in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application.
:param user_handle: The user handle (ctypes object or None) returned by install_handler.
|
def uninstall_handler(self, event_type, handler, user_handle=None):
"""Uninstalls handlers for events in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application.
:param user_handle: The user handle (ctypes object or None) returned by install_handler.
"""
self.visalib.uninstall_visa_handler(self.session, event_type, handler, user_handle)
|
Disables notification of the specified event type(s) via the specified mechanism(s).
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be disabled.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR, .VI_ALL_MECH)
|
def disable_event(self, event_type, mechanism):
"""Disables notification of the specified event type(s) via the specified mechanism(s).
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be disabled.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR, .VI_ALL_MECH)
"""
self.visalib.disable_event(self.session, event_type, mechanism)
|
Discards event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be dicarded.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR, .VI_ALL_MECH)
|
def discard_events(self, event_type, mechanism):
"""Discards event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be dicarded.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR, .VI_ALL_MECH)
"""
self.visalib.discard_events(self.session, event_type, mechanism)
|
Enable event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be enabled.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR)
:param context: Not currently used, leave as None.
|
def enable_event(self, event_type, mechanism, context=None):
"""Enable event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be enabled.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR)
:param context: Not currently used, leave as None.
"""
self.visalib.enable_event(self.session, event_type, mechanism, context)
|
Waits for an occurrence of the specified event in this resource.
:param in_event_type: Logical identifier of the event(s) to wait for.
:param timeout: Absolute time period in time units that the resource shall wait for a specified event to
occur before returning the time elapsed error. The time unit is in milliseconds.
None means waiting forever if necessary.
:param capture_timeout: When True will not produce a VisaIOError(VI_ERROR_TMO) but
instead return a WaitResponse with timed_out=True
:return: A WaitResponse object that contains event_type, context and ret value.
|
def wait_on_event(self, in_event_type, timeout, capture_timeout=False):
"""Waits for an occurrence of the specified event in this resource.
:param in_event_type: Logical identifier of the event(s) to wait for.
:param timeout: Absolute time period in time units that the resource shall wait for a specified event to
occur before returning the time elapsed error. The time unit is in milliseconds.
None means waiting forever if necessary.
:param capture_timeout: When True will not produce a VisaIOError(VI_ERROR_TMO) but
instead return a WaitResponse with timed_out=True
:return: A WaitResponse object that contains event_type, context and ret value.
"""
try:
event_type, context, ret = self.visalib.wait_on_event(self.session, in_event_type, timeout)
except errors.VisaIOError as exc:
if capture_timeout and exc.error_code == constants.StatusCode.error_timeout:
return WaitResponse(in_event_type, None, exc.error_code, self.visalib, timed_out=True)
raise
return WaitResponse(event_type, context, ret, self.visalib)
|
Establish a shared lock to the resource.
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
:param requested_key: Access key used by another session with which you
want your session to share a lock or None to generate
a new shared access key.
:returns: A new shared access key if requested_key is None,
otherwise, same value as the requested_key
|
def lock(self, timeout='default', requested_key=None):
"""Establish a shared lock to the resource.
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
:param requested_key: Access key used by another session with which you
want your session to share a lock or None to generate
a new shared access key.
:returns: A new shared access key if requested_key is None,
otherwise, same value as the requested_key
"""
timeout = self.timeout if timeout == 'default' else timeout
timeout = self._cleanup_timeout(timeout)
return self.visalib.lock(self.session, constants.AccessModes.shared_lock, timeout, requested_key)[0]
|
Establish an exclusive lock to the resource.
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
|
def lock_excl(self, timeout='default'):
"""Establish an exclusive lock to the resource.
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
"""
timeout = self.timeout if timeout == 'default' else timeout
timeout = self._cleanup_timeout(timeout)
self.visalib.lock(self.session, constants.AccessModes.exclusive_lock, timeout, None)
|
A context that locks
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
:param requested_key: When using default of 'exclusive' the lock
is an exclusive lock.
Otherwise it is the access key for the shared lock or
None to generate a new shared access key.
The returned context is the access_key if applicable.
|
def lock_context(self, timeout='default', requested_key='exclusive'):
"""A context that locks
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
:param requested_key: When using default of 'exclusive' the lock
is an exclusive lock.
Otherwise it is the access key for the shared lock or
None to generate a new shared access key.
The returned context is the access_key if applicable.
"""
if requested_key == 'exclusive':
self.lock_excl(timeout)
access_key = None
else:
access_key = self.lock(timeout, requested_key)
try:
yield access_key
finally:
self.unlock()
|
Generates a list of PrettyTables from a string of HTML code. Each <table> in
the HTML becomes one PrettyTable object.
|
def from_html(html_code, **kwargs):
"""
Generates a list of PrettyTables from a string of HTML code. Each <table> in
the HTML becomes one PrettyTable object.
"""
parser = TableHandler(**kwargs)
parser.feed(html_code)
return parser.tables
|
Generates a PrettyTables from a string of HTML code which contains only a
single <table>
|
def from_html_one(html_code, **kwargs):
"""
Generates a PrettyTables from a string of HTML code which contains only a
single <table>
"""
tables = from_html(html_code, **kwargs)
try:
assert len(tables) == 1
except AssertionError:
raise Exception("More than one <table> in provided HTML code! Use from_html instead.")
return tables[0]
|
Add a row to the table
Arguments:
row - row of data, should be a list with as many elements as the table
has fields
|
def add_row(self, row):
"""Add a row to the table
Arguments:
row - row of data, should be a list with as many elements as the table
has fields"""
if self._field_names and len(row) != len(self._field_names):
raise Exception("Row has incorrect number of values, (actual) %d!=%d (expected)" %(len(row),len(self._field_names)))
if not self._field_names:
self.field_names = [("Field %d" % (n+1)) for n in range(0,len(row))]
self._rows.append(list(row))
|
Delete a row to the table
Arguments:
row_index - The index of the row you want to delete. Indexing starts at 0.
|
def del_row(self, row_index):
"""Delete a row to the table
Arguments:
row_index - The index of the row you want to delete. Indexing starts at 0."""
if row_index > len(self._rows)-1:
raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(self._rows)))
del self._rows[row_index]
|
Add a column to the table.
Arguments:
fieldname - name of the field to contain the new column of data
column - column of data, should be a list with as many elements as the
table has rows
align - desired alignment for this column - "l" for left, "c" for centre and "r" for right
valign - desired vertical alignment for new columns - "t" for top, "m" for middle and "b" for bottom
|
def add_column(self, fieldname, column, align="c", valign="t"):
"""Add a column to the table.
Arguments:
fieldname - name of the field to contain the new column of data
column - column of data, should be a list with as many elements as the
table has rows
align - desired alignment for this column - "l" for left, "c" for centre and "r" for right
valign - desired vertical alignment for new columns - "t" for top, "m" for middle and "b" for bottom"""
if len(self._rows) in (0, len(column)):
self._validate_align(align)
self._validate_valign(valign)
self._field_names.append(fieldname)
self._align[fieldname] = align
self._valign[fieldname] = valign
for i in range(0, len(column)):
if len(self._rows) < i+1:
self._rows.append([])
self._rows[i].append(column[i])
else:
raise Exception("Column length %d does not match number of rows %d!" % (len(column), len(self._rows)))
|
Return string representation of HTML formatted version of table in current state.
Arguments:
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
fields - names of fields (columns) to include
header - print a header showing field names (True or False)
border - print a border around the table (True or False)
hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE
vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
int_format - controls formatting of integer data
float_format - controls formatting of floating point data
padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
left_padding_width - number of spaces on left hand side of column data
right_padding_width - number of spaces on right hand side of column data
sortby - name of field to sort rows by
sort_key - sorting key function, applied to data points before sorting
attributes - dictionary of name/value pairs to include as HTML attributes in the <table> tag
xhtml - print <br/> tags if True, <br> tags if false
|
def get_html_string(self, **kwargs):
"""Return string representation of HTML formatted version of table in current state.
Arguments:
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
fields - names of fields (columns) to include
header - print a header showing field names (True or False)
border - print a border around the table (True or False)
hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE
vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
int_format - controls formatting of integer data
float_format - controls formatting of floating point data
padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
left_padding_width - number of spaces on left hand side of column data
right_padding_width - number of spaces on right hand side of column data
sortby - name of field to sort rows by
sort_key - sorting key function, applied to data points before sorting
attributes - dictionary of name/value pairs to include as HTML attributes in the <table> tag
xhtml - print <br/> tags if True, <br> tags if false"""
options = self._get_options(kwargs)
if options["format"]:
string = self._get_formatted_html_string(options)
else:
string = self._get_simple_html_string(options)
return string
|
iterates over the row and make each field unique
|
def make_fields_unique(self, fields):
"""
iterates over the row and make each field unique
"""
for i in range(0, len(fields)):
for j in range(i+1, len(fields)):
if fields[i] == fields[j]:
fields[j] += "'"
|
Handles parsing response structure and translating API Exceptions
|
def meta_request(func):
""" Handles parsing response structure and translating API Exceptions """
def inner(self, resource, *args, **kwargs):
serialize_response = kwargs.pop('serialize', True)
try:
resp = func(self, resource, *args, **kwargs)
except ApiException as e:
raise api_exception(e)
if serialize_response:
return serialize(resource, resp)
return resp
return inner
|
Stream events for a resource from the Kubernetes API
:param resource: The API resource object that will be used to query the API
:param namespace: The namespace to query
:param name: The name of the resource instance to query
:param label_selector: The label selector with which to filter results
:param field_selector: The field selector with which to filter results
:param resource_version: The version with which to filter results. Only events with
a resource_version greater than this value will be returned
:param timeout: The amount of time in seconds to wait before terminating the stream
:return: Event object with these keys:
'type': The type of event such as "ADDED", "DELETED", etc.
'raw_object': a dict representing the watched object.
'object': A ResourceInstance wrapping raw_object.
Example:
client = DynamicClient(k8s_client)
v1_pods = client.resources.get(api_version='v1', kind='Pod')
for e in v1_pods.watch(resource_version=0, namespace=default, timeout=5):
print(e['type'])
print(e['object'].metadata)
|
def watch(self, resource, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None):
"""
Stream events for a resource from the Kubernetes API
:param resource: The API resource object that will be used to query the API
:param namespace: The namespace to query
:param name: The name of the resource instance to query
:param label_selector: The label selector with which to filter results
:param field_selector: The field selector with which to filter results
:param resource_version: The version with which to filter results. Only events with
a resource_version greater than this value will be returned
:param timeout: The amount of time in seconds to wait before terminating the stream
:return: Event object with these keys:
'type': The type of event such as "ADDED", "DELETED", etc.
'raw_object': a dict representing the watched object.
'object': A ResourceInstance wrapping raw_object.
Example:
client = DynamicClient(k8s_client)
v1_pods = client.resources.get(api_version='v1', kind='Pod')
for e in v1_pods.watch(resource_version=0, namespace=default, timeout=5):
print(e['type'])
print(e['object'].metadata)
"""
watcher = watch.Watch()
for event in watcher.stream(
resource.get,
namespace=namespace,
name=name,
field_selector=field_selector,
label_selector=label_selector,
resource_version=resource_version,
serialize=False,
timeout_seconds=timeout
):
event['object'] = ResourceInstance(resource, event['object'])
yield event
|
validate checks a kubernetes resource definition
Args:
definition (dict): resource definition
version (str): version of kubernetes to validate against
strict (bool): whether unexpected additional properties should be considered errors
Returns:
warnings (list), errors (list): warnings are missing validations, errors are validation failures
|
def validate(self, definition, version=None, strict=False):
"""validate checks a kubernetes resource definition
Args:
definition (dict): resource definition
version (str): version of kubernetes to validate against
strict (bool): whether unexpected additional properties should be considered errors
Returns:
warnings (list), errors (list): warnings are missing validations, errors are validation failures
"""
if not HAS_KUBERNETES_VALIDATE:
raise KubernetesValidateMissing()
errors = list()
warnings = list()
try:
if version is None:
try:
version = self.version['kubernetes']['gitVersion']
except KeyError:
version = kubernetes_validate.latest_version()
kubernetes_validate.validate(definition, version, strict)
except kubernetes_validate.utils.ValidationError as e:
errors.append("resource definition validation error at %s: %s" % ('.'.join([str(item) for item in e.path]), e.message)) # noqa: B306
except VersionNotSupportedError as e:
errors.append("Kubernetes version %s is not supported by kubernetes-validate" % version)
except kubernetes_validate.utils.SchemaNotFoundError as e:
warnings.append("Could not find schema for object kind %s with API version %s in Kubernetes version %s (possibly Custom Resource?)" %
(e.kind, e.api_version, e.version))
return warnings, errors
|
Takes a List body and return a dictionary with the following structure:
{
'api_version': str,
'kind': str,
'items': [{
'resource': Resource,
'name': str,
'namespace': str,
}]
}
|
def _items_to_resources(self, body):
""" Takes a List body and return a dictionary with the following structure:
{
'api_version': str,
'kind': str,
'items': [{
'resource': Resource,
'name': str,
'namespace': str,
}]
}
"""
if body is None:
raise ValueError("You must provide a body when calling methods on a ResourceList")
api_version = body['apiVersion']
kind = body['kind']
items = body.get('items')
if not items:
raise ValueError('The `items` field in the body must be populated when calling methods on a ResourceList')
if self.kind != kind:
raise ValueError('Methods on a {} must be called with a body containing the same kind. Receieved {} instead'.format(self.kind, kind))
return {
'api_version': api_version,
'kind': kind,
'items': [self._item_to_resource(item) for item in items]
}
|
Discovers all API groups present in the cluster
|
def parse_api_groups(self, request_resources=False, update=False):
""" Discovers all API groups present in the cluster """
if not self._cache.get('resources') or update:
self._cache['resources'] = self._cache.get('resources', {})
groups_response = load_json(self.client.request('GET', '/{}'.format(DISCOVERY_PREFIX)))['groups']
groups = self.default_groups(request_resources=request_resources)
for group in groups_response:
new_group = {}
for version_raw in group['versions']:
version = version_raw['version']
resource_group = self._cache.get('resources', {}).get(DISCOVERY_PREFIX, {}).get(group['name'], {}).get(version)
preferred = version_raw == group['preferredVersion']
resources = resource_group.resources if resource_group else {}
if request_resources:
resources = self.get_resources_for_api_version(DISCOVERY_PREFIX, group['name'], version, preferred)
new_group[version] = ResourceGroup(preferred, resources=resources)
groups[DISCOVERY_PREFIX][group['name']] = new_group
self._cache['resources'].update(groups)
self._write_cache()
return self._cache['resources']
|
returns a dictionary of resources associated with provided (prefix, group, version)
|
def get_resources_for_api_version(self, prefix, group, version, preferred):
""" returns a dictionary of resources associated with provided (prefix, group, version)"""
resources = defaultdict(list)
subresources = {}
path = '/'.join(filter(None, [prefix, group, version]))
resources_response = load_json(self.client.request('GET', path))['resources']
resources_raw = list(filter(lambda resource: '/' not in resource['name'], resources_response))
subresources_raw = list(filter(lambda resource: '/' in resource['name'], resources_response))
for subresource in subresources_raw:
resource, name = subresource['name'].split('/')
if not subresources.get(resource):
subresources[resource] = {}
subresources[resource][name] = subresource
for resource in resources_raw:
# Prevent duplicate keys
for key in ('prefix', 'group', 'api_version', 'client', 'preferred'):
resource.pop(key, None)
resourceobj = Resource(
prefix=prefix,
group=group,
api_version=version,
client=self.client,
preferred=preferred,
subresources=subresources.get(resource['name']),
**resource
)
resources[resource['kind']].append(resourceobj)
resource_list = ResourceList(self.client, group=group, api_version=version, base_kind=resource['kind'])
resources[resource_list.kind].append(resource_list)
return resources
|
Same as search, but will throw an error if there are multiple or no
results. If there are multiple results and only one is an exact match
on api_version, that resource will be returned.
|
def get(self, **kwargs):
""" Same as search, but will throw an error if there are multiple or no
results. If there are multiple results and only one is an exact match
on api_version, that resource will be returned.
"""
results = self.search(**kwargs)
# If there are multiple matches, prefer exact matches on api_version
if len(results) > 1 and kwargs.get('api_version'):
results = [
result for result in results if result.group_version == kwargs['api_version']
]
# If there are multiple matches, prefer non-List kinds
if len(results) > 1 and not all([isinstance(x, ResourceList) for x in results]):
results = [result for result in results if not isinstance(result, ResourceList)]
if len(results) == 1:
return results[0]
elif not results:
raise ResourceNotFoundError('No matches found for {}'.format(kwargs))
else:
raise ResourceNotUniqueError('Multiple matches found for {}: {}'.format(kwargs, results))
|
Returns the proper Exception class for the given kubernetes.client.rest.ApiException object
https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#success-codes
|
def api_exception(e):
"""
Returns the proper Exception class for the given kubernetes.client.rest.ApiException object
https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#success-codes
"""
_, _, exc_traceback = sys.exc_info()
tb = '\n'.join(traceback.format_tb(exc_traceback))
return {
400: BadRequestError,
401: UnauthorizedError,
403: ForbiddenError,
404: NotFoundError,
405: MethodNotAllowedError,
409: ConflictError,
410: GoneError,
422: UnprocessibleEntityError,
429: TooManyRequestsError,
500: InternalServerError,
503: ServiceUnavailableError,
504: ServerTimeoutError,
}.get(e.status, DynamicApiError)(e, tb)
|
Adds a device to the list of devices we know about.
|
def add_device(dev):
"""Adds a device to the list of devices we know about."""
global DEV_IDX, DEFAULT_DEV
with DEV_LOCK:
for idx in range(len(DEVS)):
test_dev = DEVS[idx]
if test_dev.dev_name_short == dev.dev_name_short:
# This device is already in our list. Delete the old one
if test_dev is DEFAULT_DEV:
DEFAULT_DEV = None
del DEVS[idx]
break
if find_device_by_name(dev.name):
# This name is taken - make it unique
dev.name += '-%d' % DEV_IDX
dev.name_path = '/' + dev.name + '/'
DEVS.append(dev)
DEV_IDX += 1
if DEFAULT_DEV is None:
DEFAULT_DEV = dev
|
Tries to find a board by board name.
|
def find_device_by_name(name):
"""Tries to find a board by board name."""
if not name:
return DEFAULT_DEV
with DEV_LOCK:
for dev in DEVS:
if dev.name == name:
return dev
return None
|
Checks a USB device to see if it looks like a MicroPython device.
|
def is_micropython_usb_device(port):
"""Checks a USB device to see if it looks like a MicroPython device.
"""
if type(port).__name__ == 'Device':
# Assume its a pyudev.device.Device
if ('ID_BUS' not in port or port['ID_BUS'] != 'usb' or
'SUBSYSTEM' not in port or port['SUBSYSTEM'] != 'tty'):
return False
usb_id = 'usb vid:pid={}:{}'.format(port['ID_VENDOR_ID'], port['ID_MODEL_ID'])
else:
# Assume its a port from serial.tools.list_ports.comports()
usb_id = port[2].lower()
# We don't check the last digit of the PID since there are 3 possible
# values.
if usb_id.startswith('usb vid:pid=f055:980'):
return True
# Check for Teensy VID:PID
if usb_id.startswith('usb vid:pid=16c0:0483'):
return True
return False
|
Checks to see if the indicated portname is a MicroPython device
or not.
|
def is_micropython_usb_port(portName):
"""Checks to see if the indicated portname is a MicroPython device
or not.
"""
for port in serial.tools.list_ports.comports():
if port.device == portName:
return is_micropython_usb_device(port)
return False
|
Sets up a thread to detect when USB devices are plugged and unplugged.
If the device looks like a MicroPython board, then it will automatically
connect to it.
|
def autoconnect():
"""Sets up a thread to detect when USB devices are plugged and unplugged.
If the device looks like a MicroPython board, then it will automatically
connect to it.
"""
if not USE_AUTOCONNECT:
return
try:
import pyudev
except ImportError:
return
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
connect_thread = threading.Thread(target=autoconnect_thread, args=(monitor,), name='AutoConnect')
connect_thread.daemon = True
connect_thread.start()
|
Thread which detects USB Serial devices connecting and disconnecting.
|
def autoconnect_thread(monitor):
"""Thread which detects USB Serial devices connecting and disconnecting."""
monitor.start()
monitor.filter_by('tty')
epoll = select.epoll()
epoll.register(monitor.fileno(), select.POLLIN)
while True:
try:
events = epoll.poll()
except InterruptedError:
continue
for fileno, _ in events:
if fileno == monitor.fileno():
usb_dev = monitor.poll()
print('autoconnect: {} action: {}'.format(usb_dev.device_node, usb_dev.action))
dev = find_serial_device_by_port(usb_dev.device_node)
if usb_dev.action == 'add':
# Try connecting a few times. Sometimes the serial port
# reports itself as busy, which causes the connection to fail.
for i in range(8):
if dev:
connected = connect_serial(dev.port, dev.baud, dev.wait)
elif is_micropython_usb_device(usb_dev):
connected = connect_serial(usb_dev.device_node)
else:
connected = False
if connected:
break
time.sleep(0.25)
elif usb_dev.action == 'remove':
print('')
print("USB Serial device '%s' disconnected" % usb_dev.device_node)
if dev:
dev.close()
break
|
autoscan will check all of the serial ports to see if they have
a matching VID:PID for a MicroPython board.
|
def autoscan():
"""autoscan will check all of the serial ports to see if they have
a matching VID:PID for a MicroPython board.
"""
for port in serial.tools.list_ports.comports():
if is_micropython_usb_device(port):
connect_serial(port[0])
|
Collects the serial nunber and manufacturer into a string, if
the fields are available.
|
def extra_info(port):
"""Collects the serial nunber and manufacturer into a string, if
the fields are available."""
extra_items = []
if port.manufacturer:
extra_items.append("vendor '{}'".format(port.manufacturer))
if port.serial_number:
extra_items.append("serial '{}'".format(port.serial_number))
if port.interface:
extra_items.append("intf '{}'".format(port.interface))
if extra_items:
return ' with ' + ' '.join(extra_items)
return ''
|
listports will display a list of all of the serial ports.
|
def listports():
"""listports will display a list of all of the serial ports.
"""
detected = False
for port in serial.tools.list_ports.comports():
detected = True
if port.vid:
micropythonPort = ''
if is_micropython_usb_device(port):
micropythonPort = ' *'
print('USB Serial Device {:04x}:{:04x}{} found @{}{}\r'.format(
port.vid, port.pid,
extra_info(port), port.device, micropythonPort))
else:
print('Serial Device:', port.device)
if not detected:
print('No serial devices detected')
|
Precede all special characters with a backslash.
|
def escape(str):
"""Precede all special characters with a backslash."""
out = ''
for char in str:
if char in '\\ ':
out += '\\'
out += char
return out
|
Undoes the effects of the escape() function.
|
def unescape(str):
"""Undoes the effects of the escape() function."""
out = ''
prev_backslash = False
for char in str:
if not prev_backslash and char == '\\':
prev_backslash = True
continue
out += char
prev_backslash = False
return out
|
Returns an aligned element.
|
def align_cell(fmt, elem, width):
"""Returns an aligned element."""
if fmt == "<":
return elem + ' ' * (width - len(elem))
if fmt == ">":
return ' ' * (width - len(elem)) + elem
return elem
|
Prints a formatted list, adjusting the width so everything fits.
fmt contains a single character for each column. < indicates that the
column should be left justified, > indicates that the column should
be right justified. The last column may be a space which implies left
justification and no padding.
|
def column_print(fmt, rows, print_func):
"""Prints a formatted list, adjusting the width so everything fits.
fmt contains a single character for each column. < indicates that the
column should be left justified, > indicates that the column should
be right justified. The last column may be a space which implies left
justification and no padding.
"""
# Figure out the max width of each column
num_cols = len(fmt)
width = [max(0 if isinstance(row, str) else len(row[i]) for row in rows)
for i in range(num_cols)]
for row in rows:
if isinstance(row, str):
# Print a separator line
print_func(' '.join([row * width[i] for i in range(num_cols)]))
else:
print_func(' '.join([align_cell(fmt[i], row[i], width[i])
for i in range(num_cols)]))
|
Finds all of the files which match (used for completion).
|
def find_macthing_files(match):
"""Finds all of the files which match (used for completion)."""
last_slash = match.rfind('/')
if last_slash == -1:
dirname = '.'
match_prefix = match
result_prefix = ''
else:
dirname = match[0:last_slash]
match_prefix = match[last_slash + 1:]
result_prefix = dirname + '/'
return [result_prefix + filename for filename in os.listdir(dirname) if filename.startswith(match_prefix)]
|
Similar to print, but prints to stderr.
|
def print_err(*args, end='\n'):
"""Similar to print, but prints to stderr.
"""
print(*args, end=end, file=sys.stderr)
sys.stderr.flush()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.