Exemplo n.º 1
0
    def write(self, data):
        """Writes data to device or interface synchronously.

        Corresponds to viWrite function of the VISA library.

        :param data: data to be written.
        :type data: bytes
        :return: Number of bytes actually transferred, return value of the library call.
        :rtype: int, VISAStatus
        """

        logger.debug('GPIB.write %r' % data)

        try:
            self.interface.write(data)
            count = self.interface.ibcnt()  # number of bytes transmitted

            return count, StatusCode.success

        except gpib.GpibError:
            # 0x4000 = 16384 = TIMO
            if self.interface.ibsta() & 16384:
                return 0, StatusCode.error_timeout
            else:
                return 0, StatusCode.error_system_error
Exemplo n.º 2
0
    def get_library_paths():
        """Return a tuple of possible library paths.

        :rtype: tuple
        """

        from ..util import LibraryPath, read_user_library_path, add_user_dll_extra_paths

        # Add extra .dll dependency search paths before attempting to load libraries
        add_user_dll_extra_paths()

        # Try to find IVI libraries using known names.
        tmp = [find_library(library_path)
               for library_path in ('visa', 'visa32', 'visa32.dll', 'visa64', 'visa64.dll')]

        logger.debug('Automatically found library files: %s' % tmp)

        # Prepend the path provided by the user in configuration files (if any).
        user_lib = read_user_library_path()
        if user_lib:
            tmp.insert(0, user_lib)

        # Deduplicate and convert string paths to LibraryPath objects
        tmp = [LibraryPath(library_path)
               for library_path in unique(tmp)
               if library_path is not None]

        return tuple(tmp)
Exemplo n.º 3
0
    def gpib_pass_control(self, primary_address: int,
                          secondary_address: int) -> StatusCode:
        """Tell a GPIB device to become controller in charge (CIC).

        Corresponds to viGpibPassControl function of the VISA library.

        Parameters
        ----------
        primary_address : int
            Primary address of the GPIB device to which you want to pass control.
        secondary_address : int
            Secondary address of the targeted GPIB device.
            If the targeted device does not have a secondary address,
            this parameter should contain the value Constants.VI_NO_SEC_ADDR.

        Returns
        -------
        StatusCode
            Return value of the library call.

        """
        # ibpct need to get the device id matching the primary and secondary address
        logger.debug("GPIB.pass control")
        try:
            did = gpib.dev(self.parsed.board, primary_address,
                           secondary_address)
        except gpib.GpibError:
            logger.exception("Failed to get id for %s, %d", primary_address,
                             secondary_address)
            return StatusCode.error_resource_not_found

        status = gpib_lib.ibpct(did)
        return convert_gpib_status(status)
Exemplo n.º 4
0
    def assert_trigger(self,
                       protocol: constants.TriggerProtocol) -> StatusCode:
        """Asserts hardware trigger.

        Parameters
        ----------
        protocol : constants.TriggerProtocol
            Triggering protocol to use.
            Only supports constants.TriggerProtocol.default

        Returns
        -------
        StatusCode
            Return value of the library call.

        """
        logger.debug("GPIB.device assert hardware trigger")

        try:
            if protocol == constants.VI_TRIG_PROT_DEFAULT:
                self.interface.trigger()
                return StatusCode.success
            else:
                return StatusCode.error_nonsupported_operation
        except gpib.GpibError as e:
            return convert_gpib_error(e, self.interface.ibsta(),
                                      "assert trigger")
Exemplo n.º 5
0
    def get_library_paths():
        """Return a tuple of possible library paths.

        :rtype: tuple
        """

        from ..util import LibraryPath, read_user_library_path

        user_lib = read_user_library_path()
        tmp = [
            find_library(library_path)
            for library_path in ('visa', 'visa32', 'visa32.dll', 'visa64',
                                 'visa64.dll')
        ]

        tmp = [
            LibraryPath(library_path) for library_path in set(tmp)
            if library_path is not None
        ]

        logger.debug('Automatically found library files: %s' % tmp)

        if user_lib:
            user_lib = LibraryPath(user_lib, 'user')
            try:
                tmp.remove(user_lib)
            except ValueError:
                pass
            tmp.insert(0, user_lib)

        return tuple(tmp)
Exemplo n.º 6
0
    def gpib_pass_control(self, primary_address, secondary_address):
        """Tell the GPIB device at the specified address to become controller in charge (CIC).

        Corresponds to viGpibPassControl function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param primary_address: Primary address of the GPIB device to which you want to pass control.
        :param secondary_address: Secondary address of the targeted GPIB device.
                                  If the targeted device does not have a secondary address,
                                  this parameter should contain the value Constants.VI_NO_SEC_ADDR.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        # ibpct need to get the device id matching the primary and secondary address
        logger.debug('GPIB.pass control')
        try:
            did = gpib.dev(self.parsed.board, primary_address,
                           secondary_address)
        except gpib.GpibError:
            logger.exception('Failed to get id for %s, %d', primary_address,
                             secondary_address)
            return StatusCode.error_resource_not_found

        status = gpib_lib.ibpct(did)
        return convert_gpib_status(status)
Exemplo n.º 7
0
    def write(self, data):
        """Writes data to device or interface synchronously.

        Corresponds to viWrite function of the VISA library.

        :param data: data to be written.
        :type data: bytes
        :return: Number of bytes actually transferred, return value of the library call.
        :rtype: int, VISAStatus
        """

        logger.debug('GPIB.write %r' % data)

        try:
            self.interface.write(data)
            count = self.interface.ibcnt() # number of bytes transmitted

            return count, StatusCode.success

        except gpib.GpibError:
            # 0x4000 = 16384 = TIMO
            if self.interface.ibsta() & 16384:
                return 0, StatusCode.error_timeout
            else:
                return 0, StatusCode.error_system_error
Exemplo n.º 8
0
def _find_boards() -> Iterator[Tuple[int, int]]:
    """Find GPIB board addresses."""
    for board in range(16):
        try:
            yield board, gpib.ask(board, 1)
        except gpib.GpibError as e:
            logger.debug("GPIB board %i error in _find_boards(): %s", board, repr(e))
Exemplo n.º 9
0
    def gpib_control_atn(self, mode: constants.ATNLineOperation) -> StatusCode:
        """Specifies the state of the ATN line and the local active controller state.

        Corresponds to viGpibControlATN function of the VISA library.

        Parameters
        ----------
        mode : constants.ATNLineOperation
            Specifies the state of the ATN line and optionally the local active
             controller state.

        Returns
        -------
        StatusCode
            Return value of the library call.

        """
        logger.debug("GPIB.control atn")
        if mode == constants.VI_GPIB_ATN_ASSERT:
            status = gpib_lib.ibcac(self.controller.id, 0)
        elif mode == constants.VI_GPIB_ATN_DEASSERT:
            status = gpib_lib.ibgts(self.controller.id, 0)
        elif mode == constants.VI_GPIB_ATN_ASSERT_IMMEDIATE:
            # Asynchronous assertion (the name is counter intuitive)
            status = gpib_lib.ibcac(self.controller.id, 1)
        elif mode == constants.VI_GPIB_ATN_DEASSERT_HANDSHAKE:
            status = gpib_lib.ibgts(self.controller.id, 1)
        else:
            return constants.StatusCode.error_invalid_mode
        return convert_gpib_status(status)
Exemplo n.º 10
0
    def write(self, data: bytes) -> Tuple[int, StatusCode]:
        """Writes data to device or interface synchronously.

        Corresponds to viWrite function of the VISA library.

        Parameters
        ----------
        data : bytes
            Data to be written.

        Returns
        -------
        int
            Number of bytes actually transferred
        StatusCode
            Return value of the library call.

        """
        logger.debug("GPIB.write %r" % data)

        # INTFC don't have an interface so use the controller
        ifc = self.interface or self.controller

        try:
            ifc.write(data)
            count = ifc.ibcnt()  # number of bytes transmitted

            return count, StatusCode.success
        except gpib.GpibError as e:
            return 0, convert_gpib_error(e, ifc.ibsta(), "write")
Exemplo n.º 11
0
    def get_library_paths():
        """Return a tuple of possible library paths.

        :rtype: tuple
        """

        from ..util import LibraryPath, read_user_library_path

        user_lib = read_user_library_path()
        tmp = [find_library(library_path)
               for library_path in ('visa', 'visa32', 'visa32.dll', 'visa64', 'visa64.dll')]

        tmp = [LibraryPath(library_path)
               for library_path in set(tmp)
               if library_path is not None]

        logger.debug('Automatically found library files: %s' % tmp)

        if user_lib:
            user_lib = LibraryPath(user_lib, 'user')
            try:
                tmp.remove(user_lib)
            except ValueError:
                pass
            tmp.insert(0, user_lib)

        return tuple(tmp)
Exemplo n.º 12
0
    def get_library_paths():
        """Return a tuple of possible library paths.

        :rtype: tuple
        """

        from ..util import LibraryPath, read_user_library_path

        # Try to find NI libraries using known names.
        tmp = [find_library(library_path)
               for library_path in ('visa', 'visa32', 'visa32.dll', 'visa64', 'visa64.dll')]

        logger.debug('Automatically found library files: %s' % tmp)

        # Prepend the path provided by the user in configuration files (if any).
        user_lib = read_user_library_path()
        if user_lib:
            tmp.insert(0, user_lib)

        # Deduplicate and convert string paths to LibraryPath objects
        tmp = [LibraryPath(library_path)
               for library_path in unique(tmp)
               if library_path is not None]

        return tuple(tmp)
Exemplo n.º 13
0
    def _return_handler(self, ret_value: int, func: Callable,
                        arguments: tuple) -> Any:
        """Check return values for errors and warnings."""
        logger.debug(
            "%s%s -> %r",
            func.__name__,
            _args_to_str(arguments),
            ret_value,
            extra=self._logging_extra,
        )

        rv: constants.StatusCode
        try:
            rv = constants.StatusCode(ret_value)
        except ValueError:
            rv = cast(constants.StatusCode, ret_value)

        self._last_status = rv

        # The first argument of almost all registered visa functions is a session.
        # We store the error code per session
        session = None
        if func.__name__ not in ("viFindNext", ):
            try:
                session = arguments[0]
            except KeyError:
                raise Exception("Function %r does not seem to be a valid "
                                "visa function (len args %d)" %
                                (func, len(arguments)))

            # Functions that use the first parameter to get a session value.
            if func.__name__ in ("viOpenDefaultRM", ):
                # noinspection PyProtectedMember
                session = session._obj.value

            if isinstance(session, int):
                self._last_status_in_session[session] = rv
            else:
                # Functions that might or might have a session in the first argument.
                if func.__name__ not in (
                        "viClose",
                        "viGetAttribute",
                        "viSetAttribute",
                        "viStatusDesc",
                ):
                    raise Exception("Function %r does not seem to be a valid "
                                    "visa function (type args[0] %r)" %
                                    (func, type(session)))

        if ret_value < 0:
            raise errors.VisaIOError(rv)

        if rv in self.issue_warning_on:
            if session and ret_value not in self._ignore_warning_in_session[
                    session]:
                warnings.warn(errors.VisaIOWarning(ret_value), stacklevel=2)

        return ret_value
Exemplo n.º 14
0
def _find_listeners():
    """Find GPIB listeners.
    """
    for i in range(31):
        try:
            if gpib.listener(BOARD, i) and gpib.ask(BOARD, 1) != i:
                yield i
        except gpib.GpibError as e:
            logger.debug("GPIB error in _find_listeners(): %s", repr(e))
Exemplo n.º 15
0
def _find_listeners():
    """Find GPIB listeners.
    """
    for i in range(31):
        try:
            if gpib.listener(BOARD, i) and gpib.ask(BOARD, 1) != i:
                yield i
        except gpib.GpibError as e:
            logger.debug("GPIB error in _find_listeners(): %s", repr(e))
Exemplo n.º 16
0
    def _return_handler(self, ret_value, func, arguments):
        """Check return values for errors and warnings.

        TODO: THIS IS JUST COPIED PASTED FROM NIVisaLibrary.
        Needs to be adapted.
        """

        logger.debug('%s%s -> %r',
                     func.__name__,
                     _args_to_str(arguments),
                     ret_value,
                     extra=self._logging_extra)

        try:
            ret_value = constants.StatusCode(ret_value)
        except ValueError:
            pass

        self._last_status = ret_value

        # The first argument of almost all registered visa functions is a session.
        # We store the error code per session
        session = None
        if func.__name__ not in ('viFindNext', ):
            try:
                session = arguments[0]
            except KeyError:
                raise Exception('Function %r does not seem to be a valid '
                                'visa function (len args %d)' %
                                (func, len(arguments)))

            # Functions that use the first parameter to get a session value.
            if func.__name__ in ('viOpenDefaultRM', ):
                # noinspection PyProtectedMember
                session = session._obj.value

            if isinstance(session, integer_types):
                self._last_status_in_session[session] = ret_value
            else:
                # Functions that might or might have a session in the first argument.
                if func.__name__ not in ('viClose', 'viGetAttribute',
                                         'viSetAttribute', 'viStatusDesc'):
                    raise Exception('Function %r does not seem to be a valid '
                                    'visa function (type args[0] %r)' %
                                    (func, type(session)))

        if ret_value < 0:
            raise errors.VisaIOError(ret_value)

        if ret_value in self.issue_warning_on:
            if session and ret_value not in self._ignore_warning_in_session[
                    session]:
                warnings.warn(errors.VisaIOWarning(ret_value), stacklevel=2)

        return ret_value
Exemplo n.º 17
0
def _find_listeners():
    """Find GPIB listeners.
    """
    for board, boardpad in _find_boards():
        for i in range(31):
            try:
                if boardpad != i and gpib.listener(board, i):
                    yield board, i
            except gpib.GpibError as e:
                logger.debug(
                    "GPIB board %i addr %i error in _find_listeners(): %s",
                    board, i, repr(e))
Exemplo n.º 18
0
    def gpib_send_ifc(self) -> StatusCode:
        """Pulse the interface clear line (IFC) for at least 100 microseconds.

        Corresponds to viGpibSendIFC function of the VISA library.

        """
        logger.debug("GPIB.interface clear")
        try:
            self.controller.interface_clear()
            return StatusCode.success
        except gpib.GpibError as e:
            return convert_gpib_error(e, self.controller.ibsta(), "send IFC")
Exemplo n.º 19
0
    def write(self, data: bytes) -> Tuple[int, StatusCode]:
        """Writes data to device or interface synchronously.

        Corresponds to viWrite function of the VISA library.

        Parameters
        ----------
        data : bytes
            Data to be written.

        Returns
        -------
        int
            Number of bytes actually transferred
        StatusCode
            Return value of the library call.

        """
        logger.debug("Serial.write %r" % data)
        end_out, _ = self.get_attribute(ResourceAttribute.asrl_end_out)
        send_end, _ = self.get_attribute(ResourceAttribute.send_end_enabled)

        if end_out in (SerialTermination.none,
                       SerialTermination.termination_break):
            pass
        elif end_out == SerialTermination.last_bit:
            last_bit, _ = self.get_attribute(ResourceAttribute.asrl_data_bits)
            mask = 1 << (last_bit - 1)
            data = bytes(iter_bytes(data, mask, send_end))

        elif end_out == SerialTermination.termination_char:
            term_char, _ = self.get_attribute(ResourceAttribute.termchar)
            data = data + common.int_to_byte(term_char)

        else:
            raise ValueError("Unknown value for VI_ATTR_ASRL_END_OUT: %s" %
                             end_out)

        try:
            count = self.interface.write(data)

            if end_out == SerialTermination.termination_break:
                logger.debug("Serial.sendBreak")
                self.interface.sendBreak()

            return count, StatusCode.success

        except serial.SerialTimeoutException:
            return 0, StatusCode.error_timeout
Exemplo n.º 20
0
    def _return_handler(self, ret_value, func, arguments):
        """Check return values for errors and warnings.

        TODO: THIS IS JUST COPIED PASTED FROM NIVisaLibrary.
        Needs to be adapted.
        """

        logger.debug('%s%s -> %r',
                     func.__name__, _args_to_str(arguments), ret_value,
                     extra=self._logging_extra)

        try:
            ret_value = constants.StatusCode(ret_value)
        except ValueError:
            pass

        self._last_status = ret_value

        # The first argument of almost all registered visa functions is a session.
        # We store the error code per session
        session = None
        if func.__name__ not in ('viFindNext', ):
            try:
                session = arguments[0]
            except KeyError:
                raise Exception('Function %r does not seem to be a valid '
                                'visa function (len args %d)' % (func, len(arguments)))

            # Functions that use the first parameter to get a session value.
            if func.__name__ in ('viOpenDefaultRM', ):
                # noinspection PyProtectedMember
                session = session._obj.value

            if isinstance(session, integer_types):
                self._last_status_in_session[session] = ret_value
            else:
                # Functions that might or might have a session in the first argument.
                if func.__name__ not in ('viClose', 'viGetAttribute', 'viSetAttribute', 'viStatusDesc'):
                    raise Exception('Function %r does not seem to be a valid '
                                    'visa function (type args[0] %r)' % (func, type(session)))

        if ret_value < 0:
            raise errors.VisaIOError(ret_value)

        if ret_value in self.issue_warning_on:
            if session and ret_value not in self._ignore_warning_in_session[session]:
                warnings.warn(errors.VisaIOWarning(ret_value), stacklevel=2)

        return ret_value
Exemplo n.º 21
0
    def gpib_send_ifc(self):
        """Pulse the interface clear line (IFC) for at least 100 microseconds.

        Corresponds to viGpibSendIFC function of the VISA library.

        :param session: Unique logical identifier to a session.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        logger.debug('GPIB.interface clear')
        try:
            self.controller.interface_clear()
            return StatusCode.success
        except gpib.GpibError as e:
            return convert_gpib_error(e, self.controller.ibsta(), 'send IFC')
Exemplo n.º 22
0
    def write(self, data):
        """Writes data to device or interface synchronously.

        Corresponds to viWrite function of the VISA library.

        :param data: data to be written.
        :type data: bytes
        :return: Number of bytes actually transferred, return value of the library call.
        :rtype: int, VISAStatus
        """
        logger.debug('Serial.write %r' % data)
        # TODO: How to deal with VI_ATTR_TERMCHAR_EN
        end_out, _ = self.get_attribute(constants.VI_ATTR_ASRL_END_OUT)
        send_end, _ = self.get_attribute(constants.VI_ATTR_SEND_END_EN)

        try:
            # We need to wrap data in common.iter_bytes to Provide Python 2 and 3 compatibility

            if end_out in (SerialTermination.none,
                           SerialTermination.termination_break):
                data = common.iter_bytes(data)

            elif end_out == SerialTermination.last_bit:
                last_bit, _ = self.get_attribute(
                    constants.VI_ATTR_ASRL_DATA_BITS)
                mask = 1 << (last_bit - 1)
                data = common.iter_bytes(data, mask, send_end)

            elif end_out == SerialTermination.termination_char:
                term_char, _ = self.get_attribute(constants.VI_ATTR_TERMCHAR)
                data = common.iter_bytes(data + common.int_to_byte(term_char))

            else:
                raise ValueError('Unknown value for VI_ATTR_ASRL_END_OUT: %s' %
                                 end_out)

            count = 0
            for d in data:
                count += self.interface.write(d)

            if end_out == SerialTermination.termination_break:
                logger.debug('Serial.sendBreak')
                self.interface.sendBreak()

            return count, constants.StatusCode.success

        except serial.SerialTimeoutException:
            return 0, StatusCode.error_timeout
Exemplo n.º 23
0
    def clear(self):
        """Clears a device.

        Corresponds to viClear function of the VISA library.

        :param session: Unique logical identifier to a session.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """

        logger.debug('GPIB.device clear')
        try:
            self.interface.clear()
            return StatusCode.success
        except gpib.GpibError as e:
            return convert_gpib_error(e, self.interface.ibsta(), 'clear')
Exemplo n.º 24
0
    def clear(self) -> StatusCode:
        """Clears a device.

        Corresponds to viClear function of the VISA library.

        Returns
        -------
        StatusCode
            Return value of the library call.

        """
        logger.debug("GPIB.device clear")
        try:
            self.interface.clear()
            return StatusCode.success
        except gpib.GpibError as e:
            return convert_gpib_error(e, self.interface.ibsta(), "clear")
Exemplo n.º 25
0
    def gpib_send_ifc(self):
        """Pulse the interface clear line (IFC) for at least 100 microseconds.

        Corresponds to viGpibSendIFC function of the VISA library.

        :param session: Unique logical identifier to a session.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """

        logger.debug('GPIB.interface clear')

        try:
            self.controller.interface_clear()
            return StatusCode.success
        except gpib.GpibError:
            return StatusCode.error_system_error
Exemplo n.º 26
0
    def clear(self):
        """Clears a device.

        Corresponds to viClear function of the VISA library.

        :param session: Unique logical identifier to a session.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """

        logger.debug('GPIB.device clear')

        try:
            self.interface.clear()
            return 0, StatusCode.success
        except Exception:
            return 0, StatusCode.error_system_error
Exemplo n.º 27
0
    def clear(self):
        """Clears a device.

        Corresponds to viClear function of the VISA library.

        :param session: Unique logical identifier to a session.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """

        logger.debug('GPIB.device clear')

        try:
            self.interface.clear()
            return StatusCode.success
        except gpib.GpibError:
            return StatusCode.error_system_error
Exemplo n.º 28
0
def convert_gpib_error(
    error: gpib.GpibError, status: int, operation: str
) -> StatusCode:
    """Convert a GPIB error to a VISA StatusCode.

    Parameters
    ----------
    error : gpib.GpibError
        Error to use to determine the proper status code.
    status : int
        Status byte of the GPIB library.
    operation : str
        Name of the operation that caused an exception. Used in logging.

    Returns
    -------
    StatusCode
        Status code matching the GPIB error.

    """
    # First check the imeout condition in the status byte
    if status & 0x4000:
        return StatusCode.error_timeout
    # All other cases are hard errors.
    # In particular linux-gpib simply gives a string we could parse but that
    # feels brittle. As a consequence we only try to be smart when using
    # gpib-ctypes. However in both cases we log the exception at debug level.
    else:
        logger.debug("Failed to %s.", exc_info=error)
        if not GPIB_CTYPES:
            return StatusCode.error_system_error
        if error.code == 1:
            return StatusCode.error_not_cic
        elif error.code == 2:
            return StatusCode.error_no_listeners
        elif error.code == 4:
            return StatusCode.error_invalid_mode
        elif error.code == 11:
            return StatusCode.error_nonsupported_operation
        elif error.code == 1:
            return StatusCode.error_not_cic
        elif error.code == 21:
            return StatusCode.error_resource_locked
        else:
            return StatusCode.error_system_error
Exemplo n.º 29
0
    def write(self, data):
        """Writes data to device or interface synchronously.

        Corresponds to viWrite function of the VISA library.

        :param data: data to be written.
        :type data: bytes
        :return: Number of bytes actually transferred, return value of the library call.
        :rtype: int, VISAStatus
        """
        logger.debug('Serial.write %r' % data)
        # TODO: How to deal with VI_ATTR_TERMCHAR_EN
        end_out, _ = self.get_attribute(constants.VI_ATTR_ASRL_END_OUT)
        send_end, _ = self.get_attribute(constants.VI_ATTR_SEND_END_EN)

        try:
            # We need to wrap data in common.iter_bytes to Provide Python 2 and 3 compatibility

            if end_out in (SerialTermination.none, SerialTermination.termination_break):
                data = common.iter_bytes(data)

            elif end_out == SerialTermination.last_bit:
                last_bit, _ = self.get_attribute(constants.VI_ATTR_ASRL_DATA_BITS)
                mask = 1 << (last_bit - 1)
                data = common.iter_bytes(data, mask, send_end)

            elif end_out == SerialTermination.termination_char:
                term_char, _ = self.get_attribute(constants.VI_ATTR_TERMCHAR)
                data = common.iter_bytes(data + common.int_to_byte(term_char))

            else:
                raise ValueError('Unknown value for VI_ATTR_ASRL_END_OUT: %s' % end_out)

            count = 0
            for d in data:
                count += self.interface.write(d)

            if end_out == SerialTermination.termination_break:
                logger.debug('Serial.sendBreak')
                self.interface.sendBreak()

            return count, constants.StatusCode.success

        except serial.SerialTimeoutException:
            return 0, StatusCode.error_timeout
Exemplo n.º 30
0
    def trigger(self, protocol):
        """Asserts hardware trigger.
        Only supports protocol = constants.VI_TRIG_PROT_DEFAULT

        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """

        logger.debug('GPIB.device assert hardware trigger')

        try:
            if protocol == constants.VI_TRIG_PROT_DEFAULT:
                self.interface.trigger()
                return StatusCode.success
            else:
                return StatusCode.error_nonsupported_operation
        except gpib.GpibError:
            return StatusCode.error_system_error
Exemplo n.º 31
0
    def assert_trigger(self, protocol):
        """Asserts hardware trigger.
        Only supports protocol = constants.VI_TRIG_PROT_DEFAULT

        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """

        logger.debug('GPIB.device assert hardware trigger')

        try:
            if protocol == constants.VI_TRIG_PROT_DEFAULT:
                self.interface.trigger()
                return StatusCode.success
            else:
                return StatusCode.error_nonsupported_operation
        except gpib.GpibError:
            return StatusCode.error_system_error
Exemplo n.º 32
0
    def write(self, data):
        """Writes data to device or interface synchronously.

        Corresponds to viWrite function of the VISA library.

        :param data: data to be written.
        :type data: bytes
        :return: Number of bytes actually transferred, return value of the library call.
        :rtype: int, VISAStatus
        """

        with self._lock:
            setTimeout(self._timeout)
            setAddress(self._pad)

            logger.debug('Prologix-GPIB.write %r' % data)
            gpib_prologix_device.write(data)

            return SUCCESS
Exemplo n.º 33
0
    def _return_handler(self, ret_value: int, func: Callable,
                        arguments: tuple) -> Any:
        """Check return values for errors and warnings."""
        logger.debug(
            "%s%s -> %r",
            func.__name__,
            _args_to_str(arguments),
            ret_value,
            extra=self._logging_extra,
        )

        # The first argument of almost all registered visa functions is a session.
        # We store the error code per session
        session = None
        if func.__name__ not in ("viFindNext", ):
            try:
                session = arguments[0]
            except KeyError:
                raise Exception("Function %r does not seem to be a valid "
                                "visa function (len args %d)" %
                                (func, len(arguments)))

            # Functions that use the first parameter to get a session value.
            if func.__name__ in ("viOpenDefaultRM", ):
                session = session._obj.value

            if not isinstance(session, int):
                # Functions that might or might not have a session in the first argument.
                if func.__name__ not in (
                        "viClose",
                        "viGetAttribute",
                        "viSetAttribute",
                        "viStatusDesc",
                ):
                    raise Exception("Function %r does not seem to be a valid "
                                    "visa function (type args[0] %r)" %
                                    (func, type(session)))

                # Set session back to a safe value
                session = None

        return self.handle_return_value(session, ret_value)  # type: ignore
Exemplo n.º 34
0
    def _init(self):
        try:
            lib = Library(self.library_path)
        except OSError as exc:
            raise errors.LibraryError.from_exception(exc, self.library_path)

        self.lib = lib

        # Set the argtypes, restype and errcheck for each function
        # of the visa library. Additionally store in `_functions` the
        # name of the functions.
        functions.set_signatures(self.lib, errcheck=self._return_handler)

        logger.debug('Library signatures: %d ok, %d failed',
                     len(getattr(self.lib, '_functions', [])),
                     len(getattr(self.lib, '_functions_failed', [])))

        # Set the library functions as attributes of the object.
        for method_name in getattr(self.lib, '_functions', []):
            setattr(self, method_name, getattr(self.lib, method_name))
Exemplo n.º 35
0
    def _init(self):
        try:
            lib = Library(self.library_path)
        except OSError as exc:
            raise errors.LibraryError.from_exception(exc, self.library_path)

        self.lib = lib

        # Set the argtypes, restype and errcheck for each function
        # of the visa library. Additionally store in `_functions` the
        # name of the functions.
        functions.set_signatures(self.lib, errcheck=self._return_handler)

        logger.debug('Library signatures: %d ok, %d failed',
                     len(getattr(self.lib, '_functions', [])),
                     len(getattr(self.lib, '_functions_failed', [])))

        # Set the library functions as attributes of the object.
        for method_name in getattr(self.lib, '_functions', []):
            setattr(self, method_name, getattr(self.lib, method_name))
Exemplo n.º 36
0
    def write(self, data):
        """Writes data to device or interface synchronously.

        Corresponds to viWrite function of the VISA library.

        :param data: data to be written.
        :type data: bytes
        :return: Number of bytes actually transferred, return value of the library call.
        :rtype: int, VISAStatus
        """
        logger.debug('GPIB.write %r' % data)

        # INTFC don't have an interface so use the controller
        ifc = self.interface or self.controller

        try:
            ifc.write(data)
            count = ifc.ibcnt()  # number of bytes transmitted

            return count, StatusCode.success
        except gpib.GpibError as e:
            return 0, convert_gpib_error(e, ifc.ibsta(), 'write')
Exemplo n.º 37
0
    def _init(self) -> None:
        try:
            lib = Library(self.library_path)
        except OSError as exc:
            raise errors.LibraryError.from_exception(exc, self.library_path)

        self.lib = lib
        self._async_read_jobs: List[Tuple[types.ViJobId, SupportsBytes]] = []

        # Set the argtypes, restype and errcheck for each function
        # of the visa library. Additionally store in `_functions` the
        # name of the functions.
        functions.set_signatures(self.lib, errcheck=self._return_handler)

        logger.debug(
            "Library signatures: %d ok, %d failed",
            len(getattr(self.lib, "_functions", [])),
            len(getattr(self.lib, "_functions_failed", [])),
        )

        # Set the library functions as attributes of the object.
        for method_name in getattr(self.lib, "_functions", []):
            setattr(self, method_name, getattr(self.lib, method_name))
Exemplo n.º 38
0
    def gpib_control_atn(self, mode):
        """Specifies the state of the ATN line and the local active controller state.

        Corresponds to viGpibControlATN function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param mode: Specifies the state of the ATN line and optionally the local active controller state.
                     (Constants.VI_GPIB_ATN*)
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        logger.debug('GPIB.control atn')
        if mode == constants.VI_GPIB_ATN_ASSERT:
            status = gpib_lib.ibcac(self.controller.id, 0)
        elif mode == constants.VI_GPIB_ATN_DEASSERT:
            status = gpib_lib.ibgts(self.controller.id, 0)
        elif mode == constants.VI_GPIB_ATN_ASSERT_IMMEDIATE:
            # Asynchronous assertion (the name is counter intuitive)
            status = gpib_lib.ibcac(self.controller.id, 1)
        elif mode == constants.VI_GPIB_ATN_DEASSERT_HANDSHAKE:
            status = gpib_lib.ibgts(self.controller.id, 1)
        else:
            return constants.StatusCode.error_invalid_mode
        return convert_gpib_status(status)
Exemplo n.º 39
0
    def get_library_paths() -> Tuple[LibraryPath, ...]:
        """Return a tuple of possible library paths."""
        # Add extra .dll dependency search paths before attempting to load libraries
        add_user_dll_extra_paths()

        # Try to find IVI libraries using known names.
        tmp: List[str]
        tmp = [
            find_library(library_path)
            for library_path in ("visa", "visa32", "visa32.dll", "visa64",
                                 "visa64.dll")
        ]

        logger.debug("Automatically found library files: %s" % tmp)

        # Prepend the path provided by the user in configuration files (if any).
        user_lib = read_user_library_path()
        if user_lib:
            tmp.insert(0, user_lib)

        # Deduplicate and convert string paths to LibraryPath objects
        return tuple(
            LibraryPath(library_path) for library_path in unique(tmp)
            if library_path is not None)